| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "log/slog" |
| 8 | "math/rand/v2" |
| 9 | "net/http" |
| 10 | "net/url" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | "github.com/coder/websocket" |
| 17 | ) |
| 18 | |
| 19 | // ErrSuperseded means a newer runner process holds the execution lease. |
| 20 | var ErrSuperseded = errors.New("runner superseded by a newer generation") |
| 21 | |
| 22 | // ErrRevoked means the instance refused this runner's credential. |
| 23 | var ErrRevoked = errors.New("runner credential refused") |
| 24 | |
| 25 | // ErrInstanceTooOld means the instance speaks only protocol 1 and this |
| 26 | // runner can only be a worker, which protocol 1 cannot place work on. The |
| 27 | // runner does not connect (nothing is lost: its work waits on the |
| 28 | // instance) and tries again later. |
| 29 | var ErrInstanceTooOld = errors.New("the instance speaks only protocol 1, which has no workers: update the instance first") |
| 30 | |
| 31 | // ErrRoleMismatch means the instance welcomed a worker as something else: |
| 32 | // a runner the instance once made a worker stays one (only a new |
| 33 | // enrolment makes a primary), so it does not serve. |
| 34 | var ErrRoleMismatch = errors.New("this runner is a worker and the instance welcomed it as a primary") |
| 35 | |
| 36 | // metaRole keeps the role the instance gave this runner, in its state. |
| 37 | const metaRole = "role" |
| 38 | |
| 39 | // workerOnly: this runner may be a worker, so it never runs at protocol |
| 40 | // 1 nor under a primary's welcome: by its platform, its enrolled role, the |
| 41 | // role the instance gave it, or because it knows no role yet (a |
| 42 | // credential from before roles) until a protocol 2 welcome says. |
| 43 | func (l *Link) workerOnly(ctx context.Context) bool { |
| 44 | if l.WorkerOnly || l.Role == wire.RoleWorker { |
| 45 | return true |
| 46 | } |
| 47 | role, err := l.State.meta(ctx, metaRole) |
| 48 | if err != nil || role == wire.RoleWorker { |
| 49 | return true |
| 50 | } |
| 51 | return l.Role == "" && role == "" |
| 52 | } |
| 53 | |
| 54 | // knownWorker: a worker by platform, enrolment or the instance's word. |
| 55 | func (l *Link) knownWorker(ctx context.Context) bool { |
| 56 | if l.WorkerOnly || l.Role == wire.RoleWorker { |
| 57 | return true |
| 58 | } |
| 59 | role, err := l.State.meta(ctx, metaRole) |
| 60 | return err != nil || role == wire.RoleWorker |
| 61 | } |
| 62 | |
| 63 | // olderRetry is how long a worker waits before asking an older instance |
| 64 | // again. |
| 65 | var olderRetry = time.Minute |
| 66 | |
| 67 | // HelloInterval is the heartbeat. |
| 68 | const HelloInterval = 30 * time.Second |
| 69 | |
| 70 | // Link is the runner's one outbound WebSocket to the instance. |
| 71 | type Link struct { |
| 72 | Origin string |
| 73 | Token string |
| 74 | State *State |
| 75 | Engine *Engine |
| 76 | // Steps runs dispatched step attempts; Recheck looks at what the |
| 77 | // agent reaches now (a person acted on a grant card). |
| 78 | Access *AccessEngine |
| 79 | Steps *StepEngine |
| 80 | Recheck func() |
| 81 | // Files writes attachment chunks; nil acks them unwritten (tests). |
| 82 | Files *Files |
| 83 | // Forget removes the session directories a forget_task released. |
| 84 | Forget func(dirs []string) |
| 85 | // TaskEnded is told a task ended (its ForgetTask), once per command. |
| 86 | TaskEnded func(ctx context.Context, task string) |
| 87 | // Synced runs after every sync sent (the merge and branch watch looks |
| 88 | // at once). |
| 89 | Synced func() |
| 90 | // Relay uploads packs and publishes workers' commits (protocol 2). |
| 91 | Relay *Relay |
| 92 | Hello func() wire.Hello |
| 93 | // Welcomed sees each welcome (a Mac worker updates itself to the |
| 94 | // release it names). |
| 95 | Welcomed func(wire.Welcome) |
| 96 | // Connector adds connections the person starts from the app. |
| 97 | Connector *Connector |
| 98 | Logger *slog.Logger |
| 99 | // Connected is called with true once a generation is granted and false |
| 100 | // when the socket ends. Tests use it to wait. |
| 101 | Connected func(bool) |
| 102 | // WorkerOnly: this runner can only be a worker (a Mac), so it never |
| 103 | // runs at protocol 1. |
| 104 | WorkerOnly bool |
| 105 | // Role is the role this runner was enrolled with (its credential), "" |
| 106 | // when the credential predates roles. |
| 107 | Role string |
| 108 | // Protocol caps what this runner offers (default wire.ProtocolCurrent; |
| 109 | // tests set 1 to act as a slice 4 runner). |
| 110 | Protocol int |
| 111 | |
| 112 | mu sync.Mutex |
| 113 | conn *websocket.Conn |
| 114 | generation int64 |
| 115 | notify chan struct{} |
| 116 | pending []wire.DeltaReport |
| 117 | glances []wire.GlanceReport |
| 118 | lookups []queuedLookup |
| 119 | activity []wire.ActivityReport |
| 120 | stepActs []wire.StepActivityReport |
| 121 | waiters map[string]chan string |
| 122 | tools map[string]chan wire.ToolResult |
| 123 | leaseSeq int64 |
| 124 | helloSoon bool |
| 125 | // proto keeps the last negotiated version; role is what the instance |
| 126 | // said this runner is (primary at protocol 1). |
| 127 | proto int |
| 128 | role string |
| 129 | // heldStep: a step report was held below 37 (holdBelow37) since the |
| 130 | // outbox was last offered again; rewind: offer it again from the |
| 131 | // start, on this connection (a dispatch may have classified it). |
| 132 | heldStep, rewind bool |
| 133 | // dispatches counts accepted dispatches: a hold noted after one that |
| 134 | // came while its report was being classified rewinds by itself. |
| 135 | dispatches int64 |
| 136 | // heldHook runs between holding a step report and noting it (tests). |
| 137 | heldHook func() |
| 138 | } |
| 139 | |
| 140 | // Spoken is the protocol of the current connection (0 when disconnected) |
| 141 | // and the role the instance gave this runner. |
| 142 | func (l *Link) Spoken() (int, string) { |
| 143 | l.mu.Lock() |
| 144 | defer l.mu.Unlock() |
| 145 | if l.conn == nil { |
| 146 | return 0, "" |
| 147 | } |
| 148 | return l.proto, l.role |
| 149 | } |
| 150 | |
| 151 | func (l *Link) waitTool(callID string) chan wire.ToolResult { |
| 152 | l.mu.Lock() |
| 153 | defer l.mu.Unlock() |
| 154 | if l.tools == nil { |
| 155 | l.tools = map[string]chan wire.ToolResult{} |
| 156 | } |
| 157 | ch := make(chan wire.ToolResult, 1) |
| 158 | l.tools[callID] = ch |
| 159 | return ch |
| 160 | } |
| 161 | |
| 162 | func (l *Link) forgetTool(callID string) { |
| 163 | l.mu.Lock() |
| 164 | defer l.mu.Unlock() |
| 165 | delete(l.tools, callID) |
| 166 | } |
| 167 | |
| 168 | func (l *Link) deliverTool(r wire.ToolResult) { |
| 169 | l.mu.Lock() |
| 170 | defer l.mu.Unlock() |
| 171 | if ch, ok := l.tools[r.CallID]; ok { |
| 172 | select { |
| 173 | case ch <- r: |
| 174 | default: |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // HelloSoon sends a hello at the next write, so a new repository reaches |
| 180 | // the instance's allowlist without waiting for the heartbeat. |
| 181 | func (l *Link) HelloSoon() { |
| 182 | l.mu.Lock() |
| 183 | l.helloSoon = true |
| 184 | l.mu.Unlock() |
| 185 | l.Notify() |
| 186 | } |
| 187 | |
| 188 | // Activity queues what the coordinator started doing. Like deltas it is |
| 189 | // sent once, dropped while disconnected, and never stored. |
| 190 | func (l *Link) Activity(a wire.ActivityReport) { |
| 191 | l.init() |
| 192 | l.mu.Lock() |
| 193 | if l.conn != nil { |
| 194 | l.activity = append(l.activity, a) |
| 195 | } |
| 196 | l.mu.Unlock() |
| 197 | l.Notify() |
| 198 | } |
| 199 | |
| 200 | // StepActivity queues what a running step's specialist started. Like |
| 201 | // activity it is sent once, dropped while disconnected, never stored. |
| 202 | func (l *Link) StepActivity(a wire.StepActivityReport) { |
| 203 | l.init() |
| 204 | l.mu.Lock() |
| 205 | if l.conn != nil && len(l.stepActs) < maxQueuedStepActivity { |
| 206 | l.stepActs = append(l.stepActs, a) |
| 207 | } |
| 208 | l.mu.Unlock() |
| 209 | l.Notify() |
| 210 | } |
| 211 | |
| 212 | // maxQueuedStepActivity bounds the lines waiting for the next flush. |
| 213 | const maxQueuedStepActivity = 64 |
| 214 | |
| 215 | func (l *Link) takeStepActivity() []wire.StepActivityReport { |
| 216 | l.mu.Lock() |
| 217 | defer l.mu.Unlock() |
| 218 | out := l.stepActs |
| 219 | l.stepActs = nil |
| 220 | return out |
| 221 | } |
| 222 | |
| 223 | // ErrNoAuthority means the runner holds no confirmed generation now. |
| 224 | var ErrNoAuthority = errors.New("runner holds no confirmed lease") |
| 225 | |
| 226 | // Confirm is the execution lease check: one round trip on the current |
| 227 | // connection that the instance acks only while this connection holds the |
| 228 | // generation. It fails at once when disconnected. |
| 229 | func (l *Link) Confirm(ctx context.Context) error { |
| 230 | return l.lease(ctx, wire.LeaseCheck{}) |
| 231 | } |
| 232 | |
| 233 | // ErrWithdrawn means the instance refused an attempt's start (or a |
| 234 | // publication): it was withdrawn, superseded or cancelled. Nothing of it |
| 235 | // may run; the runner ends it. |
| 236 | var ErrWithdrawn = errors.New("the instance withdrew this attempt") |
| 237 | |
| 238 | // ErrMergeNotAuthorized means the instance refused a merge request's |
| 239 | // confirmation (merge authority): nothing may be sent to the hub. |
| 240 | var ErrMergeNotAuthorized = errors.New("the instance did not authorize this merge request") |
| 241 | |
| 242 | // ConfirmStep is a step attempt's start authorization at protocol 2: the |
| 243 | // instance grants it only while the attempt is placed on this runner and |
| 244 | // not withdrawn (ErrWithdrawn). At protocol 1 it is the plain lease. |
| 245 | func (l *Link) ConfirmStep(ctx context.Context, step string, attempt int64) error { |
| 246 | return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt}) |
| 247 | } |
| 248 | |
| 249 | // ConfirmMerge is the confirmation right before a hub merge request |
| 250 | // (protocol 3, purpose merge_request): the instance decides the merge |
| 251 | // again and grants it only if it may go now. At a lower protocol the |
| 252 | // purpose is dropped by Encode and the instance treats it accordingly. |
| 253 | func (l *Link) ConfirmMerge(ctx context.Context, step string, attempt int64) error { |
| 254 | return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeMerge}) |
| 255 | } |
| 256 | |
| 257 | // ConfirmPreview is the check right before a preview step's Carloku |
| 258 | // mutation, bound to its export's digest. Below protocol 9 it is refused |
| 259 | // here, never sent as an ordinary lease. ErrPreviewNotBuilt: the instance |
| 260 | // has not applied the step's built report yet. |
| 261 | func (l *Link) ConfirmPreview(ctx context.Context, step string, attempt int64, digest string) error { |
| 262 | l.mu.Lock() |
| 263 | proto := l.proto |
| 264 | l.mu.Unlock() |
| 265 | if proto < wire.ProtocolPreview { |
| 266 | return ErrNoAuthority |
| 267 | } |
| 268 | return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposePreview, Digest: digest}) |
| 269 | } |
| 270 | |
| 271 | // ConfirmRender is the check right before each of a Design step's |
| 272 | // render_page calls (ProtocolDesign, purpose page_render): the instance |
| 273 | // decides again whether the attempt's specialist binding may render. |
| 274 | // Below protocol 38 it is refused here, never sent. |
| 275 | func (l *Link) ConfirmRender(ctx context.Context, step string, attempt int64) error { |
| 276 | l.mu.Lock() |
| 277 | proto := l.proto |
| 278 | l.mu.Unlock() |
| 279 | if proto < wire.ProtocolDesign { |
| 280 | return ErrNoAuthority |
| 281 | } |
| 282 | return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeRender}) |
| 283 | } |
| 284 | |
| 285 | // ConfirmPublish is the check right before a publish step's deploy, |
| 286 | // bound to its export's digest and its destination. Below protocol 31 it |
| 287 | // is refused here, never sent: an older instance would decide it without |
| 288 | // the destination. ErrPublishNotBuilt: the instance has not applied the |
| 289 | // step's built report yet. |
| 290 | func (l *Link) ConfirmPublish(ctx context.Context, step string, attempt int64, digest, destination string) error { |
| 291 | return l.siteCheck(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposePublish, Digest: digest, Destination: destination}) |
| 292 | } |
| 293 | |
| 294 | // ConfirmMint is the check right before a setup's or a mint's services |
| 295 | // create, bound like ConfirmPublish, and refused below protocol 31 alike. |
| 296 | func (l *Link) ConfirmMint(ctx context.Context, step string, attempt int64, digest, destination string) error { |
| 297 | return l.siteCheck(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeMint, Digest: digest, Destination: destination}) |
| 298 | } |
| 299 | |
| 300 | func (l *Link) siteCheck(ctx context.Context, check wire.LeaseCheck) error { |
| 301 | l.mu.Lock() |
| 302 | proto := l.proto |
| 303 | l.mu.Unlock() |
| 304 | if proto < wire.ProtocolPlaces || !wire.ValidDestination(check.Destination) { |
| 305 | return ErrNoAuthority |
| 306 | } |
| 307 | return l.lease(ctx, check) |
| 308 | } |
| 309 | |
| 310 | // ConfirmPublication is the primary's confirmation right before it pushes |
| 311 | // a worker's commit: refused (ErrWithdrawn) once the publication is no |
| 312 | // longer pending (cancelled, superseded). |
| 313 | func (l *Link) ConfirmPublication(ctx context.Context, step string, attempt int64, publication string) error { |
| 314 | return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Publication: publication}) |
| 315 | } |
| 316 | |
| 317 | func (l *Link) lease(ctx context.Context, check wire.LeaseCheck) error { |
| 318 | l.init() |
| 319 | l.mu.Lock() |
| 320 | c, generation, proto := l.conn, l.generation, l.proto |
| 321 | if c == nil { |
| 322 | l.mu.Unlock() |
| 323 | return ErrNoAuthority |
| 324 | } |
| 325 | if proto < wire.Protocol2 { |
| 326 | // A protocol 1 instance knows only the generation. |
| 327 | check = wire.LeaseCheck{} |
| 328 | } |
| 329 | check.Generation = generation |
| 330 | l.leaseSeq++ |
| 331 | id := l.State.prefix + "-lease-" + itoa(l.leaseSeq) |
| 332 | done := make(chan string, 1) |
| 333 | if l.waiters == nil { |
| 334 | l.waiters = map[string]chan string{} |
| 335 | } |
| 336 | l.waiters[id] = done |
| 337 | l.mu.Unlock() |
| 338 | defer func() { l.mu.Lock(); delete(l.waiters, id); l.mu.Unlock() }() |
| 339 | f, _ := wire.NewFrame(id, wire.FrameLease, check) |
| 340 | if err := l.send(ctx, c, f); err != nil { |
| 341 | return ErrNoAuthority |
| 342 | } |
| 343 | select { |
| 344 | case refused := <-done: |
| 345 | return leaseRefusal(refused) |
| 346 | case <-ctx.Done(): |
| 347 | return ctx.Err() |
| 348 | case <-time.After(15 * time.Second): |
| 349 | return ErrNoAuthority |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | // leaseRefusal is a lease answer as an error: nil when granted, |
| 354 | // ErrMergeNotAuthorized when the instance would not let a merge request |
| 355 | // go, ErrWithdrawn for any other refusal. |
| 356 | func leaseRefusal(refused string) error { |
| 357 | switch refused { |
| 358 | case "": |
| 359 | return nil |
| 360 | case wire.RefusedMergeNotAuthorized: |
| 361 | return ErrMergeNotAuthorized |
| 362 | case "preview_public_disabled", "preview_host": |
| 363 | return &previewRefusalError{reason: refused} |
| 364 | case wire.RefusedPreviewNotBuilt: |
| 365 | return ErrPreviewNotBuilt |
| 366 | case wire.RefusedPublishNotBuilt: |
| 367 | return ErrPublishNotBuilt |
| 368 | } |
| 369 | return ErrWithdrawn |
| 370 | } |
| 371 | |
| 372 | // resolve answers a waiting lease: "" granted, else the refusal. |
| 373 | func (l *Link) resolve(id, refused string) bool { |
| 374 | l.mu.Lock() |
| 375 | defer l.mu.Unlock() |
| 376 | if done, ok := l.waiters[id]; ok { |
| 377 | done <- refused |
| 378 | delete(l.waiters, id) |
| 379 | return true |
| 380 | } |
| 381 | return false |
| 382 | } |
| 383 | |
| 384 | func (l *Link) init() { |
| 385 | l.mu.Lock() |
| 386 | defer l.mu.Unlock() |
| 387 | if l.notify == nil { |
| 388 | l.notify = make(chan struct{}, 1) |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | // Notify wakes the sender after the outbox changed. |
| 393 | func (l *Link) Notify() { |
| 394 | l.init() |
| 395 | select { |
| 396 | case l.notify <- struct{}{}: |
| 397 | default: |
| 398 | } |
| 399 | } |
| 400 | |
| 401 | // Delta queues streamed text; contiguous deltas for a turn coalesce and |
| 402 | // are sent at most every 100 ms. Deltas are never stored or resent, and are |
| 403 | // dropped while disconnected: the committed reply replaces the draft. |
| 404 | func (l *Link) Delta(d wire.DeltaReport) { |
| 405 | l.init() |
| 406 | l.mu.Lock() |
| 407 | if l.conn == nil { |
| 408 | l.mu.Unlock() |
| 409 | return |
| 410 | } |
| 411 | if n := len(l.pending); n > 0 { |
| 412 | last := &l.pending[n-1] |
| 413 | if last.TurnID == d.TurnID && last.Attempt == d.Attempt && last.Offset+int64(len(last.Text)) == d.Offset { |
| 414 | last.Text += d.Text |
| 415 | l.mu.Unlock() |
| 416 | return |
| 417 | } |
| 418 | } |
| 419 | l.pending = append(l.pending, d) |
| 420 | l.mu.Unlock() |
| 421 | } |
| 422 | |
| 423 | // Glance queues an Assistant turn's glance. Like a delta it is sent |
| 424 | // once, dropped while disconnected and never stored, and it goes before |
| 425 | // any delta queued after it (the engine queues it before the turn's |
| 426 | // first). A connection below protocol 23 does not send it (Encode). |
| 427 | func (l *Link) Glance(g wire.GlanceReport) { |
| 428 | l.init() |
| 429 | l.mu.Lock() |
| 430 | if l.conn != nil { |
| 431 | l.glances = append(l.glances, g) |
| 432 | } |
| 433 | l.mu.Unlock() |
| 434 | l.Notify() |
| 435 | } |
| 436 | |
| 437 | // queuedLookup is a lookup step's result and the connection its step |
| 438 | // came on: it goes on that connection or nowhere. |
| 439 | type queuedLookup struct { |
| 440 | conn *websocket.Conn |
| 441 | r wire.LookupResult |
| 442 | } |
| 443 | |
| 444 | // lookupResult queues a lookup step's result, live, for the connection |
| 445 | // c its step came on: sent once on it, never stored, dropped when it has |
| 446 | // ended (the instance fails the attempt then, and never resends). |
| 447 | func (l *Link) lookupResult(c *websocket.Conn, r wire.LookupResult) { |
| 448 | l.init() |
| 449 | l.mu.Lock() |
| 450 | if l.conn == c { |
| 451 | l.lookups = append(l.lookups, queuedLookup{c, r}) |
| 452 | } |
| 453 | l.mu.Unlock() |
| 454 | l.Notify() |
| 455 | } |
| 456 | |
| 457 | // takeLookups takes the results queued for c; any for another |
| 458 | // connection are dropped. |
| 459 | func (l *Link) takeLookups(c *websocket.Conn) []wire.LookupResult { |
| 460 | l.mu.Lock() |
| 461 | defer l.mu.Unlock() |
| 462 | var out []wire.LookupResult |
| 463 | for _, q := range l.lookups { |
| 464 | if q.conn == c { |
| 465 | out = append(out, q.r) |
| 466 | } |
| 467 | } |
| 468 | l.lookups = nil |
| 469 | return out |
| 470 | } |
| 471 | |
| 472 | // Glances reports whether the current connection speaks glances. |
| 473 | func (l *Link) Glances() bool { |
| 474 | p, _ := l.Spoken() |
| 475 | return p >= wire.ProtocolGlance |
| 476 | } |
| 477 | |
| 478 | // takeQueued takes the glances, activity, deltas and a hello request |
| 479 | // under one lock: a glance and the delta queued after it are taken |
| 480 | // together or not at all, so the glance is sent first. |
| 481 | func (l *Link) takeQueued() ([]wire.GlanceReport, []wire.ActivityReport, []wire.DeltaReport, bool) { |
| 482 | l.mu.Lock() |
| 483 | defer l.mu.Unlock() |
| 484 | glances, acts, out, hello := l.glances, l.activity, l.pending, l.helloSoon |
| 485 | l.glances, l.activity, l.pending, l.helloSoon = nil, nil, nil, false |
| 486 | return glances, acts, out, hello |
| 487 | } |
| 488 | |
| 489 | // Run connects and reconnects until ctx ends or the lease is lost. |
| 490 | func (l *Link) Run(ctx context.Context) error { |
| 491 | l.init() |
| 492 | backoff := time.Second |
| 493 | for { |
| 494 | retry, err := l.session(ctx) |
| 495 | if l.Connected != nil { |
| 496 | l.Connected(false) |
| 497 | } |
| 498 | if errors.Is(err, ErrSuperseded) || errors.Is(err, ErrRevoked) || ctx.Err() != nil { |
| 499 | if ctx.Err() != nil { |
| 500 | return ctx.Err() |
| 501 | } |
| 502 | return err |
| 503 | } |
| 504 | older := errors.Is(err, ErrInstanceTooOld) || errors.Is(err, ErrRoleMismatch) |
| 505 | if older { |
| 506 | retry = olderRetry |
| 507 | } |
| 508 | wait := backoff |
| 509 | if retry > 0 { |
| 510 | wait, backoff = retry, time.Second |
| 511 | } else if backoff < 30*time.Second { |
| 512 | backoff *= 2 |
| 513 | } |
| 514 | wait += time.Duration(rand.Int64N(int64(wait / 4))) |
| 515 | // Every ending is logged with the wait before the next try, the |
| 516 | // first included: a runner that never connects says why. |
| 517 | if l.Logger != nil { |
| 518 | switch { |
| 519 | case older: |
| 520 | l.Logger.Error("runner refused: this runner is a worker and the instance is an older release", "origin", l.Origin, "err", err, "retry_in", wait.Round(time.Millisecond)) |
| 521 | case err != nil: |
| 522 | l.Logger.Warn("runner stream", "err", err, "retry_in", wait.Round(time.Millisecond)) |
| 523 | default: |
| 524 | l.Logger.Info("runner stream ended", "retry_in", wait.Round(time.Millisecond)) |
| 525 | } |
| 526 | } |
| 527 | select { |
| 528 | case <-ctx.Done(): |
| 529 | return ctx.Err() |
| 530 | case <-time.After(wait): |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | // send writes one frame as the current connection's protocol speaks it; |
| 536 | // a frame that protocol does not have is not sent. |
| 537 | func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error { |
| 538 | l.mu.Lock() |
| 539 | proto, role := l.proto, l.role |
| 540 | l.mu.Unlock() |
| 541 | if (f.Type == wire.FrameConnection || f.Type == wire.FrameUsage) && (l.WorkerOnly || role == wire.RoleWorker) && proto < wire.ProtocolMacEngineering { |
| 542 | // A worker says nothing of its connections below 37: kept in |
| 543 | // the outbox for a connection that speaks it. |
| 544 | return nil |
| 545 | } |
| 546 | l.mu.Lock() |
| 547 | gen := l.dispatches |
| 548 | l.mu.Unlock() |
| 549 | if hold, err := l.State.holdBelow37(ctx, f, l.WorkerOnly || role == wire.RoleWorker, proto); hold { |
| 550 | // Nor of its Engineering, which only 37 places (holdBelow37). |
| 551 | if l.heldHook != nil { |
| 552 | l.heldHook() |
| 553 | } |
| 554 | l.mu.Lock() |
| 555 | l.heldStep = true |
| 556 | // A dispatch accepted since the classification began may have |
| 557 | // classified it, and saw no hold to rewind for: rewind now. |
| 558 | again := l.dispatches != gen |
| 559 | l.rewind = l.rewind || again |
| 560 | l.mu.Unlock() |
| 561 | if again { |
| 562 | l.Notify() |
| 563 | } |
| 564 | if err != nil && l.Logger != nil { |
| 565 | l.Logger.Warn("a step report kept for protocol 37: it could not be classified", "frame", f.ID, "err", sanitize(err)) |
| 566 | } |
| 567 | return nil |
| 568 | } |
| 569 | if f.Type == wire.FrameToolCall { |
| 570 | body, err := f.Decode() |
| 571 | if err != nil { |
| 572 | return err |
| 573 | } |
| 574 | if call, ok := body.(*wire.ToolCall); ok { |
| 575 | result, refused := accessRefused(*call, proto) |
| 576 | if !refused { |
| 577 | result, refused = stuckRefused(*call, proto) |
| 578 | } |
| 579 | if !refused { |
| 580 | result, refused = placesRefused(*call, proto) |
| 581 | } |
| 582 | if !refused { |
| 583 | result, refused = designRefused(*call, proto) |
| 584 | } |
| 585 | if refused { |
| 586 | if err := l.State.Acked(ctx, f.ID); err != nil { |
| 587 | return err |
| 588 | } |
| 589 | l.deliverTool(result) |
| 590 | return nil |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | f, err := l.State.unfinishedReport(ctx, f, proto, role == wire.RoleWorker) |
| 595 | if err != nil { |
| 596 | return err |
| 597 | } |
| 598 | f, err = wire.Encode(f, max(proto, wire.Protocol1)) |
| 599 | if errors.Is(err, wire.ErrProtocol) { |
| 600 | if l.Logger != nil { |
| 601 | l.Logger.Warn("runner frame not sent at protocol 1", "type", f.Type) |
| 602 | } |
| 603 | return nil |
| 604 | } |
| 605 | if err != nil { |
| 606 | return err |
| 607 | } |
| 608 | raw, err := json.Marshal(f) |
| 609 | if err != nil { |
| 610 | return err |
| 611 | } |
| 612 | wctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 613 | defer cancel() |
| 614 | return c.Write(wctx, websocket.MessageText, raw) |
| 615 | } |
| 616 | |
| 617 | // session is one connection. It returns a retry delay after drain. It |
| 618 | // offers protocol 2; an older instance refuses that hello (its strict |
| 619 | // decoder closes with a policy violation before any welcome), and the |
| 620 | // runner says hello once more at protocol 1 on a new connection, unless it |
| 621 | // can only be a worker. |
| 622 | func (l *Link) session(ctx context.Context) (time.Duration, error) { |
| 623 | offer := wire.ProtocolCurrent |
| 624 | if l.Protocol > 0 { |
| 625 | offer = min(l.Protocol, offer) |
| 626 | } |
| 627 | for { |
| 628 | c, welcome, err := l.handshake(ctx, offer) |
| 629 | if err == nil { |
| 630 | return l.serve(ctx, c, welcome) |
| 631 | } |
| 632 | if offer < wire.Protocol2 || websocket.CloseStatus(err) != websocket.StatusPolicyViolation { |
| 633 | return 0, err |
| 634 | } |
| 635 | if l.workerOnly(ctx) { |
| 636 | return 0, ErrInstanceTooOld |
| 637 | } |
| 638 | if l.Logger != nil { |
| 639 | l.Logger.Warn("the instance is older: speaking protocol 1 on this connection", "origin", l.Origin) |
| 640 | } |
| 641 | offer = wire.Protocol1 |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // handshake dials, says hello at offer and reads the welcome. |
| 646 | func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire.Welcome, error) { |
| 647 | url := "ws" + strings.TrimPrefix(l.Origin, "http") + wire.StreamPath |
| 648 | host := originHost(l.Origin) |
| 649 | l.info("connecting", "host", host, "protocol", offer) |
| 650 | start := time.Now() |
| 651 | dctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| 652 | c, res, err := websocket.Dial(dctx, url, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + l.Token}}, CompressionMode: websocket.CompressionDisabled}) |
| 653 | cancel() |
| 654 | if err != nil { |
| 655 | if res != nil && res.StatusCode == http.StatusForbidden { |
| 656 | return nil, nil, ErrRevoked |
| 657 | } |
| 658 | return nil, nil, err |
| 659 | } |
| 660 | l.info("connected", "host", host, "took", took(start)) |
| 661 | c.SetReadLimit(wire.MaxFrameBytes) |
| 662 | hello := l.Hello() |
| 663 | // Said before the instance says its protocol: never an empty |
| 664 | // repository, which an older instance's strict decoder refuses. The |
| 665 | // next hello carries them once the welcome says protocol 6. |
| 666 | held := wire.WithoutEmptyRepos(&hello) |
| 667 | // Nor the previews capability, which an instance below protocol 10 |
| 668 | // refuses the same way. |
| 669 | heldPreviews := wire.WithoutPreviews(&hello) |
| 670 | // Nor the Research addresses, which an instance below protocol 13 |
| 671 | // refuses the same way. |
| 672 | heldResearch := withoutResearch(&hello) |
| 673 | // Nor a reading's time, which an instance below protocol 15 refuses |
| 674 | // the same way. |
| 675 | heldReadings := wire.WithoutReadingTimes(&hello) |
| 676 | heldUsage := wire.WithoutUsageRefresh(&hello) |
| 677 | // Nor the sites capability, below protocol 16. |
| 678 | heldSites := wire.WithoutSites(&hello) |
| 679 | // Nor the reach and carlos health, below protocol 31. |
| 680 | heldPlaces := wire.WithoutPlaces(&hello) |
| 681 | // Nor the tool health, below protocol 30. |
| 682 | heldTools := wire.WithoutToolHealth(&hello) |
| 683 | l.mu.Lock() |
| 684 | hello.Generation, hello.Protocol, l.proto = l.generation, offer, offer |
| 685 | l.mu.Unlock() |
| 686 | f, _ := wire.NewFrame(l.State.prefix+"-hello", wire.FrameHello, hello) |
| 687 | if err = l.send(ctx, c, f); err != nil { |
| 688 | c.CloseNow() |
| 689 | return nil, nil, err |
| 690 | } |
| 691 | l.info("hello sent", "protocol", offer) |
| 692 | rctx, rcancel := context.WithTimeout(ctx, 15*time.Second) |
| 693 | _, raw, err := c.Read(rctx) |
| 694 | rcancel() |
| 695 | if err != nil { |
| 696 | c.CloseNow() |
| 697 | if websocket.CloseStatus(err) == websocket.StatusPolicyViolation { |
| 698 | return nil, nil, err |
| 699 | } |
| 700 | return nil, nil, closeError(err) |
| 701 | } |
| 702 | wf, body, err := wire.ParseFrame(raw) |
| 703 | welcome, ok := body.(*wire.Welcome) |
| 704 | if err != nil || !ok || wf.Type != wire.FrameWelcome || welcome.Generation < 1 { |
| 705 | c.CloseNow() |
| 706 | return nil, nil, errors.New("runner stream: no welcome") |
| 707 | } |
| 708 | spoken, role := wire.Spoken(welcome.Protocol), welcome.Role |
| 709 | if welcome.Protocol == 0 { |
| 710 | spoken, role = wire.Protocol1, wire.RolePrimary |
| 711 | } |
| 712 | worker := l.workerOnly(ctx) |
| 713 | if spoken < wire.Protocol2 && worker { |
| 714 | c.CloseNow() |
| 715 | return nil, nil, ErrInstanceTooOld |
| 716 | } |
| 717 | if role != wire.RoleWorker && l.knownWorker(ctx) { |
| 718 | c.CloseNow() |
| 719 | return nil, nil, ErrRoleMismatch |
| 720 | } |
| 721 | if role != "" { |
| 722 | // The instance's word at protocol 2: kept, so a later rollback |
| 723 | // cannot make a worker a primary. |
| 724 | if err := l.State.setMeta(ctx, metaRole, role); err != nil { |
| 725 | c.CloseNow() |
| 726 | return nil, nil, err |
| 727 | } |
| 728 | } |
| 729 | l.mu.Lock() |
| 730 | l.proto, l.role = min(spoken, offer), role |
| 731 | if heldUsage && l.proto >= wire.ProtocolUsageRefresh || held && l.proto >= wire.ProtocolEmptyRepos || heldPreviews && l.proto >= wire.ProtocolExplore || heldResearch && l.proto >= wire.ProtocolResearch || heldReadings && l.proto >= wire.ProtocolReadings || heldSites && l.proto >= wire.ProtocolPublish || heldTools && l.proto >= wire.ProtocolStuckTasks || heldPlaces && l.proto >= wire.ProtocolPlaces { |
| 732 | l.helloSoon = true |
| 733 | } |
| 734 | l.mu.Unlock() |
| 735 | l.info("welcome", "protocol", min(spoken, offer), "role", role, "generation", welcome.Generation) |
| 736 | return c, welcome, nil |
| 737 | } |
| 738 | |
| 739 | // info logs one line of a connection's start (a few per reconnect). |
| 740 | func (l *Link) info(msg string, args ...any) { |
| 741 | if l.Logger != nil { |
| 742 | l.Logger.Info(msg, args...) |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | // originHost is the origin's host and port alone, for a log line. |
| 747 | func originHost(origin string) string { |
| 748 | u, err := url.Parse(origin) |
| 749 | if err != nil { |
| 750 | return "" |
| 751 | } |
| 752 | return u.Host |
| 753 | } |
| 754 | |
| 755 | // serve runs one connection after its welcome. |
| 756 | func (l *Link) serve(ctx context.Context, c *websocket.Conn, welcome *wire.Welcome) (time.Duration, error) { |
| 757 | defer c.CloseNow() |
| 758 | c.SetReadLimit(wire.MaxFrameBytes) |
| 759 | parent := ctx |
| 760 | ctx, stop := context.WithCancel(ctx) |
| 761 | defer stop() |
| 762 | // On shutdown say goodbye, so the instance (through any proxy) marks |
| 763 | // the runner offline at once instead of waiting for silence. |
| 764 | defer func() { |
| 765 | if parent.Err() != nil { |
| 766 | done := make(chan struct{}) |
| 767 | go func() { c.Close(websocket.StatusGoingAway, "stopping"); close(done) }() |
| 768 | select { |
| 769 | case <-done: |
| 770 | case <-time.After(2 * time.Second): |
| 771 | } |
| 772 | } |
| 773 | }() |
| 774 | |
| 775 | l.mu.Lock() |
| 776 | l.generation, l.conn = welcome.Generation, c |
| 777 | l.mu.Unlock() |
| 778 | defer func() { |
| 779 | l.mu.Lock() |
| 780 | l.conn, l.lookups = nil, nil |
| 781 | l.mu.Unlock() |
| 782 | }() |
| 783 | if err := l.State.SaveGeneration(ctx, welcome.Generation); err != nil { |
| 784 | return 0, err |
| 785 | } |
| 786 | if l.Welcomed != nil { |
| 787 | l.Welcomed(*welcome) |
| 788 | } |
| 789 | sync, err := l.State.Sync(ctx) |
| 790 | if err == nil && l.Hello != nil { |
| 791 | sync.Connections = l.Hello().Connections |
| 792 | } |
| 793 | if err != nil { |
| 794 | return 0, err |
| 795 | } |
| 796 | f, _ := wire.NewFrame(l.State.prefix+"-sync-"+time.Now().UTC().Format("150405.000000"), wire.FrameSync, sync) |
| 797 | if err = l.send(ctx, c, f); err != nil { |
| 798 | return 0, err |
| 799 | } |
| 800 | if l.Connected != nil { |
| 801 | l.Connected(true) |
| 802 | } |
| 803 | if l.Steps != nil { |
| 804 | // On every sync, re-probe attempts still waiting for their proof. |
| 805 | go l.Steps.Probe(ctx) |
| 806 | } |
| 807 | if l.Synced != nil { |
| 808 | go l.Synced() |
| 809 | } |
| 810 | |
| 811 | type outcome struct { |
| 812 | retry time.Duration |
| 813 | err error |
| 814 | } |
| 815 | done := make(chan outcome, 1) |
| 816 | go func() { |
| 817 | retry, err := l.read(ctx, c) |
| 818 | done <- outcome{retry, err} |
| 819 | stop() |
| 820 | }() |
| 821 | err = l.write(ctx, c) |
| 822 | stop() |
| 823 | out := <-done |
| 824 | if out.err != nil || out.retry > 0 { |
| 825 | return out.retry, out.err |
| 826 | } |
| 827 | return 0, err |
| 828 | } |
| 829 | |
| 830 | func closeError(err error) error { |
| 831 | switch websocket.CloseStatus(err) { |
| 832 | case wire.CloseSuperseded: |
| 833 | return ErrSuperseded |
| 834 | case wire.CloseRevoked: |
| 835 | return ErrRevoked |
| 836 | } |
| 837 | return err |
| 838 | } |
| 839 | |
| 840 | // laneSpoken says a message of kind in lane may run at protocol proto: |
| 841 | // the coordinator's always, the Assistant's from 19, a well-formed job |
| 842 | // lane from 22. Moving in and exploring are the coordinator's alone. |
| 843 | func laneSpoken(lane, kind string, proto int) bool { |
| 844 | _, job := wire.JobOf(lane) |
| 845 | switch { |
| 846 | case lane == wire.LaneCoordinator: |
| 847 | return true |
| 848 | case kind == wire.TurnMoveIn || kind == wire.TurnExplore: |
| 849 | return false |
| 850 | case lane == wire.LaneAssistant: |
| 851 | return proto >= wire.ProtocolAssistant |
| 852 | default: |
| 853 | return job && proto >= wire.ProtocolJobs |
| 854 | } |
| 855 | } |
| 856 | |
| 857 | // read applies instance frames, acking durable ones after commit. |
| 858 | func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, error) { |
| 859 | for { |
| 860 | _, raw, err := c.Read(ctx) |
| 861 | if err != nil { |
| 862 | return 0, closeError(err) |
| 863 | } |
| 864 | f, body, err := wire.ParseFrame(raw) |
| 865 | if err != nil { |
| 866 | return 0, err |
| 867 | } |
| 868 | if wire.ConnectionCommands[f.Type] { |
| 869 | if proto, role := l.Spoken(); (l.WorkerOnly || role == wire.RoleWorker) && proto < wire.ProtocolMacEngineering { |
| 870 | // A worker takes no connection command below 37: not acted |
| 871 | // on and not acked, it waits for a connection that speaks it. |
| 872 | continue |
| 873 | } |
| 874 | } |
| 875 | switch v := body.(type) { |
| 876 | case *wire.AttachmentChunk: |
| 877 | // Written and recorded before the ack; chunks precede the |
| 878 | // message frame that names them, on this one reader. |
| 879 | if l.Files == nil { |
| 880 | _, err = l.State.SeenResult(ctx, f.ID) |
| 881 | } else { |
| 882 | err = l.Files.Accept(ctx, f.ID, *v) |
| 883 | } |
| 884 | if err != nil { |
| 885 | return 0, err |
| 886 | } |
| 887 | case *wire.MessageCommand: |
| 888 | if proto, _ := l.Spoken(); !laneSpoken(v.Lane, v.Kind, proto) { |
| 889 | // An instance below 19 has no Assistant, one below 22 no |
| 890 | // job lanes, there is no other lane, and only the person's |
| 891 | // own conversation moves in: such a message is never run, |
| 892 | // least of all as a coordinator turn. |
| 893 | l.info("message in an unknown lane dropped", "protocol", proto) |
| 894 | continue |
| 895 | } |
| 896 | if err = l.State.Accept(ctx, f.ID, *v); err != nil { |
| 897 | return 0, err |
| 898 | } |
| 899 | if l.Engine != nil { |
| 900 | l.Engine.Wake(v.Person, v.Lane) |
| 901 | } |
| 902 | case *wire.ResetCommand: |
| 903 | // Recorded durably with the frame id before the ack; the |
| 904 | // person's worker applies it before running any later turn |
| 905 | // (a turn in flight may still need this reader for its tools). |
| 906 | if _, err := l.State.AcceptReset(ctx, f.ID, v.Person); err != nil { |
| 907 | return 0, err |
| 908 | } |
| 909 | l.Engine.Wake(v.Person, wire.LaneCoordinator) |
| 910 | case *wire.DispatchCommand: |
| 911 | if proto, _ := l.Spoken(); proto < wire.ProtocolSandboxConsent { |
| 912 | // An older instance never carries the person's choice to run |
| 913 | // outside the sandbox: its dispatch is no consent. |
| 914 | v.Unsandboxed = false |
| 915 | } |
| 916 | if err = l.State.AcceptDispatch(ctx, f.ID, *v); err != nil { |
| 917 | return 0, err |
| 918 | } |
| 919 | // A report held below 37 may be classified now (a cancel that |
| 920 | // came before this dispatch): offered again. |
| 921 | l.mu.Lock() |
| 922 | held := l.heldStep |
| 923 | l.heldStep, l.rewind = false, l.rewind || held |
| 924 | l.dispatches++ |
| 925 | l.mu.Unlock() |
| 926 | if held { |
| 927 | l.Notify() |
| 928 | } |
| 929 | if l.Steps != nil { |
| 930 | l.Steps.Wake() |
| 931 | } |
| 932 | case *wire.CancelStepCommand: |
| 933 | if err = l.State.RequestStepCancel(ctx, f.ID, *v); err != nil { |
| 934 | return 0, err |
| 935 | } |
| 936 | if l.Steps != nil { |
| 937 | l.Steps.Cancel(v.StepID, v.Attempt) |
| 938 | l.Steps.Wake() |
| 939 | } |
| 940 | case *wire.AskCommand: |
| 941 | if err = l.State.AcceptAsk(ctx, f.ID, *v); err != nil { |
| 942 | return 0, err |
| 943 | } |
| 944 | if l.Steps != nil { |
| 945 | l.Steps.Wake() |
| 946 | } |
| 947 | case *wire.CancelAskCommand: |
| 948 | if err = l.State.RequestAskCancel(ctx, f.ID, *v); err != nil { |
| 949 | return 0, err |
| 950 | } |
| 951 | if l.Steps != nil { |
| 952 | l.Steps.CancelAsk(v.QuestionID, v.Attempt) |
| 953 | l.Steps.Wake() |
| 954 | } |
| 955 | case *wire.ForgetTaskCommand: |
| 956 | dirs, err := l.State.ForgetTask(ctx, f.ID, *v) |
| 957 | if err != nil { |
| 958 | return 0, err |
| 959 | } |
| 960 | if l.Forget != nil { |
| 961 | l.Forget(dirs) |
| 962 | } |
| 963 | if l.TaskEnded != nil && !v.KeepPreview { |
| 964 | // Its preview link comes down (devbox), off the read loop, |
| 965 | // unless the instance keeps it up until the person answers |
| 966 | // Publish; a later forget_task without KeepPreview takes it |
| 967 | // down. |
| 968 | go l.TaskEnded(context.WithoutCancel(ctx), v.TaskID) |
| 969 | } |
| 970 | case *wire.WatchMergeCommand: |
| 971 | if err = l.State.AcceptWatch(ctx, f.ID, *v); err != nil { |
| 972 | return 0, err |
| 973 | } |
| 974 | case *wire.AccessCommand: |
| 975 | if err = l.acceptAccess(ctx, f.ID, *v); err != nil { |
| 976 | return 0, err |
| 977 | } |
| 978 | case *wire.RecheckCommand: |
| 979 | fresh, err := l.State.SeenResult(ctx, f.ID) |
| 980 | if err != nil { |
| 981 | return 0, err |
| 982 | } |
| 983 | if fresh && l.Recheck != nil { |
| 984 | go l.Recheck() |
| 985 | } |
| 986 | case *wire.CancelCommand: |
| 987 | if _, err = l.State.RequestCancel(ctx, f.ID, *v); err != nil { |
| 988 | return 0, err |
| 989 | } |
| 990 | l.Engine.Cancel(v.Person, v.TurnID, v.Attempt) |
| 991 | l.Engine.Wake(v.Person, l.State.runLane(ctx, v.TurnID)) |
| 992 | case *wire.Refused: |
| 993 | l.resolve(v.ID, firstNonEmpty(v.Reason, "refused")) |
| 994 | continue |
| 995 | case *wire.Blob: |
| 996 | if err = l.State.AcceptChunk(ctx, f.ID, *v); err != nil { |
| 997 | return 0, err |
| 998 | } |
| 999 | if l.Steps != nil { |
| 1000 | l.Steps.Wake() |
| 1001 | } |
| 1002 | if l.Relay != nil { |
| 1003 | l.Relay.Wake() |
| 1004 | } |
| 1005 | case *wire.SendPackCommand: |
| 1006 | if err = l.State.AcceptUpload(ctx, f.ID, *v); err != nil { |
| 1007 | return 0, err |
| 1008 | } |
| 1009 | if l.Relay != nil { |
| 1010 | l.Relay.Wake() |
| 1011 | } |
| 1012 | case *wire.PublishCommand: |
| 1013 | if err = l.State.AcceptPublish(ctx, f.ID, *v); err != nil { |
| 1014 | return 0, err |
| 1015 | } |
| 1016 | if l.Relay != nil { |
| 1017 | l.Relay.Wake() |
| 1018 | } |
| 1019 | case *wire.PrepareBaseCommand: |
| 1020 | // Mac Engineering on a worker (protocol 37): the primary resolves |
| 1021 | // the attempt's base, durably, and reports it once per attempt. |
| 1022 | if err = l.State.AcceptPrepareBase(ctx, f.ID, *v); err != nil { |
| 1023 | return 0, err |
| 1024 | } |
| 1025 | if l.Relay != nil { |
| 1026 | l.Relay.Wake() |
| 1027 | } |
| 1028 | case *wire.Ack: |
| 1029 | if l.resolve(v.ID, "") { |
| 1030 | continue |
| 1031 | } |
| 1032 | if err = l.State.Acked(ctx, v.ID); err != nil { |
| 1033 | return 0, err |
| 1034 | } |
| 1035 | if l.Steps != nil { |
| 1036 | // A step's final report acked: its files can go. |
| 1037 | l.Steps.Wake() |
| 1038 | } |
| 1039 | continue |
| 1040 | case *wire.ToolResult: |
| 1041 | fresh, err := l.State.SeenResult(ctx, f.ID) |
| 1042 | if err != nil { |
| 1043 | return 0, err |
| 1044 | } |
| 1045 | if fresh { |
| 1046 | l.deliverTool(*v) |
| 1047 | } |
| 1048 | case *wire.ConnectCommand: |
| 1049 | if l.Connector == nil { |
| 1050 | continue |
| 1051 | } |
| 1052 | if err = l.Connector.Accept(ctx, f.ID, *v); err != nil { |
| 1053 | return 0, err |
| 1054 | } |
| 1055 | case *wire.DisconnectCommand: |
| 1056 | if l.Connector == nil { |
| 1057 | continue |
| 1058 | } |
| 1059 | if err = l.Connector.Disconnect(ctx, f.ID, *v); err != nil { |
| 1060 | return 0, err |
| 1061 | } |
| 1062 | case *wire.CheckCommand: |
| 1063 | if l.Connector == nil || l.Connector.Conns == nil { |
| 1064 | continue |
| 1065 | } |
| 1066 | if err = l.Connector.Check(ctx, f.ID, *v); err != nil { |
| 1067 | return 0, err |
| 1068 | } |
| 1069 | case *wire.PreferenceCommand: |
| 1070 | if l.Connector == nil || l.Connector.Conns == nil { |
| 1071 | continue |
| 1072 | } |
| 1073 | if err = l.Connector.Conns.Prefer(ctx, f.ID, *v); err != nil { |
| 1074 | return 0, err |
| 1075 | } |
| 1076 | l.wakeHeld(ctx) |
| 1077 | case *wire.ReleaseCommand: |
| 1078 | // Run now: kept for its step revision, consumed with the |
| 1079 | // admission it causes; a stale or replayed one is acked and |
| 1080 | // ignored. |
| 1081 | if _, err = l.State.Release(ctx, f.ID, *v); err != nil { |
| 1082 | return 0, err |
| 1083 | } |
| 1084 | l.wakeHeld(ctx) |
| 1085 | case *wire.PriorityCommand: |
| 1086 | if _, err = l.State.SetPriority(ctx, f.ID, *v); err != nil { |
| 1087 | return 0, err |
| 1088 | } |
| 1089 | l.wakeHeld(ctx) |
| 1090 | case *wire.SecretCommand: |
| 1091 | // Acked only once the secret is committed (or refused). |
| 1092 | if l.Connector == nil { |
| 1093 | continue |
| 1094 | } |
| 1095 | if err = l.Connector.Secret(ctx, f.ID, *v); err != nil { |
| 1096 | return 0, err |
| 1097 | } |
| 1098 | case *wire.ModelCommand: |
| 1099 | if l.Connector == nil { |
| 1100 | continue |
| 1101 | } |
| 1102 | if err = l.Connector.Model(ctx, f.ID, *v); err != nil { |
| 1103 | return 0, err |
| 1104 | } |
| 1105 | case *wire.ModelsCommand: |
| 1106 | // Acked once applied (§16.1): until then the instance shows the |
| 1107 | // set pending beside the applied one. |
| 1108 | if l.Connector == nil { |
| 1109 | continue |
| 1110 | } |
| 1111 | if err = l.Connector.Models(ctx, f.ID, *v); err != nil { |
| 1112 | return 0, err |
| 1113 | } |
| 1114 | case *wire.BudgetCommand: |
| 1115 | // Acked once applied: the instance shows it applied then. |
| 1116 | if l.Connector == nil { |
| 1117 | continue |
| 1118 | } |
| 1119 | if err = l.Connector.Budget(ctx, f.ID, *v); err != nil { |
| 1120 | return 0, err |
| 1121 | } |
| 1122 | case *wire.ResumeSpendCommand: |
| 1123 | if l.Connector == nil { |
| 1124 | continue |
| 1125 | } |
| 1126 | if err = l.Connector.ResumeSpend(ctx, f.ID, *v); err != nil { |
| 1127 | return 0, err |
| 1128 | } |
| 1129 | case *wire.CancelConnectCommand: |
| 1130 | if l.Connector == nil { |
| 1131 | continue |
| 1132 | } |
| 1133 | if err = l.Connector.Cancel(ctx, f.ID, *v); err != nil { |
| 1134 | return 0, err |
| 1135 | } |
| 1136 | case *wire.WarmCommand: |
| 1137 | // The person opened Base: warm their Assistant now. Below 24 |
| 1138 | // the instance has no such command, so one is not acted on. |
| 1139 | if proto, _ := l.Spoken(); proto < wire.ProtocolWarm { |
| 1140 | continue |
| 1141 | } |
| 1142 | l.Engine.WarmAssistant(v.Person) |
| 1143 | case *wire.LookupStep: |
| 1144 | // A lookup step: run beside everything else, its result sent |
| 1145 | // live on this connection. Below 36 the instance sends none. |
| 1146 | if proto, _ := l.Spoken(); proto < wire.ProtocolLookup || l.Engine == nil { |
| 1147 | continue |
| 1148 | } |
| 1149 | step := *v |
| 1150 | go func() { l.lookupResult(c, l.Engine.Lookup(ctx, step)) }() |
| 1151 | case *wire.Drain: |
| 1152 | return time.Duration(max(v.RetryAfter, 1)) * time.Second, nil |
| 1153 | default: |
| 1154 | continue |
| 1155 | } |
| 1156 | ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) |
| 1157 | if err = l.send(ctx, c, ack); err != nil { |
| 1158 | return 0, err |
| 1159 | } |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | // afterTake, set only by tests, runs in a flush right after it takes |
| 1164 | // what is queued. |
| 1165 | var afterTake func() |
| 1166 | |
| 1167 | // write sends unacked outbox frames, then new ones, deltas and heartbeats. |
| 1168 | func (l *Link) write(ctx context.Context, c *websocket.Conn) error { |
| 1169 | var sent int64 |
| 1170 | hello := time.NewTicker(HelloInterval) |
| 1171 | defer hello.Stop() |
| 1172 | batch := time.NewTicker(100 * time.Millisecond) |
| 1173 | defer batch.Stop() |
| 1174 | var seq int64 |
| 1175 | sendHello := func() error { |
| 1176 | h := l.Hello() |
| 1177 | l.mu.Lock() |
| 1178 | h.Generation = l.generation |
| 1179 | l.mu.Unlock() |
| 1180 | f, _ := wire.NewFrame(l.State.prefix+"-hello", wire.FrameHello, h) |
| 1181 | return l.send(ctx, c, f) |
| 1182 | } |
| 1183 | flush := func() error { |
| 1184 | // Glances first: a delta queued after one goes after it. |
| 1185 | glances, acts, deltas, hello := l.takeQueued() |
| 1186 | if afterTake != nil { |
| 1187 | afterTake() |
| 1188 | } |
| 1189 | if hello { |
| 1190 | if err := sendHello(); err != nil { |
| 1191 | return err |
| 1192 | } |
| 1193 | } |
| 1194 | for _, g := range glances { |
| 1195 | seq++ |
| 1196 | f, _ := wire.NewFrame(l.State.prefix+"-g-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameGlance, g) |
| 1197 | if err := l.send(ctx, c, f); err != nil { |
| 1198 | return err |
| 1199 | } |
| 1200 | } |
| 1201 | for _, r := range l.takeLookups(c) { |
| 1202 | seq++ |
| 1203 | f, _ := wire.NewFrame(l.State.prefix+"-l-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameLookupResult, r) |
| 1204 | if err := l.send(ctx, c, f); err != nil { |
| 1205 | return err |
| 1206 | } |
| 1207 | } |
| 1208 | for _, a := range acts { |
| 1209 | seq++ |
| 1210 | f, _ := wire.NewFrame(l.State.prefix+"-a-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameActivity, a) |
| 1211 | if err := l.send(ctx, c, f); err != nil { |
| 1212 | return err |
| 1213 | } |
| 1214 | } |
| 1215 | for _, a := range l.takeStepActivity() { |
| 1216 | seq++ |
| 1217 | f, _ := wire.NewFrame(l.State.prefix+"-sa-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameStepActivity, a) |
| 1218 | if err := l.send(ctx, c, f); err != nil { |
| 1219 | return err |
| 1220 | } |
| 1221 | } |
| 1222 | for _, d := range deltas { |
| 1223 | seq++ |
| 1224 | f, _ := wire.NewFrame(l.State.prefix+"-d-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameDelta, d) |
| 1225 | if err := l.send(ctx, c, f); err != nil { |
| 1226 | return err |
| 1227 | } |
| 1228 | } |
| 1229 | return nil |
| 1230 | } |
| 1231 | for { |
| 1232 | // Streamed text goes before the reply that replaces it. |
| 1233 | if err := flush(); err != nil { |
| 1234 | return err |
| 1235 | } |
| 1236 | l.mu.Lock() |
| 1237 | if l.rewind { |
| 1238 | // Held step reports are offered again from the start; a frame |
| 1239 | // already sent and not acked may go twice, as after a |
| 1240 | // reconnect. |
| 1241 | sent, l.rewind = 0, false |
| 1242 | } |
| 1243 | l.mu.Unlock() |
| 1244 | frames, last, err := l.State.Unacked(ctx, sent) |
| 1245 | if err != nil { |
| 1246 | return err |
| 1247 | } |
| 1248 | for _, f := range frames { |
| 1249 | if err = l.send(ctx, c, f); err != nil { |
| 1250 | return err |
| 1251 | } |
| 1252 | } |
| 1253 | sent = last |
| 1254 | select { |
| 1255 | case <-ctx.Done(): |
| 1256 | return nil |
| 1257 | case <-hello.C: |
| 1258 | if err = sendHello(); err != nil { |
| 1259 | return err |
| 1260 | } |
| 1261 | case <-batch.C: |
| 1262 | case <-l.notify: |
| 1263 | } |
| 1264 | } |
| 1265 | } |
| 1266 | |
| 1267 | func itoa(n int64) string { |
| 1268 | b, _ := json.Marshal(n) |
| 1269 | return string(b) |
| 1270 | } |
| 1271 | |
| 1272 | // wakeHeld makes the steps the scheduler holds look again (a fact |
| 1273 | // changed: a release, a priority, a preference). |
| 1274 | func (l *Link) wakeHeld(ctx context.Context) { |
| 1275 | if l.Steps == nil { |
| 1276 | return |
| 1277 | } |
| 1278 | if err := l.State.wakeHeld(ctx); err != nil && l.Logger != nil { |
| 1279 | l.Logger.Warn("step holds", "err", sanitize(err)) |
| 1280 | } |
| 1281 | l.Steps.Wake() |
| 1282 | } |
| 1283 | |