| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/conversation/chatstate" |
| 5 | "crypto/rand" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "time" |
| 9 | "unicode/utf8" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 12 | "gorm.io/gorm" |
| 13 | "gorm.io/gorm/clause" |
| 14 | ) |
| 15 | |
| 16 | type TaskAccess struct { |
| 17 | ID, TeamID, Requester string |
| 18 | Revision int64 |
| 19 | } |
| 20 | type Dependencies struct { |
| 21 | ContextSource ContextSource |
| 22 | ContextMessage func(*gorm.DB, CoordinatorClaim, Message) (bool, error) |
| 23 | CoordinatorAudit func(*gorm.DB, BindingRecord, string, string) error |
| 24 | Authorize func(*gorm.DB, kernel.Actor) (string, error) |
| 25 | Task func(*gorm.DB, kernel.Actor, string) (TaskAccess, error) |
| 26 | Audit func(*gorm.DB, kernel.Actor, string, string) error |
| 27 | NotFound, Conflict, Invalid, CursorExpired error |
| 28 | ProposedCopy, RoutedCopy string |
| 29 | } |
| 30 | type Store struct { |
| 31 | tx *gorm.DB |
| 32 | deps Dependencies |
| 33 | readOnly bool |
| 34 | cursorCodec kernel.CursorCodec |
| 35 | } |
| 36 | |
| 37 | func New(tx *gorm.DB, deps Dependencies) *Store { return &Store{tx: tx, deps: deps} } |
| 38 | func (s *Store) main(actor kernel.Actor) (Main, error) { |
| 39 | teamID, err := s.deps.Authorize(s.tx, actor) |
| 40 | if err != nil { |
| 41 | return Main{}, err |
| 42 | } |
| 43 | if s.readOnly { |
| 44 | return s.readMain(teamID, actor) |
| 45 | } |
| 46 | row := Main{ID: rand.Text(), TeamID: teamID, Person: actor.Address, Revision: 1} |
| 47 | if err = s.tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "team_id"}, {Name: "person"}}, DoNothing: true}).Create(&row).Error; err != nil { |
| 48 | return Main{}, err |
| 49 | } |
| 50 | row = Main{} |
| 51 | err = s.tx.Where("team_id=? AND person=?", teamID, actor.Address).First(&row).Error |
| 52 | return row, err |
| 53 | } |
| 54 | func (s *Store) Conversation(actor kernel.Actor, cursor string, limit int) (ConversationPage, error) { |
| 55 | row, err := s.main(actor) |
| 56 | if err != nil { |
| 57 | return ConversationPage{}, err |
| 58 | } |
| 59 | page, err := s.page(actor, row.ID, row.LastSequence, row.Revision, cursor, limit) |
| 60 | if err != nil { |
| 61 | return page, err |
| 62 | } |
| 63 | b, err := s.Binding(actor) |
| 64 | if errors.Is(err, s.deps.NotFound) { |
| 65 | return page, nil |
| 66 | } |
| 67 | if err != nil { |
| 68 | return page, err |
| 69 | } |
| 70 | |
| 71 | cards, err := chatstate.Status(s.tx, b.ID, b.Person, b.Generation) |
| 72 | page.Cards = append(page.Cards, cards...) |
| 73 | return page, err |
| 74 | } |
| 75 | func (s *Store) SendMessage(actor kernel.Actor, threadID, body string, m kernel.Mutation) (Message, error) { |
| 76 | if !m.Valid() || !utf8.ValidString(body) || len(body) < 1 || len(body) > 16384 { |
| 77 | return Message{}, s.deps.Invalid |
| 78 | } |
| 79 | var stream, mainID, tid string |
| 80 | var revision int64 |
| 81 | if threadID == "" { |
| 82 | row, err := s.main(actor) |
| 83 | if err != nil { |
| 84 | return Message{}, err |
| 85 | } |
| 86 | stream, mainID, revision = row.ID, row.ID, row.Revision |
| 87 | } else { |
| 88 | row, _, err := s.thread(actor, threadID) |
| 89 | if err != nil { |
| 90 | return Message{}, err |
| 91 | } |
| 92 | stream, tid, revision = row.ID, row.ID, row.Revision |
| 93 | } |
| 94 | hash, err := kernel.InputHash(struct { |
| 95 | Body string |
| 96 | Revision int64 |
| 97 | }{body, m.Revision}) |
| 98 | if err != nil { |
| 99 | return Message{}, err |
| 100 | } |
| 101 | req := requestRecord{Principal: actor.Address, Operation: "send", Resource: stream, RequestID: m.RequestID, InputHash: hash} |
| 102 | if saved, ok, err := s.replay(req); ok || err != nil { |
| 103 | return saved, err |
| 104 | } |
| 105 | if m.Revision != 0 && m.Revision != revision { |
| 106 | return Message{}, s.deps.Conflict |
| 107 | } |
| 108 | purpose := "discussion" |
| 109 | if mainID != "" { |
| 110 | purpose = "coordinator" |
| 111 | } |
| 112 | msg, err := s.appendMessage(stream, mainID, tid, "person", actor.Address, body, purpose) |
| 113 | if err != nil { |
| 114 | return Message{}, err |
| 115 | } |
| 116 | if err = s.deps.Audit(s.tx, actor, "conversation.send", msg.ID); err != nil { |
| 117 | return Message{}, err |
| 118 | } |
| 119 | return msg, s.save(req, msg) |
| 120 | } |
| 121 | func (s *Store) replay(req requestRecord) (Message, bool, error) { |
| 122 | var old requestRecord |
| 123 | err := s.tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", req.Principal, req.Operation, req.Resource, req.RequestID).First(&old).Error |
| 124 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 125 | return Message{}, false, nil |
| 126 | } |
| 127 | if err != nil { |
| 128 | return Message{}, false, err |
| 129 | } |
| 130 | if old.InputHash != req.InputHash { |
| 131 | return Message{}, true, s.deps.Conflict |
| 132 | } |
| 133 | var msg Message |
| 134 | err = json.Unmarshal([]byte(old.Result), &msg) |
| 135 | return msg, true, err |
| 136 | } |
| 137 | func (s *Store) save(req requestRecord, msg Message) error { |
| 138 | raw, err := json.Marshal(msg) |
| 139 | if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | req.Result = string(raw) |
| 143 | return s.tx.Create(&req).Error |
| 144 | } |
| 145 | func (s *Store) appendMessage(stream, mainID, tid, kind, author, body, purpose string) (Message, error) { |
| 146 | table := "conversations" |
| 147 | if tid != "" { |
| 148 | table = "conversation_threads" |
| 149 | } |
| 150 | // The caller owns a write transaction, so sequence allocation and insertion |
| 151 | // are serialized with replay, audit and outbox writes. |
| 152 | update := s.tx.Table(table).Where("id=?", stream).Select("last_sequence", "revision").Updates(map[string]any{"last_sequence": gorm.Expr("last_sequence+1"), "revision": gorm.Expr("revision+1")}) |
| 153 | if update.Error != nil { |
| 154 | return Message{}, update.Error |
| 155 | } |
| 156 | if update.RowsAffected != 1 { |
| 157 | return Message{}, s.deps.NotFound |
| 158 | } |
| 159 | var sequence int64 |
| 160 | if err := s.tx.Table(table).Select("last_sequence").Where("id=?", stream).Scan(&sequence).Error; err != nil { |
| 161 | return Message{}, err |
| 162 | } |
| 163 | row := messageRecord{ID: rand.Text(), StreamID: stream, Sequence: sequence, ConversationID: mainID, ThreadID: tid, AuthorKind: kind, AuthorID: author, Body: body, Revision: 1, CreatedAt: time.Now().UTC()} |
| 164 | if err := s.tx.Create(&row).Error; err != nil { |
| 165 | return Message{}, err |
| 166 | } |
| 167 | if err := s.tx.Create(&outboxRecord{MessageID: row.ID, StreamID: stream, Purpose: purpose}).Error; err != nil { |
| 168 | return Message{}, err |
| 169 | } |
| 170 | return row.message(), nil |
| 171 | } |
| 172 | func (s *Store) page(actor kernel.Actor, stream string, through, revision int64, cursor string, limit int) (ConversationPage, error) { |
| 173 | return s.pageAfter(actor, stream, through, revision, cursor, limit, 0) |
| 174 | } |
| 175 | func (s *Store) pageAfter(actor kernel.Actor, stream string, through, revision int64, cursor string, limit int, after int64) (ConversationPage, error) { |
| 176 | page := ConversationPage{Messages: []Message{}, Cards: []Card{}, Revision: revision} |
| 177 | if limit == 0 { |
| 178 | limit = 50 |
| 179 | } |
| 180 | if limit < 1 || limit > 100 { |
| 181 | return page, s.deps.Invalid |
| 182 | } |
| 183 | if !s.readOnly && cursor == "" { |
| 184 | if err := s.tx.Where("expires_at <= ?", time.Now().UTC()).Delete(&cursorRecord{}).Error; err != nil { |
| 185 | return page, err |
| 186 | } |
| 187 | } |
| 188 | if cursor != "" && s.readOnly { |
| 189 | var c cursorRecord |
| 190 | if err := s.cursorCodec.Open(actor.Address+"\x00stream:"+stream, cursor, &c); err != nil { |
| 191 | return page, s.deps.CursorExpired |
| 192 | } |
| 193 | after, through, page.Revision = c.After, c.Through, c.Revision |
| 194 | } else if cursor != "" { |
| 195 | var c cursorRecord |
| 196 | err := s.tx.Where("id=? AND principal=? AND stream_id=?", cursor, actor.Address, stream).First(&c).Error |
| 197 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 198 | return page, s.deps.NotFound |
| 199 | } |
| 200 | if err != nil { |
| 201 | return page, err |
| 202 | } |
| 203 | if !time.Now().Before(c.ExpiresAt) { |
| 204 | return page, s.deps.CursorExpired |
| 205 | } |
| 206 | after, through, page.Revision = c.After, c.Through, c.Revision |
| 207 | } |
| 208 | var rows []messageRecord |
| 209 | if err := s.tx.Where("stream_id=? AND sequence>? AND sequence<=?", stream, after, through).Order("sequence ASC").Limit(limit + 1).Find(&rows).Error; err != nil { |
| 210 | return page, err |
| 211 | } |
| 212 | more := len(rows) > limit |
| 213 | if more { |
| 214 | rows = rows[:limit] |
| 215 | } |
| 216 | for _, row := range rows { |
| 217 | page.Messages = append(page.Messages, row.message()) |
| 218 | } |
| 219 | if len(rows) > 0 { |
| 220 | end := rows[len(rows)-1].Sequence |
| 221 | var cards []cardRecord |
| 222 | if err := s.tx.Where("stream_id=? AND sequence>? AND sequence<=?", stream, after, end).Order("sequence ASC, id ASC").Find(&cards).Error; err != nil { |
| 223 | return page, err |
| 224 | } |
| 225 | for _, c := range cards { |
| 226 | if c.Kind != "task" { |
| 227 | switch c.Kind { |
| 228 | case "project_setup": |
| 229 | p, err := s.projectProposal(actor, c.ResourceID) |
| 230 | if err != nil { |
| 231 | return page, err |
| 232 | } |
| 233 | page.Cards = append(page.Cards, Card{Sequence: c.Sequence, ID: c.ID, Kind: c.Kind, ResourceID: p.ID, Revision: p.Revision}) |
| 234 | case "clarification": |
| 235 | var q QuestionRecord |
| 236 | if err := s.tx.Where("id=? AND person=?", c.ResourceID, actor.Address).First(&q).Error; err != nil { |
| 237 | return page, err |
| 238 | } |
| 239 | page.Cards = append(page.Cards, Card{Sequence: c.Sequence, ID: c.ID, Kind: c.Kind, ResourceID: q.ID, Revision: q.Revision}) |
| 240 | case "suggest_preference", "suggest_specialist", "suggest_playbook": |
| 241 | var msg messageRecord |
| 242 | if err := s.tx.Where("id=? AND conversation_id=?", c.ResourceID, stream).First(&msg).Error; err != nil { |
| 243 | return page, err |
| 244 | } |
| 245 | page.Cards = append(page.Cards, Card{Sequence: c.Sequence, ID: c.ID, Kind: c.Kind, ResourceID: msg.ID, Revision: msg.Revision}) |
| 246 | default: |
| 247 | return page, s.deps.Invalid |
| 248 | } |
| 249 | continue |
| 250 | } |
| 251 | task, err := s.deps.Task(s.tx, actor, c.ResourceID) |
| 252 | if err != nil { |
| 253 | return page, err |
| 254 | } |
| 255 | page.Cards = append(page.Cards, Card{Sequence: c.Sequence, ID: c.ID, Kind: c.Kind, ResourceID: task.ID, Revision: task.Revision}) |
| 256 | } |
| 257 | if more { |
| 258 | c := cursorRecord{ID: rand.Text(), Principal: actor.Address, StreamID: stream, After: end, Through: through, Revision: page.Revision, ExpiresAt: time.Now().UTC().Add(24 * time.Hour)} |
| 259 | if s.readOnly { |
| 260 | token, err := s.cursorCodec.Seal(actor.Address+"\x00stream:"+stream, struct{ After, Through, Revision int64 }{end, through, page.Revision}) |
| 261 | if err != nil { |
| 262 | return page, err |
| 263 | } |
| 264 | page.NextCursor = token |
| 265 | } else { |
| 266 | if err := s.tx.Create(&c).Error; err != nil { |
| 267 | return page, err |
| 268 | } |
| 269 | page.NextCursor = c.ID |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | return page, nil |
| 274 | } |
| 275 | |
| 276 | func (s *Store) SystemNote(conversationID, body string) error { |
| 277 | _, err := s.appendMessage(conversationID, conversationID, "", "system", "", body, "system") |
| 278 | return err |
| 279 | } |
| 280 | |