| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 5 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 6 | "crypto/rand" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "gorm.io/gorm" |
| 10 | "math" |
| 11 | "net/url" |
| 12 | ) |
| 13 | |
| 14 | type CoordinatorBinding = runnerproto.CoordinatorBinding |
| 15 | type CoordinatorTurn = runnerproto.CoordinatorTurn |
| 16 | type CoordinatorContext = runnerproto.CoordinatorContext |
| 17 | |
| 18 | type BindingRecord struct { |
| 19 | CoordinatorBinding `gorm:"embedded"` |
| 20 | TeamID string `gorm:"uniqueIndex:coordinator_person,priority:1"` |
| 21 | PersonKey string `gorm:"uniqueIndex:coordinator_person,priority:2"` |
| 22 | MemberRevision, ConnectionRevision int64 |
| 23 | } |
| 24 | |
| 25 | func (BindingRecord) TableName() string { return "coordinator_bindings" } |
| 26 | |
| 27 | type TurnRecord struct { |
| 28 | PartialSequence, PartialAt int64 |
| 29 | CoordinatorTurn `gorm:"embedded"` |
| 30 | TeamID string `gorm:"uniqueIndex:coordinator_active,priority:1,where:state='running'"` |
| 31 | Person string `gorm:"uniqueIndex:coordinator_active,priority:2,where:state='running'"` |
| 32 | BindingID, ConversationID string |
| 33 | Sequence, ProjectID, ProjectRevision, MemberRevision, ConnectionRevision int64 |
| 34 | PartialText, ReplyMessageID, SupersededBy, Claim, Selection, InputHash, DeliveryHash, SessionID string |
| 35 | JobID, AttemptID, Fence int64 |
| 36 | } |
| 37 | |
| 38 | func (TurnRecord) TableName() string { return "coordinator_turns" } |
| 39 | |
| 40 | type QuestionRecord struct { |
| 41 | ID string `gorm:"primaryKey"` |
| 42 | BindingID, TurnID, Person, RequestID, State, Payload string |
| 43 | Generation, Revision int64 |
| 44 | } |
| 45 | |
| 46 | func (QuestionRecord) TableName() string { return "coordinator_questions" } |
| 47 | func (s *Store) Binding(actor kernel.Actor) (BindingRecord, error) { |
| 48 | teamID, err := s.deps.Authorize(s.tx, actor) |
| 49 | if err != nil { |
| 50 | return BindingRecord{}, err |
| 51 | } |
| 52 | var b BindingRecord |
| 53 | err = s.tx.Where("team_id=? AND person_key=?", teamID, actor.Address).First(&b).Error |
| 54 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 55 | return b, s.deps.NotFound |
| 56 | } |
| 57 | if err == nil { |
| 58 | var wait requestRecord |
| 59 | err = s.tx.Where("principal=? AND operation='coordinator.waiting' AND resource=? AND request_id='current'", actor.Address, b.ID).First(&wait).Error |
| 60 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 61 | err = nil |
| 62 | } else if err == nil { |
| 63 | if err = json.Unmarshal([]byte(wait.Result), &b.WaitingTaskID); err == nil && b.WaitingTaskID != "" { |
| 64 | b.WaitingTaskURL = "/tasks/" + url.PathEscape(b.WaitingTaskID) |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | return b, err |
| 69 | } |
| 70 | func (s *Store) CoordinatorReplay(actor kernel.Actor, op, resource string, m kernel.Mutation, input, out any) (bool, error) { |
| 71 | if !m.Valid() { |
| 72 | return false, s.deps.Invalid |
| 73 | } |
| 74 | if _, err := s.deps.Authorize(s.tx, actor); err != nil { |
| 75 | return false, err |
| 76 | } |
| 77 | hash, err := kernel.InputHash(input) |
| 78 | if err != nil { |
| 79 | return false, err |
| 80 | } |
| 81 | var old requestRecord |
| 82 | err = s.tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", actor.Address, op, resource, m.RequestID).First(&old).Error |
| 83 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 84 | return false, nil |
| 85 | } |
| 86 | if err != nil { |
| 87 | return false, err |
| 88 | } |
| 89 | if old.InputHash != hash { |
| 90 | return false, s.deps.Conflict |
| 91 | } |
| 92 | return true, json.Unmarshal([]byte(old.Result), out) |
| 93 | } |
| 94 | func (s *Store) SaveCoordinatorResult(actor kernel.Actor, op, resource string, m kernel.Mutation, input, result any) error { |
| 95 | hash, err := kernel.InputHash(input) |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | raw, err := json.Marshal(result) |
| 100 | if err != nil { |
| 101 | return err |
| 102 | } |
| 103 | return s.tx.Create(&requestRecord{Principal: actor.Address, Operation: op, Resource: resource, RequestID: m.RequestID, InputHash: hash, Result: string(raw)}).Error |
| 104 | } |
| 105 | func (s *Store) QueueCoordinator(actor kernel.Actor, messageID string, project int64, m kernel.Mutation) (CoordinatorTurn, error) { |
| 106 | b, err := s.Binding(actor) |
| 107 | if err != nil { |
| 108 | return CoordinatorTurn{}, err |
| 109 | } |
| 110 | input := struct { |
| 111 | Message, Binding string |
| 112 | Generation, Project, Revision int64 |
| 113 | }{messageID, b.ID, b.Generation, project, m.Revision} |
| 114 | var out CoordinatorTurn |
| 115 | if ok, err := s.CoordinatorReplay(actor, "coordinator.queue", actor.Address, m, input, &out); ok || err != nil { |
| 116 | return out, err |
| 117 | } |
| 118 | var msg messageRecord |
| 119 | if err = s.tx.Where("id=? AND author_kind='person' AND author_id=? AND conversation_id<>''", messageID, actor.Address).First(&msg).Error; err != nil { |
| 120 | return out, err |
| 121 | } |
| 122 | var main Main |
| 123 | if err = s.tx.Where("id=? AND team_id=? AND person=?", msg.ConversationID, b.TeamID, actor.Address).First(&main).Error; err != nil { |
| 124 | return out, err |
| 125 | } |
| 126 | var old TurnRecord |
| 127 | err = s.tx.Where("message_id=? AND (state='delivered' OR generation=? OR superseded_by IN (SELECT id FROM coordinator_turns WHERE state='delivered'))", messageID, b.Generation).First(&old).Error |
| 128 | if err == nil { |
| 129 | return old.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.queue", actor.Address, m, input, old.CoordinatorTurn) |
| 130 | } |
| 131 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 132 | return out, err |
| 133 | } |
| 134 | hash, err := kernel.InputHash(input) |
| 135 | if err != nil { |
| 136 | return out, err |
| 137 | } |
| 138 | row := TurnRecord{CoordinatorTurn: CoordinatorTurn{ID: rand.Text(), MessageID: messageID, RequestID: m.RequestID, Generation: b.Generation, Revision: 1, State: "queued"}, TeamID: b.TeamID, Person: actor.Address, BindingID: b.ID, ConversationID: msg.ConversationID, Sequence: msg.Sequence, ProjectID: project, MemberRevision: b.MemberRevision, ConnectionRevision: b.ConnectionRevision, InputHash: hash} |
| 139 | if err = s.tx.Create(&row).Error; err != nil { |
| 140 | return out, err |
| 141 | } |
| 142 | if err = s.deps.CoordinatorAudit(s.tx, b, "coordinator.queue", row.ID); err != nil { |
| 143 | return out, err |
| 144 | } |
| 145 | return row.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.queue", actor.Address, m, input, row.CoordinatorTurn) |
| 146 | } |
| 147 | func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutation) (CoordinatorTurn, error) { |
| 148 | b, err := s.Binding(actor) |
| 149 | if err != nil { |
| 150 | return CoordinatorTurn{}, err |
| 151 | } |
| 152 | input := struct { |
| 153 | ID string |
| 154 | Revision int64 |
| 155 | }{id, m.Revision} |
| 156 | var out CoordinatorTurn |
| 157 | if ok, err := s.CoordinatorReplay(actor, "coordinator.retry", id, m, input, &out); ok || err != nil { |
| 158 | return out, err |
| 159 | } |
| 160 | var old TurnRecord |
| 161 | if err = s.tx.Where("id=? AND person=? AND team_id=?", id, actor.Address, b.TeamID).First(&old).Error; err != nil { |
| 162 | return out, err |
| 163 | } |
| 164 | if old.Revision != m.Revision { |
| 165 | return out, s.deps.Conflict |
| 166 | } |
| 167 | if old.State != "context_limit" && old.State != "context_unavailable" && old.State != "fenced" { |
| 168 | if old.State != "uncertain" || old.AttemptID == 0 { |
| 169 | return out, s.deps.Conflict |
| 170 | } |
| 171 | var n int64 |
| 172 | if err = s.tx.Table("attempts").Where("id=? AND containment='contained'", old.AttemptID).Count(&n).Error; err != nil { |
| 173 | return out, err |
| 174 | } |
| 175 | if n != 1 { |
| 176 | return out, s.deps.Conflict |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | if old.Revision == math.MaxInt64 { |
| 181 | return out, s.deps.Conflict |
| 182 | } |
| 183 | if err = s.tx.Model(&TurnRecord{}).Where("id=?", id).Select("state", "revision").Updates(map[string]any{"state": "superseded", "revision": old.Revision + 1}).Error; err != nil { |
| 184 | return out, err |
| 185 | } |
| 186 | hash, err := kernel.InputHash(input) |
| 187 | if err != nil { |
| 188 | return out, err |
| 189 | } |
| 190 | row := TurnRecord{CoordinatorTurn: CoordinatorTurn{ID: rand.Text(), MessageID: old.MessageID, RequestID: m.RequestID, Generation: b.Generation, Revision: 1, State: "queued"}, TeamID: b.TeamID, Person: actor.Address, BindingID: b.ID, ConversationID: old.ConversationID, Sequence: old.Sequence, ProjectID: old.ProjectID, MemberRevision: b.MemberRevision, ConnectionRevision: b.ConnectionRevision, InputHash: hash} |
| 191 | if err = s.tx.Create(&row).Error; err != nil { |
| 192 | return out, err |
| 193 | } |
| 194 | return row.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.retry", id, m, input, row.CoordinatorTurn) |
| 195 | } |
| 196 | |
| 197 | func (s *Store) clearCoordinatorWaiting(b BindingRecord) error { |
| 198 | var n int64 |
| 199 | if err := s.tx.Model(&requestRecord{}).Where("principal=? AND operation='coordinator.waiting' AND resource=?", b.Person, b.ID).Count(&n).Error; err != nil || n == 0 { |
| 200 | return err |
| 201 | } |
| 202 | if err := s.tx.Where("principal=? AND operation='coordinator.waiting' AND resource=?", b.Person, b.ID).Delete(&requestRecord{}).Error; err != nil { |
| 203 | return err |
| 204 | } |
| 205 | return s.tx.Model(&Main{}).Where("person=? AND team_id=?", b.Person, b.TeamID).Select("revision").Updates(map[string]any{"revision": gorm.Expr("revision+1")}).Error |
| 206 | } |
| 207 | |