| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/conversation" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | |
| 9 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 10 | "amadan.net/oficina/equipo/internal/runner" |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | "gorm.io/gorm" |
| 13 | ) |
| 14 | |
| 15 | type runnerEvent = conversation.EventRecord |
| 16 | |
| 17 | type runnerEventID struct { |
| 18 | RunnerID string `gorm:"primaryKey"` |
| 19 | EventID string `gorm:"primaryKey"` |
| 20 | EventKey string |
| 21 | } |
| 22 | |
| 23 | func (runnerEventID) TableName() string { return "runner_event_ids" } |
| 24 | |
| 25 | type runnerTimeline struct { |
| 26 | StreamKey string `gorm:"primaryKey"` |
| 27 | AssignmentID string `gorm:"index:runner_timeline_assignment"` |
| 28 | Epoch string |
| 29 | HighWater int64 |
| 30 | Blocked bool |
| 31 | Isolation string |
| 32 | } |
| 33 | |
| 34 | func (runnerTimeline) TableName() string { return "runner_timelines" } |
| 35 | |
| 36 | type runnerArtifactRequest struct { |
| 37 | AssignmentID string `gorm:"primaryKey"` |
| 38 | RequestID string `gorm:"primaryKey"` |
| 39 | PayloadHash string |
| 40 | ArtifactID int64 |
| 41 | } |
| 42 | |
| 43 | func (runnerArtifactRequest) TableName() string { return "runner_artifact_requests" } |
| 44 | func (s *Store) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, event runnerproto.Event) error { |
| 45 | if s.execution == nil { |
| 46 | return ErrUnavailable |
| 47 | } |
| 48 | return s.execution.IngestRunnerEvent(ctx, p, event) |
| 49 | } |
| 50 | func (e *Execution) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, event runnerproto.Event) error { |
| 51 | if event.Validate() != nil || ((event.Kind == "turn.completed" || event.Kind == "turn.failed") && (event.TurnID == "" || event.ActionID <= 0)) { |
| 52 | return ErrInvalid |
| 53 | } |
| 54 | return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 55 | if err := e.syncExposure(ctx, tx); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil { |
| 59 | return err |
| 60 | } |
| 61 | var a runnerAssignment |
| 62 | if err := tx.First(&a, "id=?", event.AssignmentID).Error; err != nil { |
| 63 | return storeError(err) |
| 64 | } |
| 65 | q := RunnerRequest{Version: 2, AssignmentID: event.AssignmentID, Scope: event.Scope, Handle: event.Handle, RequestID: event.ID, ActionID: event.ActionID} |
| 66 | if !binding(a, q) || a.TaskID != event.TaskID || a.RunnerID != p.RunnerID || a.Person != p.Person { |
| 67 | return ErrForbidden |
| 68 | } |
| 69 | value, err := assignmentValue(a) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | // Historical observations need current roster and runner authority, but a |
| 74 | // cancelled task must still accept corroborated completion accounting. |
| 75 | return e.ingestEventAt(ctx, tx, p, a, value, event) |
| 76 | }) |
| 77 | } |
| 78 | func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, p RunnerPrincipal, a runnerAssignment, value Assignment, event runnerproto.Event) error { |
| 79 | key, hash := event.DedupKey(), event.ContentHash() |
| 80 | var alias runnerEventID |
| 81 | err := tx.First(&alias, "runner_id=? AND event_id=?", a.RunnerID, event.ID).Error |
| 82 | if err == nil && alias.EventKey != key { |
| 83 | return ErrConflict |
| 84 | } |
| 85 | if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| 86 | return storeError(err) |
| 87 | } |
| 88 | var old runnerEvent |
| 89 | err = tx.First(&old, "key=?", key).Error |
| 90 | if err == nil { |
| 91 | if old.ContentHash != hash { |
| 92 | return ErrConflict |
| 93 | } |
| 94 | if alias.EventID == "" { |
| 95 | return storeError(tx.Create(&runnerEventID{RunnerID: a.RunnerID, EventID: event.ID, EventKey: key}).Error) |
| 96 | } |
| 97 | return nil |
| 98 | } |
| 99 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 100 | return storeError(err) |
| 101 | } |
| 102 | if event.Kind == "namespace.launch" || event.Kind == "namespace.owner" { |
| 103 | if _, err = e.assignmentCurrent(ctx, tx, p, a); err != nil { |
| 104 | return err |
| 105 | } |
| 106 | if a.State != "claimed" { |
| 107 | return ErrForbidden |
| 108 | } |
| 109 | if a.Kind == "step" { |
| 110 | if err = e.Core.ValidateHandle(ctx, event.Scope, event.Handle); err != nil { |
| 111 | return err |
| 112 | } |
| 113 | } else if !e.store.runnerClock.Now().Before(a.LeaseDeadline) { |
| 114 | return ErrForbidden |
| 115 | } |
| 116 | } |
| 117 | if e.validators.Events == nil { |
| 118 | return ErrUnavailable |
| 119 | } |
| 120 | raw, err := runnerproto.Marshal(event) |
| 121 | if err != nil { |
| 122 | return ErrInvalid |
| 123 | } |
| 124 | q := RunnerRequest{Version: 2, AssignmentID: a.ID, Scope: event.Scope, Handle: event.Handle, RequestID: event.ID, ActionID: event.ActionID, Event: raw} |
| 125 | if err = e.validators.Events(ctx, value, q); err != nil { |
| 126 | return err |
| 127 | } |
| 128 | if event.Kind == "turn_completed" || event.Kind == "turn_failed" || event.Kind == "turn.completed" || event.Kind == "turn.failed" { |
| 129 | if e.validators.Receipt == nil { |
| 130 | return ErrUnavailable |
| 131 | } |
| 132 | action, err := e.Core.GetAction(ctx, event.Scope, event.ActionID) |
| 133 | if err != nil { |
| 134 | return err |
| 135 | } |
| 136 | if action.Attempt != event.Handle.Attempt || action.Fence != event.Handle.Fence || action.Operation != team.OpProviderCall { |
| 137 | return ErrForbidden |
| 138 | } |
| 139 | receipt, err := e.validators.Receipt(ctx, value, q) |
| 140 | if err != nil { |
| 141 | return err |
| 142 | } |
| 143 | if err = e.recordVerifiedReceipt(ctx, tx, a, q, receipt); err != nil { |
| 144 | return err |
| 145 | } |
| 146 | } |
| 147 | event.Isolation = value.Selection.Isolation |
| 148 | event.Payload = runner.RedactJSON(event.Payload, nil) |
| 149 | iso, _ := json.Marshal(event.Isolation) |
| 150 | raw, err = json.Marshal(event) |
| 151 | if err != nil { |
| 152 | return ErrInvalid |
| 153 | } |
| 154 | row := runnerEvent{Key: key, AssignmentID: a.ID, StreamKey: event.StreamKey(), Epoch: event.Epoch, Sequence: event.Sequence, Kind: event.Kind, ContentHash: hash, Body: string(raw), Isolation: string(iso)} |
| 155 | if err = tx.Create(&row).Error; err != nil { |
| 156 | return storeError(err) |
| 157 | } |
| 158 | if err = tx.Create(&runnerEventID{RunnerID: a.RunnerID, EventID: event.ID, EventKey: key}).Error; err != nil { |
| 159 | return storeError(err) |
| 160 | } |
| 161 | if err = projectRunnerEvent(tx, event, string(iso)); err != nil { |
| 162 | return err |
| 163 | } |
| 164 | return appendAudit(tx, Actor{Address: a.Person}, "runner.event", key) |
| 165 | } |
| 166 | func projectRunnerEvent(tx *gorm.DB, event runnerproto.Event, iso string) error { |
| 167 | var row runnerTimeline |
| 168 | err := tx.First(&row, "stream_key=?", event.StreamKey()).Error |
| 169 | fresh := errors.Is(err, gorm.ErrRecordNotFound) |
| 170 | if err != nil && !fresh { |
| 171 | return storeError(err) |
| 172 | } |
| 173 | if fresh { |
| 174 | row = runnerTimeline{StreamKey: event.StreamKey(), AssignmentID: event.AssignmentID, Epoch: event.Epoch} |
| 175 | } |
| 176 | var historical team.IsolationSnapshot |
| 177 | if !fresh && json.Unmarshal([]byte(row.Isolation), &historical) != nil { |
| 178 | return ErrInvalid |
| 179 | } |
| 180 | var current team.IsolationSnapshot |
| 181 | if json.Unmarshal([]byte(iso), ¤t) != nil { |
| 182 | return ErrInvalid |
| 183 | } |
| 184 | merged, _ := json.Marshal(runnerproto.MergeIsolation(historical, current)) |
| 185 | row.Isolation = string(merged) |
| 186 | switch event.Kind { |
| 187 | case "timeline_gap": |
| 188 | row.Blocked = true |
| 189 | case "timeline_replacement": |
| 190 | row.Epoch = event.Epoch |
| 191 | row.HighWater = 0 |
| 192 | row.Blocked = true |
| 193 | case "timeline_ready": |
| 194 | if event.Epoch != row.Epoch { |
| 195 | return ErrConflict |
| 196 | } |
| 197 | row.Blocked = false |
| 198 | default: |
| 199 | if event.Sequence != nil { |
| 200 | if row.Epoch == "" { |
| 201 | row.Epoch = event.Epoch |
| 202 | } |
| 203 | if event.Epoch != row.Epoch { |
| 204 | row.Blocked = true |
| 205 | } else { |
| 206 | // Timeline pages may span sequences. Gaps are explicitly validated by the |
| 207 | // adapter; a monotonic high-water alone never establishes readiness. |
| 208 | if *event.Sequence > row.HighWater { |
| 209 | row.HighWater = *event.Sequence |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | if fresh { |
| 215 | return storeError(tx.Create(&row).Error) |
| 216 | } |
| 217 | return storeError(tx.Model(&runnerTimeline{}).Where("stream_key=?", row.StreamKey).Select("Epoch", "HighWater", "Blocked", "Isolation").Updates(&row).Error) |
| 218 | } |
| 219 | func runnerTimelineAvailable(tx *gorm.DB, assignment string) error { |
| 220 | var count int64 |
| 221 | if err := tx.Model(&runnerTimeline{}).Where("assignment_id=? AND blocked=?", assignment, true).Count(&count).Error; err != nil { |
| 222 | return storeError(err) |
| 223 | } |
| 224 | if count != 0 { |
| 225 | return ErrUnavailable |
| 226 | } |
| 227 | return nil |
| 228 | } |
| 229 | func (e *Execution) registerArtifactOnce(ctx context.Context, tx *gorm.DB, a runnerAssignment, q RunnerRequest) (team.Artifact, error) { |
| 230 | hash := runnerproto.EventHash(q.Artifact) |
| 231 | var old runnerArtifactRequest |
| 232 | err := tx.First(&old, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error |
| 233 | if err == nil { |
| 234 | if old.PayloadHash != hash { |
| 235 | return team.Artifact{}, ErrConflict |
| 236 | } |
| 237 | return e.Core.Artifact(ctx, q.Scope, team.ArtifactID(old.ArtifactID)) |
| 238 | } |
| 239 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 240 | return team.Artifact{}, storeError(err) |
| 241 | } |
| 242 | if e.validators.Artifact == nil { |
| 243 | return team.Artifact{}, ErrUnavailable |
| 244 | } |
| 245 | value, err := assignmentValue(a) |
| 246 | if err != nil { |
| 247 | return team.Artifact{}, err |
| 248 | } |
| 249 | if err = e.validators.Artifact(ctx, value, q); err != nil { |
| 250 | return team.Artifact{}, err |
| 251 | } |
| 252 | artifact, err := e.Core.Register(ctx, q.Scope, q.Handle, *q.Artifact) |
| 253 | if err != nil { |
| 254 | return team.Artifact{}, err |
| 255 | } |
| 256 | err = tx.Create(&runnerArtifactRequest{AssignmentID: a.ID, RequestID: q.RequestID, PayloadHash: hash, ArtifactID: int64(artifact.ID)}).Error |
| 257 | return artifact, storeError(err) |
| 258 | } |
| 259 | |
| 260 | func syncRunnerEventExposure(tx *gorm.DB, assignment string, iso team.IsolationSnapshot, revoked ...string) error { |
| 261 | expected, _ := json.Marshal(iso) |
| 262 | var events []runnerEvent |
| 263 | if err := tx.Where("assignment_id=? AND isolation!=?", assignment, string(expected)).Find(&events).Error; err != nil { |
| 264 | return storeError(err) |
| 265 | } |
| 266 | for _, row := range events { |
| 267 | var event runnerproto.Event |
| 268 | if err := json.Unmarshal([]byte(row.Body), &event); err != nil { |
| 269 | return err |
| 270 | } |
| 271 | event.Isolation = runnerproto.MergeIsolation(runnerproto.WithoutApproval(event.Isolation, revoked...), iso) |
| 272 | raw, _ := json.Marshal(event.Isolation) |
| 273 | body, _ := json.Marshal(event) |
| 274 | if row.Isolation == string(raw) && row.Body == string(body) { |
| 275 | continue |
| 276 | } |
| 277 | if err := tx.Model(&runnerEvent{}).Where("key=?", row.Key).Select("Isolation", "Body").Updates(&runnerEvent{Isolation: string(raw), Body: string(body)}).Error; err != nil { |
| 278 | return storeError(err) |
| 279 | } |
| 280 | } |
| 281 | var timelines []runnerTimeline |
| 282 | if err := tx.Where("assignment_id=? AND isolation!=?", assignment, string(expected)).Find(&timelines).Error; err != nil { |
| 283 | return storeError(err) |
| 284 | } |
| 285 | for _, row := range timelines { |
| 286 | var old team.IsolationSnapshot |
| 287 | if err := json.Unmarshal([]byte(row.Isolation), &old); err != nil { |
| 288 | return err |
| 289 | } |
| 290 | raw, _ := json.Marshal(runnerproto.MergeIsolation(runnerproto.WithoutApproval(old, revoked...), iso)) |
| 291 | if row.Isolation == string(raw) { |
| 292 | continue |
| 293 | } |
| 294 | if err := tx.Model(&runnerTimeline{}).Where("stream_key=?", row.StreamKey).Select("Isolation").Updates(&runnerTimeline{Isolation: string(raw)}).Error; err != nil { |
| 295 | return storeError(err) |
| 296 | } |
| 297 | } |
| 298 | return nil |
| 299 | } |
| 300 | |