| 1 | package conversation |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/conversation/chatstate" |
| 5 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 6 | "amadan.net/oficina/equipo/internal/equipo/ownermode" |
| 7 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 8 | "context" |
| 9 | "errors" |
| 10 | "gorm.io/gorm" |
| 11 | "gorm.io/gorm/clause" |
| 12 | "strconv" |
| 13 | ) |
| 14 | |
| 15 | func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]CoordinatorTurn, error) { |
| 16 | out := []CoordinatorTurn{} |
| 17 | var denied error |
| 18 | err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 19 | if err := e.RunnerCurrent(tx, p); err != nil { |
| 20 | return err |
| 21 | } |
| 22 | b, err := e.Conversation(tx).Binding(kernel.Actor{Address: p.Person}) |
| 23 | if err != nil && !errors.Is(err, e.NotFound) { |
| 24 | return err |
| 25 | } |
| 26 | if e.Rebind != nil { |
| 27 | b, err = e.Rebind(tx, kernel.Actor{Address: p.Person}, b) |
| 28 | if err != nil { |
| 29 | return err |
| 30 | } |
| 31 | } |
| 32 | if b.ID == "" { |
| 33 | return nil |
| 34 | } |
| 35 | if b.RunnerID != p.RunnerID { |
| 36 | return nil |
| 37 | } |
| 38 | var messages []struct{ ID string } |
| 39 | if err = tx.Table("conversation_messages m").Select("m.id").Joins("JOIN conversations c ON c.id=m.conversation_id").Where("c.person=? AND c.team_id=? AND m.author_kind='person' AND NOT EXISTS (SELECT 1 FROM coordinator_turns t WHERE t.message_id=m.id AND (t.state='delivered' OR t.generation=? OR t.superseded_by IN (SELECT id FROM coordinator_turns WHERE state='delivered')))", p.Person, b.TeamID, b.Generation).Order("m.sequence").Limit(50).Scan(&messages).Error; err != nil { |
| 40 | return err |
| 41 | } |
| 42 | for _, msg := range messages { |
| 43 | if _, err = e.Conversation(tx).QueueCoordinator(kernel.Actor{Address: p.Person}, msg.ID, 0, kernel.Mutation{RequestID: "message:" + msg.ID + ":" + strconv.FormatInt(b.Generation, 10)}); err != nil { |
| 44 | return err |
| 45 | } |
| 46 | } |
| 47 | if err := chatstate.Coalesce(tx, b.ID, b.Generation, func(id string) error { return e.Audit(tx, b, "coordinator.superseded", id) }); err != nil { |
| 48 | return err |
| 49 | } |
| 50 | var rows []TurnRecord |
| 51 | if err = tx.Where("binding_id=? AND generation=? AND state NOT IN ('delivered','superseded','fenced')", b.ID, b.Generation).Order("sequence").Limit(1).Find(&rows).Error; err != nil { |
| 52 | return err |
| 53 | } |
| 54 | for _, row := range rows { |
| 55 | if row.State == "running" || row.State == "uncertain" || row.State == "context_limit" || row.State == "context_unavailable" { |
| 56 | continue |
| 57 | } |
| 58 | if err := e.Core.AdmissionAvailable(ctx); err != nil { |
| 59 | return e.waitCoordinator(tx, b, row, "admission_denied") |
| 60 | } |
| 61 | blocked, err := ownermode.CoordinatorBlocked(tx, row.TeamID, row.Person, row.ID, row.Generation, row.Sequence) |
| 62 | if err != nil { |
| 63 | return err |
| 64 | } |
| 65 | if blocked { |
| 66 | continue |
| 67 | } |
| 68 | _, _, sel, err := e.Current(ctx, tx, p, row.ID) |
| 69 | if err != nil { |
| 70 | if errors.Is(err, e.Forbidden) { |
| 71 | denied = err |
| 72 | return e.waitCoordinator(tx, b, row, "admission_denied") |
| 73 | } |
| 74 | if errors.Is(err, e.WaitingConnection) { |
| 75 | return e.waitCoordinator(tx, b, row, "waiting_connection") |
| 76 | } |
| 77 | return err |
| 78 | } |
| 79 | if e.Defaults != nil { |
| 80 | if err = e.Defaults(ctx, tx, sel); err != nil { |
| 81 | return err |
| 82 | } |
| 83 | } |
| 84 | var busy int64 |
| 85 | if err = tx.Table("runner_assignments").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", p.Person, b.ConnectionID).Count(&busy).Error; err != nil { |
| 86 | return err |
| 87 | } |
| 88 | if busy > 0 { |
| 89 | return e.waitCoordinator(tx, b, row, "waiting_task") |
| 90 | } |
| 91 | if err = e.Core.CoordinatorAvailable(ctx, team.AccountID(b.TeamID), p.Person); err != nil { |
| 92 | if errors.Is(err, team.ErrBudget) { |
| 93 | return e.waitCoordinator(tx, b, row, "budget_needed") |
| 94 | } |
| 95 | return err |
| 96 | } |
| 97 | if err = e.Conversation(tx).clearCoordinatorWaiting(b); err != nil { |
| 98 | return err |
| 99 | } |
| 100 | out = append(out, row.CoordinatorTurn) |
| 101 | } |
| 102 | return nil |
| 103 | }) |
| 104 | if err == nil { |
| 105 | err = denied |
| 106 | } |
| 107 | return out, err |
| 108 | } |
| 109 | |
| 110 | func (e *Engine) waitCoordinator(tx *gorm.DB, b BindingRecord, row TurnRecord, state string) error { |
| 111 | var taskID string |
| 112 | if state == "waiting_task" { |
| 113 | if err := tx.Table("runner_assignments").Select("task_id").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", row.Person, b.ConnectionID).Order("id").Limit(1).Scan(&taskID).Error; err != nil { |
| 114 | return err |
| 115 | } |
| 116 | } |
| 117 | var prior requestRecord |
| 118 | err := tx.Where("principal=? AND operation='coordinator.waiting' AND resource=? AND request_id='current'", row.Person, b.ID).First(&prior).Error |
| 119 | if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| 120 | return err |
| 121 | } |
| 122 | result := string(mustCoordinatorJSON(taskID)) |
| 123 | changed := err != nil || prior.Result != result |
| 124 | if changed { |
| 125 | wait := requestRecord{Principal: row.Person, Operation: "coordinator.waiting", Resource: b.ID, RequestID: "current", Result: result} |
| 126 | if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "principal"}, {Name: "operation"}, {Name: "resource"}, {Name: "request_id"}}, DoUpdates: clause.AssignmentColumns([]string{"result"})}).Create(&wait).Error; err != nil { |
| 127 | return err |
| 128 | } |
| 129 | } |
| 130 | if row.State == state && !changed { |
| 131 | return nil |
| 132 | } |
| 133 | if err := tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": state}).Error; err != nil { |
| 134 | return err |
| 135 | } |
| 136 | if err := tx.Model(&Main{}).Where("id=?", row.ConversationID).Select("revision").Updates(map[string]any{"revision": gorm.Expr("revision+1")}).Error; err != nil { |
| 137 | return err |
| 138 | } |
| 139 | |
| 140 | return e.Audit(tx, b, "coordinator."+state, row.ID) |
| 141 | } |
| 142 | |