| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/wire" |
| 11 | "gorm.io/gorm" |
| 12 | ) |
| 13 | |
| 14 | // Lease is one runner connection's hold on its generation. Protocol is |
| 15 | // what the connection speaks; Role the runner's role. |
| 16 | type Lease struct { |
| 17 | Runner RunnerPrincipal |
| 18 | Generation int64 |
| 19 | Process string |
| 20 | Protocol int |
| 21 | Role string |
| 22 | // Tainted: the instance holds that a check ran outside the sandbox |
| 23 | // on this runner (told in every welcome). |
| 24 | Tainted bool |
| 25 | } |
| 26 | |
| 27 | // Connect grants a generation. A hello with generation 0 is a new runner |
| 28 | // process and supersedes any other; the current generation reconnects; an |
| 29 | // older one is refused so a stale process stops. observed is the |
| 30 | // address the connection was seen from (ObservedAddress; "" for none), |
| 31 | // recorded for a primary's site inventory. |
| 32 | func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string, hello wire.Hello, observed string) (Lease, error) { |
| 33 | // The lease names this one connection, so a replaced connection of the |
| 34 | // same generation (another instance process, a reconnect) is fenced. |
| 35 | lease := Lease{Runner: p, Process: process + "/" + newID("c"), Protocol: wire.Spoken(wire.HelloProtocol(hello))} |
| 36 | raw, _ := json.Marshal(cleanHello(hello)) |
| 37 | err := s.tx(ctx, func(t *txn) error { |
| 38 | if err := s.authority.CurrentRunner(t.db, p); err != nil { |
| 39 | return err |
| 40 | } |
| 41 | role, rerr := t.s.authority.RunnerRole(t.db, p.RunnerID) |
| 42 | if rerr != nil { |
| 43 | return rerr |
| 44 | } |
| 45 | lease.Role = role |
| 46 | if role == wire.RoleWorker && wire.WithoutWorkerConnections(&hello, lease.Protocol) { |
| 47 | // A worker below 37 holds no connection and publishes no seal |
| 48 | // key: what it says of either is not kept. |
| 49 | raw, _ = json.Marshal(cleanHello(hello)) |
| 50 | } |
| 51 | if hello.Capabilities != nil && hello.Capabilities.Tainted { |
| 52 | if err := t.markTainted(p.RunnerID); err != nil { |
| 53 | return err |
| 54 | } |
| 55 | } |
| 56 | tainted, terr := t.tainted(p.RunnerID) |
| 57 | if terr != nil { |
| 58 | return terr |
| 59 | } |
| 60 | lease.Tainted = tainted |
| 61 | // A protocol 1 runner is always a primary: a worker that cannot say |
| 62 | // what it is never connects. |
| 63 | if role == wire.RoleWorker && lease.Protocol < wire.Protocol2 { |
| 64 | return ErrForbidden |
| 65 | } |
| 66 | var r runnerSessionRecord |
| 67 | err := t.db.Where("runner_id = ?", p.RunnerID).First(&r).Error |
| 68 | fresh := errors.Is(err, gorm.ErrRecordNotFound) |
| 69 | if err != nil && !fresh { |
| 70 | return err |
| 71 | } |
| 72 | switch { |
| 73 | case hello.Generation != 0 && hello.Generation < r.Generation: |
| 74 | return ErrSuperseded |
| 75 | case hello.Generation != 0 && hello.Generation == r.Generation: |
| 76 | lease.Generation = r.Generation |
| 77 | default: |
| 78 | lease.Generation = max(r.Generation, hello.Generation) + 1 |
| 79 | } |
| 80 | r = runnerSessionRecord{RunnerID: p.RunnerID, Generation: lease.Generation, Connected: true, Process: lease.Process, Revision: r.Revision + 1, Hello: string(raw), SeenAt: t.now(), Protocol: lease.Protocol} |
| 81 | if fresh { |
| 82 | err = t.db.Create(&r).Error |
| 83 | } else { |
| 84 | err = t.db.Model(&runnerSessionRecord{}).Where("runner_id = ?", p.RunnerID).Select("*").Updates(&r).Error |
| 85 | } |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | if role == wire.RolePrimary { |
| 90 | if err := t.rebind(p); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | if err := t.reprepareBases(p.Person, p.RunnerID, lease.Protocol); err != nil { |
| 94 | return err |
| 95 | } |
| 96 | if err := t.reassignPublications(p.Person, p.RunnerID); err != nil { |
| 97 | return err |
| 98 | } |
| 99 | if err := t.reconcileOutbound(p.Person, p.RunnerID); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | if err := t.reconcileUnpublished(p.Person, p.RunnerID); err != nil { |
| 103 | return err |
| 104 | } |
| 105 | } |
| 106 | // The Assistant: nor its turns, below protocol 19. |
| 107 | if err := t.fenceLanes(lease); err != nil { |
| 108 | return err |
| 109 | } |
| 110 | if primary, err := t.s.authority.PrimaryRunner(t.db, p.Person); err != nil { |
| 111 | return err |
| 112 | } else if primary == p.RunnerID { |
| 113 | if err := t.resolveAccess(p.Person, hello); err != nil { |
| 114 | return err |
| 115 | } |
| 116 | if err := t.helloConnections(lease, hello.Connections, true); err != nil { |
| 117 | return err |
| 118 | } |
| 119 | } else if err := t.workerHello(lease, hello, true); err != nil { |
| 120 | return err |
| 121 | } |
| 122 | if err := t.runnerEvent(p.Person, r); err != nil { |
| 123 | return err |
| 124 | } |
| 125 | // Merge authority: an older runner holds no automatic merge. |
| 126 | if err := t.fenceOldRunner(lease); err != nil { |
| 127 | return err |
| 128 | } |
| 129 | // Previews: an older runner holds none. |
| 130 | if err := t.fencePreviews(lease); err != nil { |
| 131 | return err |
| 132 | } |
| 133 | // Nor a site publish, below protocol 16. |
| 134 | if err := t.fencePublishes(lease); err != nil { |
| 135 | return err |
| 136 | } |
| 137 | // Research: nor does a runner below protocol 13. |
| 138 | if err := t.fenceCopy(lease); err != nil { |
| 139 | return err |
| 140 | } |
| 141 | if err := t.fenceResearch(lease); err != nil { |
| 142 | return err |
| 143 | } |
| 144 | // A primary's detected addresses, for Research's site inventory; |
| 145 | // its steps waiting for the inventory are looked at again. |
| 146 | if role == wire.RolePrimary { |
| 147 | if err := t.recordAddresses(lease, hello, &observed); err != nil { |
| 148 | return err |
| 149 | } |
| 150 | } |
| 151 | // A runner that fits may have come online. |
| 152 | if err := t.resumeMoves(p.Person); err != nil { |
| 153 | return err |
| 154 | } |
| 155 | if err := t.placeWaiting(p.Person); err != nil { |
| 156 | return err |
| 157 | } |
| 158 | if err := t.recheckMacEngineering(p.RunnerID); err != nil { |
| 159 | return err |
| 160 | } |
| 161 | return t.recheckMac(p.Person, p.RunnerID) |
| 162 | }) |
| 163 | return lease, err |
| 164 | } |
| 165 | |
| 166 | // runnerEvent tells the person about one of their runners, each runner |
| 167 | // by its own id. |
| 168 | func (t *txn) runnerEvent(person string, r runnerSessionRecord) error { |
| 169 | rs, err := t.runners(person) |
| 170 | if err != nil { |
| 171 | return err |
| 172 | } |
| 173 | for _, info := range rs { |
| 174 | if info.ID == r.RunnerID { |
| 175 | v := runnerView(info) |
| 176 | v.Online = r.Connected |
| 177 | return t.event("", person, wire.EventRunner, "runner", r.RunnerID, r.Revision, "", "", 0, v) |
| 178 | } |
| 179 | } |
| 180 | return nil |
| 181 | } |
| 182 | |
| 183 | // current checks, inside a write, that this lease still holds the |
| 184 | // generation and the credential and owner are still valid. |
| 185 | func (t *txn) current(l Lease) (runnerSessionRecord, error) { |
| 186 | if err := t.s.authority.CurrentRunner(t.db, l.Runner); err != nil { |
| 187 | return runnerSessionRecord{}, err |
| 188 | } |
| 189 | var r runnerSessionRecord |
| 190 | if err := t.db.Where("runner_id = ?", l.Runner.RunnerID).First(&r).Error; err != nil { |
| 191 | return r, err |
| 192 | } |
| 193 | if r.Generation != l.Generation || r.Process != l.Process { |
| 194 | return r, ErrSuperseded |
| 195 | } |
| 196 | return r, nil |
| 197 | } |
| 198 | |
| 199 | // Confirm answers a runner's lease check before it executes: this |
| 200 | // connection still holds the generation and the credential is valid. |
| 201 | func (s *Store) Confirm(ctx context.Context, l Lease) error { |
| 202 | return s.tx(ctx, func(t *txn) error { _, err := t.current(l); return err }) |
| 203 | } |
| 204 | |
| 205 | // Heartbeat records a repeated hello. |
| 206 | func (s *Store) Heartbeat(ctx context.Context, l Lease, hello wire.Hello) error { |
| 207 | if l.Role == wire.RoleWorker { |
| 208 | wire.WithoutWorkerConnections(&hello, l.Protocol) |
| 209 | } |
| 210 | raw, _ := json.Marshal(cleanHello(hello)) |
| 211 | return s.tx(ctx, func(t *txn) error { |
| 212 | r, err := t.current(l) |
| 213 | if err != nil { |
| 214 | return err |
| 215 | } |
| 216 | online := r.Connected && t.now().Sub(r.SeenAt) < runnerOnline |
| 217 | // A Mac whose sandbox is proven now: checks waiting for it run. |
| 218 | proven := helloSandbox(r.Hello) != wire.SandboxSeatbelt && helloSandbox(string(raw)) == wire.SandboxSeatbelt |
| 219 | // A Mac whose readiness for Engineering moved (its tags or its |
| 220 | // Engineering status): Mac Engineering waiting for it is placed |
| 221 | // again. |
| 222 | macMoved := helloEngineering(r.Hello) != helloEngineering(string(raw)) |
| 223 | // Previews on now (the first hello never says so): approved |
| 224 | // candidates without a preview get one. |
| 225 | previewsOn := !helloPreviews(r.Hello) && hello.Capabilities != nil && hello.Capabilities.Previews |
| 226 | r.Hello, r.SeenAt, r.Connected = string(raw), t.now(), true |
| 227 | if !online { |
| 228 | r.Revision++ |
| 229 | } |
| 230 | if hello.Capabilities != nil && hello.Capabilities.Tainted { |
| 231 | if err := t.markTainted(r.RunnerID); err != nil { |
| 232 | return err |
| 233 | } |
| 234 | } |
| 235 | if err = t.db.Model(&runnerSessionRecord{}).Where("runner_id = ?", r.RunnerID).Select("hello", "seen_at", "connected", "revision").Updates(&r).Error; err != nil { |
| 236 | return err |
| 237 | } |
| 238 | if primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person); err != nil { |
| 239 | return err |
| 240 | } else if primary == l.Runner.RunnerID { |
| 241 | if err := t.resolveAccess(l.Runner.Person, hello); err != nil { |
| 242 | return err |
| 243 | } |
| 244 | if err := t.helloConnections(l, hello.Connections, true); err != nil { |
| 245 | return err |
| 246 | } |
| 247 | if err := t.recordAddresses(l, hello, nil); err != nil { |
| 248 | return err |
| 249 | } |
| 250 | if previewsOn { |
| 251 | if err := t.reschedulePreviews(l.Runner.Person); err != nil { |
| 252 | return err |
| 253 | } |
| 254 | } |
| 255 | // An older primary asks for no start authorization: its queued |
| 256 | // Engineering is looked at again with each catalog it sends. |
| 257 | if hello.Protocol < wire.Protocol2 { |
| 258 | if err := t.recheckMacEngineering(l.Runner.RunnerID); err != nil { |
| 259 | return err |
| 260 | } |
| 261 | } |
| 262 | } else if err := t.workerHello(l, hello, false); err != nil { |
| 263 | return err |
| 264 | } |
| 265 | if !online { |
| 266 | if err := t.runnerEvent(l.Runner.Person, r); err != nil { |
| 267 | return err |
| 268 | } |
| 269 | } |
| 270 | if err := t.resumeMoves(l.Runner.Person); err != nil { |
| 271 | return err |
| 272 | } |
| 273 | if !online || proven || macMoved { |
| 274 | if err := t.placeWaiting(l.Runner.Person); err != nil { |
| 275 | return err |
| 276 | } |
| 277 | return t.recheckMac(l.Runner.Person, l.Runner.RunnerID) |
| 278 | } |
| 279 | return nil |
| 280 | }) |
| 281 | } |
| 282 | |
| 283 | // Disconnect marks the runner offline if this lease still holds it. |
| 284 | func (s *Store) Disconnect(ctx context.Context, l Lease) error { |
| 285 | return s.tx(ctx, func(t *txn) error { |
| 286 | var r runnerSessionRecord |
| 287 | if err := t.db.Where("runner_id = ?", l.Runner.RunnerID).First(&r).Error; err != nil { |
| 288 | return err |
| 289 | } |
| 290 | if r.Generation != l.Generation || r.Process != l.Process || !r.Connected { |
| 291 | return nil |
| 292 | } |
| 293 | r.Connected = false |
| 294 | r.Revision++ |
| 295 | if err := t.db.Model(&runnerSessionRecord{}).Where("runner_id = ?", r.RunnerID).Select("connected", "revision").Updates(&r).Error; err != nil { |
| 296 | return err |
| 297 | } |
| 298 | return t.runnerEvent(l.Runner.Person, r) |
| 299 | }) |
| 300 | } |
| 301 | |
| 302 | // Pending returns the unacked commands addressed to this lease's runner |
| 303 | // after seq, and only those: a worker never sees the primary's work, nor |
| 304 | // the primary a worker's. |
| 305 | func (s *Store) Pending(ctx context.Context, l Lease, after int64) (out []wire.Frame, last int64, err error) { |
| 306 | last = after |
| 307 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 308 | var session runnerSessionRecord |
| 309 | if err := tx.Where("runner_id = ?", l.Runner.RunnerID).First(&session).Error; err != nil { |
| 310 | return err |
| 311 | } |
| 312 | if session.Generation != l.Generation || session.Process != l.Process { |
| 313 | return ErrSuperseded |
| 314 | } |
| 315 | var rows []commandRecord |
| 316 | if err := tx.Where("runner_id = ? AND person = ? AND acked_at IS NULL AND seq > ?", l.Runner.RunnerID, l.Runner.Person, after).Order("seq").Limit(100).Find(&rows).Error; err != nil { |
| 317 | return err |
| 318 | } |
| 319 | for _, r := range rows { |
| 320 | body := r.Body |
| 321 | if l.Role == wire.RoleWorker && l.Protocol < wire.ProtocolMacEngineering && wire.ConnectionCommands[r.Kind] { |
| 322 | // A worker below 37 is given nothing of its connections; |
| 323 | // the command waits, unacked, for a connection at 37. |
| 324 | last = r.Seq |
| 325 | continue |
| 326 | } |
| 327 | if r.Kind == wire.FrameAttachment { |
| 328 | // The chunk's bytes come from the stored file as it goes. |
| 329 | if body, err = hydrate(tx, body); err != nil { |
| 330 | return err |
| 331 | } |
| 332 | } |
| 333 | out = append(out, wire.Frame{ID: commandID(r.Seq), Type: r.Kind, Data: json.RawMessage(body)}) |
| 334 | last = r.Seq |
| 335 | } |
| 336 | return nil |
| 337 | }) |
| 338 | return out, last, err |
| 339 | } |
| 340 | |
| 341 | func commandID(seq int64) string { return "c" + strconv.FormatInt(seq, 10) } |
| 342 | |
| 343 | func commandSeq(id string) (int64, bool) { |
| 344 | if !strings.HasPrefix(id, "c") { |
| 345 | return 0, false |
| 346 | } |
| 347 | seq, err := strconv.ParseInt(id[1:], 10, 64) |
| 348 | return seq, err == nil && seq > 0 |
| 349 | } |
| 350 | |
| 351 | // Apply commits one runner frame and its effect exactly once. The caller |
| 352 | // acks a durable frame only after Apply returns nil. |
| 353 | func (s *Store) Apply(ctx context.Context, l Lease, f wire.Frame, body any) error { |
| 354 | return s.tx(ctx, func(t *txn) error { |
| 355 | if _, err := t.current(l); err != nil { |
| 356 | return err |
| 357 | } |
| 358 | if f.Durable() { |
| 359 | res := t.db.Exec("INSERT INTO runner_inbox(runner_id, frame_id, seen_at) VALUES (?,?,?) ON CONFLICT DO NOTHING", l.Runner.RunnerID, f.ID, t.now()) |
| 360 | if res.Error != nil { |
| 361 | return res.Error |
| 362 | } |
| 363 | if res.RowsAffected == 0 { |
| 364 | return nil |
| 365 | } |
| 366 | } |
| 367 | switch v := body.(type) { |
| 368 | case *wire.AccessReport: |
| 369 | return t.accessReport(l, v) |
| 370 | case *wire.Ack: |
| 371 | return t.ack(l, v.ID) |
| 372 | case *wire.DeltaReport: |
| 373 | return t.delta(l, v) |
| 374 | case *wire.GlanceReport: |
| 375 | return t.glance(l, v) |
| 376 | case *wire.Reply: |
| 377 | return t.reply(l, v) |
| 378 | case *wire.TurnReport: |
| 379 | return t.report(l, v) |
| 380 | case *wire.Sync: |
| 381 | return t.sync(l, v) |
| 382 | case *wire.ToolCall: |
| 383 | return t.toolCall(l, v) |
| 384 | case *wire.ActivityReport: |
| 385 | return t.activity(l, v) |
| 386 | case *wire.MoveIn: |
| 387 | return t.moveIn(l, v) |
| 388 | case *wire.NotebookReport: |
| 389 | return t.notebookReport(l, v) |
| 390 | case *wire.StepReport: |
| 391 | // A Design attempt's render records are kept first, as |
| 392 | // plain data (design_renders.go). |
| 393 | if err := t.keepRenders(l, v); err != nil { |
| 394 | return err |
| 395 | } |
| 396 | return t.stepReport(l, v) |
| 397 | case *wire.MergedReport: |
| 398 | return t.merged(l, v) |
| 399 | case *wire.AnswerReport: |
| 400 | return t.answer(l, v) |
| 401 | case *wire.BranchReport: |
| 402 | return t.branchMoved(l, v) |
| 403 | case *wire.Blob: |
| 404 | return t.blob(l, v) |
| 405 | case *wire.PublishedReport: |
| 406 | return t.published(l, v) |
| 407 | case *wire.BaseReport: |
| 408 | return t.base(l, v) |
| 409 | case *wire.ConnectionReport: |
| 410 | return t.connectionReport(l, v) |
| 411 | case *wire.UsageReport: |
| 412 | return t.usageReport(l, v) |
| 413 | case *wire.StepActivityReport: |
| 414 | return t.stepActivity(l, v) |
| 415 | case *wire.ChangeDiffUpload: |
| 416 | return t.changeDiff(l, v) |
| 417 | case *wire.ResearchFile: |
| 418 | return t.researchFile(l, v) |
| 419 | case *wire.RenderFile: |
| 420 | return t.renderFile(l, v) |
| 421 | } |
| 422 | return ErrInvalid |
| 423 | }) |
| 424 | } |
| 425 | |
| 426 | func (t *txn) ownTurn(l Lease, id string) (turnRecord, error) { |
| 427 | var r turnRecord |
| 428 | if err := t.db.Where("id = ? AND person = ?", id, l.Runner.Person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 429 | return r, ErrNotFound |
| 430 | } else if err != nil { |
| 431 | return r, err |
| 432 | } |
| 433 | primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| 434 | if err != nil { |
| 435 | return r, err |
| 436 | } |
| 437 | if primary != l.Runner.RunnerID { |
| 438 | return r, ErrForbidden |
| 439 | } |
| 440 | return r, nil |
| 441 | } |
| 442 | |
| 443 | func (t *txn) ack(l Lease, id string) error { |
| 444 | seq, ok := commandSeq(id) |
| 445 | if !ok { |
| 446 | return ErrInvalid |
| 447 | } |
| 448 | // Only the runner a command was addressed to may ack it (Apply has |
| 449 | // checked this connection holds its generation and process). |
| 450 | var c commandRecord |
| 451 | if err := t.db.Where("runner_id = ? AND person = ? AND acked_at IS NULL AND seq = ?", l.Runner.RunnerID, l.Runner.Person, seq).First(&c).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 452 | return nil |
| 453 | } else if err != nil { |
| 454 | return err |
| 455 | } |
| 456 | now := t.now() |
| 457 | if err := t.db.Model(&commandRecord{}).Where("seq = ?", c.Seq).Update("acked_at", now).Error; err != nil { |
| 458 | return err |
| 459 | } |
| 460 | if c.Kind == wire.FrameBlob { |
| 461 | return t.blobAcked(c.Body) |
| 462 | } |
| 463 | if c.Kind == wire.FrameBudget { |
| 464 | return t.budgetAcked(c.Body) |
| 465 | } |
| 466 | // A models frame's ack is receipt only (a runner acks a set it |
| 467 | // refuses too): its hello says which set it applied (§16.1). |
| 468 | if c.Kind == wire.FrameSecret { |
| 469 | // The runner holds the secret now: the box leaves the mailbox |
| 470 | // (only WAL and backup residue can remain, spec §2.4). |
| 471 | return t.db.Model(&commandRecord{}).Where("seq = ?", c.Seq).Update("body", "{}").Error |
| 472 | } |
| 473 | if c.Kind != wire.FrameMessage { |
| 474 | return nil |
| 475 | } |
| 476 | var m wire.MessageCommand |
| 477 | if err := json.Unmarshal([]byte(c.Body), &m); err != nil { |
| 478 | return err |
| 479 | } |
| 480 | r, err := t.ownTurn(l, m.TurnID) |
| 481 | if err != nil { |
| 482 | return err |
| 483 | } |
| 484 | if r.State != wire.TurnQueued { |
| 485 | return nil |
| 486 | } |
| 487 | r.State = wire.TurnRunning |
| 488 | if r.DispatchedAt != nil { |
| 489 | raw, _ := json.Marshal(wire.TurnTiming{QueuedMs: now.Sub(*r.DispatchedAt).Milliseconds()}) |
| 490 | r.Timing = string(raw) |
| 491 | } |
| 492 | return t.saveTurn(&r) |
| 493 | } |
| 494 | |
| 495 | func (t *txn) delta(l Lease, d *wire.DeltaReport) error { |
| 496 | if isQuestionID(d.TurnID) { |
| 497 | return t.questionDelta(l, d) |
| 498 | } |
| 499 | r, err := t.ownTurn(l, d.TurnID) |
| 500 | if errors.Is(err, ErrNotFound) { |
| 501 | return nil |
| 502 | } |
| 503 | if err != nil { |
| 504 | return err |
| 505 | } |
| 506 | if wire.Terminal(r.State) || d.Attempt != r.Attempt || d.Offset < 0 || d.Text == "" || len(d.Text) > wire.MaxMessageBytes { |
| 507 | return nil |
| 508 | } |
| 509 | return t.event(r.Lane, r.Person, wire.EventDelta, "turn", r.ID, 0, r.ID, "", r.Attempt, wire.Delta{TurnID: r.ID, Offset: d.Offset, Text: d.Text}) |
| 510 | } |
| 511 | |
| 512 | // glance publishes an Assistant turn's instant first line to the |
| 513 | // Assistant's streams following now: a glance event, revision 0 and no |
| 514 | // cursor, never stored as a message or an event, so no snapshot or |
| 515 | // replay holds it. It goes only for a live Assistant |
| 516 | // person turn at its attempt, from the person's primary runner speaking |
| 517 | // protocol 23, and only when its text is already one clean line |
| 518 | // (wire.GlanceText), and before the turn's first delta. Anything else is |
| 519 | // dropped, quietly: a glance is a |
| 520 | // nicety, never worth the runner's stream. |
| 521 | func (t *txn) glance(l Lease, g *wire.GlanceReport) error { |
| 522 | if l.Protocol < wire.ProtocolGlance { |
| 523 | return nil |
| 524 | } |
| 525 | text, ok := wire.GlanceText(g.Text) |
| 526 | if !ok || text != g.Text { |
| 527 | return nil |
| 528 | } |
| 529 | r, err := t.ownTurn(l, g.TurnID) |
| 530 | if errors.Is(err, ErrNotFound) || errors.Is(err, ErrForbidden) { |
| 531 | return nil |
| 532 | } |
| 533 | if err != nil { |
| 534 | return err |
| 535 | } |
| 536 | if r.Lane != wire.LaneAssistant || r.Kind != wire.TurnPerson || wire.Terminal(r.State) || g.Attempt != r.Attempt { |
| 537 | return nil |
| 538 | } |
| 539 | // The reply began: its words already replace the glance. |
| 540 | var streamed int64 |
| 541 | if err := t.db.Model(&eventRecord{}).Where("person = ? AND lane = ? AND type = ? AND body LIKE ?", r.Person, r.Lane, wire.EventDelta, `%"turn_id":"`+r.ID+`"%`).Count(&streamed).Error; err != nil { |
| 542 | return err |
| 543 | } |
| 544 | if streamed > 0 { |
| 545 | return nil |
| 546 | } |
| 547 | data, err := json.Marshal(wire.Glance{TurnID: r.ID, Text: text}) |
| 548 | if err != nil { |
| 549 | return err |
| 550 | } |
| 551 | // Live only: it goes to the streams following now and nowhere else, |
| 552 | // with no cursor, so nothing stores or replays it. |
| 553 | t.live = append(t.live, liveEvent{person: r.Person, lane: r.Lane, event: wire.Event{Type: wire.EventGlance, Resource: "turn", ID: r.ID, TurnID: r.ID, Attempt: r.Attempt, Data: data}}) |
| 554 | return nil |
| 555 | } |
| 556 | |
| 557 | // reply commits the coordinator's message, ends the turn and starts the |
| 558 | // next queued turn. Only forward transitions are accepted. |
| 559 | func (t *txn) reply(l Lease, v *wire.Reply) error { |
| 560 | r, err := t.ownTurn(l, v.TurnID) |
| 561 | if err != nil { |
| 562 | return err |
| 563 | } |
| 564 | if wire.Terminal(r.State) || v.Attempt < r.Attempt { |
| 565 | return nil |
| 566 | } |
| 567 | if len(v.Text) > 4*wire.MaxMessageBytes { |
| 568 | v.Text = v.Text[:4*wire.MaxMessageBytes] |
| 569 | } |
| 570 | r.State, r.Reason, r.Attempt = wire.TurnReplied, "", v.Attempt |
| 571 | for _, u := range v.Usage { |
| 572 | r.Connection = u.Connection |
| 573 | } |
| 574 | if err := t.recordUsage(l, r.Person, "coordinator", "", "", r.ID, 0, v.Usage); err != nil { |
| 575 | return err |
| 576 | } |
| 577 | // A move-in or explore turn with nothing to say posts nothing. |
| 578 | if !quietReply(r, v.Text) { |
| 579 | role := wire.RoleCoordinator |
| 580 | if r.Lane == wire.LaneAssistant { |
| 581 | role = wire.RoleAssistant |
| 582 | } |
| 583 | m := messageRecord{ID: newID("m_"), Person: r.Person, IdempotencyKey: "reply:" + r.ID, Role: role, Text: v.Text, TurnID: r.ID, Revision: 1, CreatedAt: t.now(), Switched: asJSON(v.Switched), Lane: r.Lane} |
| 584 | if err = t.db.Create(&m).Error; err != nil { |
| 585 | return err |
| 586 | } |
| 587 | if err = t.messageEvent(m); err != nil { |
| 588 | return err |
| 589 | } |
| 590 | r.ReplyID = m.ID |
| 591 | } |
| 592 | if v.Timing != nil { |
| 593 | var queued wire.TurnTiming |
| 594 | _ = json.Unmarshal([]byte(r.Timing), &queued) |
| 595 | timing := *v.Timing |
| 596 | timing.QueuedMs = queued.QueuedMs |
| 597 | raw, _ := json.Marshal(timing) |
| 598 | r.Timing = string(raw) |
| 599 | } |
| 600 | if err = t.saveTurn(&r); err != nil { |
| 601 | return err |
| 602 | } |
| 603 | if err = t.kindReplied(r); err != nil { |
| 604 | return err |
| 605 | } |
| 606 | return t.dispatchNext(r.Person, r.Lane) |
| 607 | } |
| 608 | |
| 609 | // waitReasons say why a turn waits: its connection was limited or |
| 610 | // refused its credential (between attempts), or nothing can answer. |
| 611 | var waitReasons = map[string]bool{"limited": true, "sign_in_again": true, wire.ReasonNoConnection: true} |
| 612 | |
| 613 | func (t *txn) report(l Lease, v *wire.TurnReport) error { |
| 614 | if !wire.Reasons[v.Reason] { |
| 615 | return ErrInvalid |
| 616 | } |
| 617 | r, err := t.ownTurn(l, v.TurnID) |
| 618 | if err != nil { |
| 619 | return err |
| 620 | } |
| 621 | if wire.Terminal(r.State) || v.Attempt < r.Attempt { |
| 622 | return nil |
| 623 | } |
| 624 | switch v.State { |
| 625 | case wire.TurnRunning, wire.TurnWaiting: |
| 626 | // Running again on a new attempt (recovery, a failover), held for a |
| 627 | // connection (waiting, no_connection), or going again (running). |
| 628 | if v.State == wire.TurnRunning && v.Reason != "" || v.State == wire.TurnWaiting && !waitReasons[v.Reason] { |
| 629 | return ErrInvalid |
| 630 | } |
| 631 | if v.Attempt == r.Attempt && r.State == v.State { |
| 632 | return nil |
| 633 | } |
| 634 | r.State, r.Attempt, r.Reason = v.State, v.Attempt, v.Reason |
| 635 | return t.saveTurn(&r) |
| 636 | case wire.TurnFailed, wire.TurnCancelled: |
| 637 | r.State, r.Reason, r.Attempt = v.State, v.Reason, v.Attempt |
| 638 | if r.Reason == "" { |
| 639 | r.Reason = v.State |
| 640 | } |
| 641 | if v.State == wire.TurnCancelled && r.Yield { |
| 642 | r.Reason = wire.ReasonYielded |
| 643 | } |
| 644 | if err = t.saveTurn(&r); err != nil { |
| 645 | return err |
| 646 | } |
| 647 | if err = t.kindEnded(r); err != nil { |
| 648 | return err |
| 649 | } |
| 650 | return t.dispatchNext(r.Person, r.Lane) |
| 651 | } |
| 652 | return ErrInvalid |
| 653 | } |
| 654 | |
| 655 | // sync reconciles after a reconnect: a turn the instance thinks is running |
| 656 | // that the runner no longer holds has failed visibly. |
| 657 | func (t *txn) sync(l Lease, v *wire.Sync) error { |
| 658 | // Each runner settles only its own steps and questions. |
| 659 | if err := t.syncSteps(l, v.Steps); err != nil { |
| 660 | return err |
| 661 | } |
| 662 | if err := t.syncQuestions(l, v.Asks); err != nil { |
| 663 | return err |
| 664 | } |
| 665 | // Only the person's primary runner holds their turns and questions; |
| 666 | // another of their runners must not fail the primary's work. |
| 667 | primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| 668 | if err != nil { |
| 669 | return err |
| 670 | } |
| 671 | if primary != l.Runner.RunnerID { |
| 672 | // A worker's own connections (37): what the sync reports is |
| 673 | // recorded and holds the Mac at once; it never says one is gone |
| 674 | // (only a complete hello does). Nothing else of the primary's is |
| 675 | // its to settle. |
| 676 | if l.Role == wire.RoleWorker && l.Protocol >= wire.ProtocolMacEngineering { |
| 677 | if err := t.helloConnections(l, v.Connections, false); err != nil { |
| 678 | return err |
| 679 | } |
| 680 | if len(v.Connections) > 0 { |
| 681 | return t.holdCredential(l.Runner.RunnerID) |
| 682 | } |
| 683 | } |
| 684 | return nil |
| 685 | } |
| 686 | if err := t.helloConnections(l, v.Connections, true); err != nil { |
| 687 | return err |
| 688 | } |
| 689 | if err := t.advanceAll(l.Runner.Person); err != nil { |
| 690 | return err |
| 691 | } |
| 692 | held := map[string]bool{} |
| 693 | for _, run := range v.Runs { |
| 694 | held[run.TurnID] = true |
| 695 | } |
| 696 | var running []turnRecord |
| 697 | if err := t.db.Where("person = ? AND state IN ?", l.Runner.Person, []string{wire.TurnRunning, wire.TurnWaiting}).Find(&running).Error; err != nil { |
| 698 | return err |
| 699 | } |
| 700 | for _, r := range running { |
| 701 | if held[r.ID] { |
| 702 | continue |
| 703 | } |
| 704 | var unacked int64 |
| 705 | if err := t.db.Model(&commandRecord{}).Where("runner_id = ? AND person = ? AND kind = ? AND acked_at IS NULL", l.Runner.RunnerID, r.Person, wire.FrameMessage).Count(&unacked).Error; err != nil { |
| 706 | return err |
| 707 | } |
| 708 | if unacked != 0 { |
| 709 | continue |
| 710 | } |
| 711 | r.State, r.Reason = wire.TurnFailed, "interrupted" |
| 712 | if err := t.saveTurn(&r); err != nil { |
| 713 | return err |
| 714 | } |
| 715 | if err := t.kindEnded(r); err != nil { |
| 716 | return err |
| 717 | } |
| 718 | if err := t.dispatchNext(r.Person, r.Lane); err != nil { |
| 719 | return err |
| 720 | } |
| 721 | } |
| 722 | // Every path that ends a turn starts the next in the same |
| 723 | // transaction. A queued turn left behind with nothing in flight (an |
| 724 | // older instance's crash) starts here, once per lane: dispatchNext |
| 725 | // does nothing while a turn of its lane is in flight. Below the |
| 726 | // Assistant's protocol only the person's own; below 22 no job |
| 727 | // thread's. |
| 728 | if err := t.dispatchNext(l.Runner.Person, wire.LaneCoordinator); err != nil || l.Protocol < wire.ProtocolAssistant { |
| 729 | return err |
| 730 | } |
| 731 | if err := t.dispatchNext(l.Runner.Person, wire.LaneAssistant); err != nil || l.Protocol < wire.ProtocolJobs { |
| 732 | return err |
| 733 | } |
| 734 | var jobs []string |
| 735 | if err := t.db.Model(&turnRecord{}).Where("person = ? AND lane LIKE 'job:%' AND dispatched = ? AND state = ?", l.Runner.Person, false, wire.TurnQueued).Distinct("lane").Order("lane").Pluck("lane", &jobs).Error; err != nil { |
| 736 | return err |
| 737 | } |
| 738 | for _, lane := range jobs { |
| 739 | if err := t.dispatchNext(l.Runner.Person, lane); err != nil { |
| 740 | return err |
| 741 | } |
| 742 | } |
| 743 | return nil |
| 744 | } |
| 745 | |
| 746 | // markTainted records, for good, that a check ran outside the sandbox on |
| 747 | // a runner. |
| 748 | func (t *txn) markTainted(runnerID string) error { |
| 749 | return t.db.Exec(`UPDATE runners SET tainted_at = ? WHERE id = ? AND tainted_at IS NULL`, t.now(), runnerID).Error |
| 750 | } |
| 751 | |
| 752 | // tainted reports whether a check ever ran outside the sandbox on a |
| 753 | // runner. |
| 754 | func (t *txn) tainted(runnerID string) (bool, error) { |
| 755 | var n int64 |
| 756 | err := t.db.Raw(`SELECT count(*) FROM runners WHERE id = ? AND tainted_at IS NOT NULL`, runnerID).Scan(&n).Error |
| 757 | return n > 0, err |
| 758 | } |
| 759 | |