package thin import ( "context" "encoding/json" "errors" "log/slog" "math/rand/v2" "net/http" "net/url" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/wire" "github.com/coder/websocket" ) // ErrSuperseded means a newer runner process holds the execution lease. var ErrSuperseded = errors.New("runner superseded by a newer generation") // ErrRevoked means the instance refused this runner's credential. var ErrRevoked = errors.New("runner credential refused") // ErrInstanceTooOld means the instance speaks only protocol 1 and this // runner can only be a worker, which protocol 1 cannot place work on. The // runner does not connect (nothing is lost: its work waits on the // instance) and tries again later. var ErrInstanceTooOld = errors.New("the instance speaks only protocol 1, which has no workers: update the instance first") // ErrRoleMismatch means the instance welcomed a worker as something else: // a runner the instance once made a worker stays one (only a new // enrolment makes a primary), so it does not serve. var ErrRoleMismatch = errors.New("this runner is a worker and the instance welcomed it as a primary") // metaRole keeps the role the instance gave this runner, in its state. const metaRole = "role" // workerOnly: this runner may be a worker, so it never runs at protocol // 1 nor under a primary's welcome: by its platform, its enrolled role, the // role the instance gave it, or because it knows no role yet (a // credential from before roles) until a protocol 2 welcome says. func (l *Link) workerOnly(ctx context.Context) bool { if l.WorkerOnly || l.Role == wire.RoleWorker { return true } role, err := l.State.meta(ctx, metaRole) if err != nil || role == wire.RoleWorker { return true } return l.Role == "" && role == "" } // knownWorker: a worker by platform, enrolment or the instance's word. func (l *Link) knownWorker(ctx context.Context) bool { if l.WorkerOnly || l.Role == wire.RoleWorker { return true } role, err := l.State.meta(ctx, metaRole) return err != nil || role == wire.RoleWorker } // olderRetry is how long a worker waits before asking an older instance // again. var olderRetry = time.Minute // HelloInterval is the heartbeat. const HelloInterval = 30 * time.Second // Link is the runner's one outbound WebSocket to the instance. type Link struct { Origin string Token string State *State Engine *Engine // Steps runs dispatched step attempts; Recheck looks at what the // agent reaches now (a person acted on a grant card). Access *AccessEngine Steps *StepEngine Recheck func() // Files writes attachment chunks; nil acks them unwritten (tests). Files *Files // Forget removes the session directories a forget_task released. Forget func(dirs []string) // TaskEnded is told a task ended (its ForgetTask), once per command. TaskEnded func(ctx context.Context, task string) // Synced runs after every sync sent (the merge and branch watch looks // at once). Synced func() // Relay uploads packs and publishes workers' commits (protocol 2). Relay *Relay Hello func() wire.Hello // Welcomed sees each welcome (a Mac worker updates itself to the // release it names). Welcomed func(wire.Welcome) // Connector adds connections the person starts from the app. Connector *Connector Logger *slog.Logger // Connected is called with true once a generation is granted and false // when the socket ends. Tests use it to wait. Connected func(bool) // WorkerOnly: this runner can only be a worker (a Mac), so it never // runs at protocol 1. WorkerOnly bool // Role is the role this runner was enrolled with (its credential), "" // when the credential predates roles. Role string // Protocol caps what this runner offers (default wire.ProtocolCurrent; // tests set 1 to act as a slice 4 runner). Protocol int mu sync.Mutex conn *websocket.Conn generation int64 notify chan struct{} pending []wire.DeltaReport glances []wire.GlanceReport lookups []queuedLookup activity []wire.ActivityReport stepActs []wire.StepActivityReport waiters map[string]chan string tools map[string]chan wire.ToolResult leaseSeq int64 helloSoon bool // proto keeps the last negotiated version; role is what the instance // said this runner is (primary at protocol 1). proto int role string // heldStep: a step report was held below 37 (holdBelow37) since the // outbox was last offered again; rewind: offer it again from the // start, on this connection (a dispatch may have classified it). heldStep, rewind bool // dispatches counts accepted dispatches: a hold noted after one that // came while its report was being classified rewinds by itself. dispatches int64 // heldHook runs between holding a step report and noting it (tests). heldHook func() } // Spoken is the protocol of the current connection (0 when disconnected) // and the role the instance gave this runner. func (l *Link) Spoken() (int, string) { l.mu.Lock() defer l.mu.Unlock() if l.conn == nil { return 0, "" } return l.proto, l.role } func (l *Link) waitTool(callID string) chan wire.ToolResult { l.mu.Lock() defer l.mu.Unlock() if l.tools == nil { l.tools = map[string]chan wire.ToolResult{} } ch := make(chan wire.ToolResult, 1) l.tools[callID] = ch return ch } func (l *Link) forgetTool(callID string) { l.mu.Lock() defer l.mu.Unlock() delete(l.tools, callID) } func (l *Link) deliverTool(r wire.ToolResult) { l.mu.Lock() defer l.mu.Unlock() if ch, ok := l.tools[r.CallID]; ok { select { case ch <- r: default: } } } // HelloSoon sends a hello at the next write, so a new repository reaches // the instance's allowlist without waiting for the heartbeat. func (l *Link) HelloSoon() { l.mu.Lock() l.helloSoon = true l.mu.Unlock() l.Notify() } // Activity queues what the coordinator started doing. Like deltas it is // sent once, dropped while disconnected, and never stored. func (l *Link) Activity(a wire.ActivityReport) { l.init() l.mu.Lock() if l.conn != nil { l.activity = append(l.activity, a) } l.mu.Unlock() l.Notify() } // StepActivity queues what a running step's specialist started. Like // activity it is sent once, dropped while disconnected, never stored. func (l *Link) StepActivity(a wire.StepActivityReport) { l.init() l.mu.Lock() if l.conn != nil && len(l.stepActs) < maxQueuedStepActivity { l.stepActs = append(l.stepActs, a) } l.mu.Unlock() l.Notify() } // maxQueuedStepActivity bounds the lines waiting for the next flush. const maxQueuedStepActivity = 64 func (l *Link) takeStepActivity() []wire.StepActivityReport { l.mu.Lock() defer l.mu.Unlock() out := l.stepActs l.stepActs = nil return out } // ErrNoAuthority means the runner holds no confirmed generation now. var ErrNoAuthority = errors.New("runner holds no confirmed lease") // Confirm is the execution lease check: one round trip on the current // connection that the instance acks only while this connection holds the // generation. It fails at once when disconnected. func (l *Link) Confirm(ctx context.Context) error { return l.lease(ctx, wire.LeaseCheck{}) } // ErrWithdrawn means the instance refused an attempt's start (or a // publication): it was withdrawn, superseded or cancelled. Nothing of it // may run; the runner ends it. var ErrWithdrawn = errors.New("the instance withdrew this attempt") // ErrMergeNotAuthorized means the instance refused a merge request's // confirmation (merge authority): nothing may be sent to the hub. var ErrMergeNotAuthorized = errors.New("the instance did not authorize this merge request") // ConfirmStep is a step attempt's start authorization at protocol 2: the // instance grants it only while the attempt is placed on this runner and // not withdrawn (ErrWithdrawn). At protocol 1 it is the plain lease. func (l *Link) ConfirmStep(ctx context.Context, step string, attempt int64) error { return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt}) } // ConfirmMerge is the confirmation right before a hub merge request // (protocol 3, purpose merge_request): the instance decides the merge // again and grants it only if it may go now. At a lower protocol the // purpose is dropped by Encode and the instance treats it accordingly. func (l *Link) ConfirmMerge(ctx context.Context, step string, attempt int64) error { return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeMerge}) } // ConfirmPreview is the check right before a preview step's Carloku // mutation, bound to its export's digest. Below protocol 9 it is refused // here, never sent as an ordinary lease. ErrPreviewNotBuilt: the instance // has not applied the step's built report yet. func (l *Link) ConfirmPreview(ctx context.Context, step string, attempt int64, digest string) error { l.mu.Lock() proto := l.proto l.mu.Unlock() if proto < wire.ProtocolPreview { return ErrNoAuthority } return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposePreview, Digest: digest}) } // ConfirmRender is the check right before each of a Design step's // render_page calls (ProtocolDesign, purpose page_render): the instance // decides again whether the attempt's specialist binding may render. // Below protocol 38 it is refused here, never sent. func (l *Link) ConfirmRender(ctx context.Context, step string, attempt int64) error { l.mu.Lock() proto := l.proto l.mu.Unlock() if proto < wire.ProtocolDesign { return ErrNoAuthority } return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeRender}) } // ConfirmPublish is the check right before a publish step's deploy, // bound to its export's digest and its destination. Below protocol 31 it // is refused here, never sent: an older instance would decide it without // the destination. ErrPublishNotBuilt: the instance has not applied the // step's built report yet. func (l *Link) ConfirmPublish(ctx context.Context, step string, attempt int64, digest, destination string) error { return l.siteCheck(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposePublish, Digest: digest, Destination: destination}) } // ConfirmMint is the check right before a setup's or a mint's services // create, bound like ConfirmPublish, and refused below protocol 31 alike. func (l *Link) ConfirmMint(ctx context.Context, step string, attempt int64, digest, destination string) error { return l.siteCheck(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Purpose: wire.LeasePurposeMint, Digest: digest, Destination: destination}) } func (l *Link) siteCheck(ctx context.Context, check wire.LeaseCheck) error { l.mu.Lock() proto := l.proto l.mu.Unlock() if proto < wire.ProtocolPlaces || !wire.ValidDestination(check.Destination) { return ErrNoAuthority } return l.lease(ctx, check) } // ConfirmPublication is the primary's confirmation right before it pushes // a worker's commit: refused (ErrWithdrawn) once the publication is no // longer pending (cancelled, superseded). func (l *Link) ConfirmPublication(ctx context.Context, step string, attempt int64, publication string) error { return l.lease(ctx, wire.LeaseCheck{StepID: step, Attempt: attempt, Publication: publication}) } func (l *Link) lease(ctx context.Context, check wire.LeaseCheck) error { l.init() l.mu.Lock() c, generation, proto := l.conn, l.generation, l.proto if c == nil { l.mu.Unlock() return ErrNoAuthority } if proto < wire.Protocol2 { // A protocol 1 instance knows only the generation. check = wire.LeaseCheck{} } check.Generation = generation l.leaseSeq++ id := l.State.prefix + "-lease-" + itoa(l.leaseSeq) done := make(chan string, 1) if l.waiters == nil { l.waiters = map[string]chan string{} } l.waiters[id] = done l.mu.Unlock() defer func() { l.mu.Lock(); delete(l.waiters, id); l.mu.Unlock() }() f, _ := wire.NewFrame(id, wire.FrameLease, check) if err := l.send(ctx, c, f); err != nil { return ErrNoAuthority } select { case refused := <-done: return leaseRefusal(refused) case <-ctx.Done(): return ctx.Err() case <-time.After(15 * time.Second): return ErrNoAuthority } } // leaseRefusal is a lease answer as an error: nil when granted, // ErrMergeNotAuthorized when the instance would not let a merge request // go, ErrWithdrawn for any other refusal. func leaseRefusal(refused string) error { switch refused { case "": return nil case wire.RefusedMergeNotAuthorized: return ErrMergeNotAuthorized case "preview_public_disabled", "preview_host": return &previewRefusalError{reason: refused} case wire.RefusedPreviewNotBuilt: return ErrPreviewNotBuilt case wire.RefusedPublishNotBuilt: return ErrPublishNotBuilt } return ErrWithdrawn } // resolve answers a waiting lease: "" granted, else the refusal. func (l *Link) resolve(id, refused string) bool { l.mu.Lock() defer l.mu.Unlock() if done, ok := l.waiters[id]; ok { done <- refused delete(l.waiters, id) return true } return false } func (l *Link) init() { l.mu.Lock() defer l.mu.Unlock() if l.notify == nil { l.notify = make(chan struct{}, 1) } } // Notify wakes the sender after the outbox changed. func (l *Link) Notify() { l.init() select { case l.notify <- struct{}{}: default: } } // Delta queues streamed text; contiguous deltas for a turn coalesce and // are sent at most every 100 ms. Deltas are never stored or resent, and are // dropped while disconnected: the committed reply replaces the draft. func (l *Link) Delta(d wire.DeltaReport) { l.init() l.mu.Lock() if l.conn == nil { l.mu.Unlock() return } if n := len(l.pending); n > 0 { last := &l.pending[n-1] if last.TurnID == d.TurnID && last.Attempt == d.Attempt && last.Offset+int64(len(last.Text)) == d.Offset { last.Text += d.Text l.mu.Unlock() return } } l.pending = append(l.pending, d) l.mu.Unlock() } // Glance queues an Assistant turn's glance. Like a delta it is sent // once, dropped while disconnected and never stored, and it goes before // any delta queued after it (the engine queues it before the turn's // first). A connection below protocol 23 does not send it (Encode). func (l *Link) Glance(g wire.GlanceReport) { l.init() l.mu.Lock() if l.conn != nil { l.glances = append(l.glances, g) } l.mu.Unlock() l.Notify() } // queuedLookup is a lookup step's result and the connection its step // came on: it goes on that connection or nowhere. type queuedLookup struct { conn *websocket.Conn r wire.LookupResult } // lookupResult queues a lookup step's result, live, for the connection // c its step came on: sent once on it, never stored, dropped when it has // ended (the instance fails the attempt then, and never resends). func (l *Link) lookupResult(c *websocket.Conn, r wire.LookupResult) { l.init() l.mu.Lock() if l.conn == c { l.lookups = append(l.lookups, queuedLookup{c, r}) } l.mu.Unlock() l.Notify() } // takeLookups takes the results queued for c; any for another // connection are dropped. func (l *Link) takeLookups(c *websocket.Conn) []wire.LookupResult { l.mu.Lock() defer l.mu.Unlock() var out []wire.LookupResult for _, q := range l.lookups { if q.conn == c { out = append(out, q.r) } } l.lookups = nil return out } // Glances reports whether the current connection speaks glances. func (l *Link) Glances() bool { p, _ := l.Spoken() return p >= wire.ProtocolGlance } // takeQueued takes the glances, activity, deltas and a hello request // under one lock: a glance and the delta queued after it are taken // together or not at all, so the glance is sent first. func (l *Link) takeQueued() ([]wire.GlanceReport, []wire.ActivityReport, []wire.DeltaReport, bool) { l.mu.Lock() defer l.mu.Unlock() glances, acts, out, hello := l.glances, l.activity, l.pending, l.helloSoon l.glances, l.activity, l.pending, l.helloSoon = nil, nil, nil, false return glances, acts, out, hello } // Run connects and reconnects until ctx ends or the lease is lost. func (l *Link) Run(ctx context.Context) error { l.init() backoff := time.Second for { retry, err := l.session(ctx) if l.Connected != nil { l.Connected(false) } if errors.Is(err, ErrSuperseded) || errors.Is(err, ErrRevoked) || ctx.Err() != nil { if ctx.Err() != nil { return ctx.Err() } return err } older := errors.Is(err, ErrInstanceTooOld) || errors.Is(err, ErrRoleMismatch) if older { retry = olderRetry } wait := backoff if retry > 0 { wait, backoff = retry, time.Second } else if backoff < 30*time.Second { backoff *= 2 } wait += time.Duration(rand.Int64N(int64(wait / 4))) // Every ending is logged with the wait before the next try, the // first included: a runner that never connects says why. if l.Logger != nil { switch { case older: 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)) case err != nil: l.Logger.Warn("runner stream", "err", err, "retry_in", wait.Round(time.Millisecond)) default: l.Logger.Info("runner stream ended", "retry_in", wait.Round(time.Millisecond)) } } select { case <-ctx.Done(): return ctx.Err() case <-time.After(wait): } } } // send writes one frame as the current connection's protocol speaks it; // a frame that protocol does not have is not sent. func (l *Link) send(ctx context.Context, c *websocket.Conn, f wire.Frame) error { l.mu.Lock() proto, role := l.proto, l.role l.mu.Unlock() if (f.Type == wire.FrameConnection || f.Type == wire.FrameUsage) && (l.WorkerOnly || role == wire.RoleWorker) && proto < wire.ProtocolMacEngineering { // A worker says nothing of its connections below 37: kept in // the outbox for a connection that speaks it. return nil } l.mu.Lock() gen := l.dispatches l.mu.Unlock() if hold, err := l.State.holdBelow37(ctx, f, l.WorkerOnly || role == wire.RoleWorker, proto); hold { // Nor of its Engineering, which only 37 places (holdBelow37). if l.heldHook != nil { l.heldHook() } l.mu.Lock() l.heldStep = true // A dispatch accepted since the classification began may have // classified it, and saw no hold to rewind for: rewind now. again := l.dispatches != gen l.rewind = l.rewind || again l.mu.Unlock() if again { l.Notify() } if err != nil && l.Logger != nil { l.Logger.Warn("a step report kept for protocol 37: it could not be classified", "frame", f.ID, "err", sanitize(err)) } return nil } if f.Type == wire.FrameToolCall { body, err := f.Decode() if err != nil { return err } if call, ok := body.(*wire.ToolCall); ok { result, refused := accessRefused(*call, proto) if !refused { result, refused = stuckRefused(*call, proto) } if !refused { result, refused = placesRefused(*call, proto) } if !refused { result, refused = designRefused(*call, proto) } if refused { if err := l.State.Acked(ctx, f.ID); err != nil { return err } l.deliverTool(result) return nil } } } f, err := l.State.unfinishedReport(ctx, f, proto, role == wire.RoleWorker) if err != nil { return err } f, err = wire.Encode(f, max(proto, wire.Protocol1)) if errors.Is(err, wire.ErrProtocol) { if l.Logger != nil { l.Logger.Warn("runner frame not sent at protocol 1", "type", f.Type) } return nil } if err != nil { return err } raw, err := json.Marshal(f) if err != nil { return err } wctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() return c.Write(wctx, websocket.MessageText, raw) } // session is one connection. It returns a retry delay after drain. It // offers protocol 2; an older instance refuses that hello (its strict // decoder closes with a policy violation before any welcome), and the // runner says hello once more at protocol 1 on a new connection, unless it // can only be a worker. func (l *Link) session(ctx context.Context) (time.Duration, error) { offer := wire.ProtocolCurrent if l.Protocol > 0 { offer = min(l.Protocol, offer) } for { c, welcome, err := l.handshake(ctx, offer) if err == nil { return l.serve(ctx, c, welcome) } if offer < wire.Protocol2 || websocket.CloseStatus(err) != websocket.StatusPolicyViolation { return 0, err } if l.workerOnly(ctx) { return 0, ErrInstanceTooOld } if l.Logger != nil { l.Logger.Warn("the instance is older: speaking protocol 1 on this connection", "origin", l.Origin) } offer = wire.Protocol1 } } // handshake dials, says hello at offer and reads the welcome. func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire.Welcome, error) { url := "ws" + strings.TrimPrefix(l.Origin, "http") + wire.StreamPath host := originHost(l.Origin) l.info("connecting", "host", host, "protocol", offer) start := time.Now() dctx, cancel := context.WithTimeout(ctx, 20*time.Second) c, res, err := websocket.Dial(dctx, url, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + l.Token}}, CompressionMode: websocket.CompressionDisabled}) cancel() if err != nil { if res != nil && res.StatusCode == http.StatusForbidden { return nil, nil, ErrRevoked } return nil, nil, err } l.info("connected", "host", host, "took", took(start)) c.SetReadLimit(wire.MaxFrameBytes) hello := l.Hello() // Said before the instance says its protocol: never an empty // repository, which an older instance's strict decoder refuses. The // next hello carries them once the welcome says protocol 6. held := wire.WithoutEmptyRepos(&hello) // Nor the previews capability, which an instance below protocol 10 // refuses the same way. heldPreviews := wire.WithoutPreviews(&hello) // Nor the Research addresses, which an instance below protocol 13 // refuses the same way. heldResearch := withoutResearch(&hello) // Nor a reading's time, which an instance below protocol 15 refuses // the same way. heldReadings := wire.WithoutReadingTimes(&hello) heldUsage := wire.WithoutUsageRefresh(&hello) // Nor the sites capability, below protocol 16. heldSites := wire.WithoutSites(&hello) // Nor the reach and carlos health, below protocol 31. heldPlaces := wire.WithoutPlaces(&hello) // Nor the tool health, below protocol 30. heldTools := wire.WithoutToolHealth(&hello) l.mu.Lock() hello.Generation, hello.Protocol, l.proto = l.generation, offer, offer l.mu.Unlock() f, _ := wire.NewFrame(l.State.prefix+"-hello", wire.FrameHello, hello) if err = l.send(ctx, c, f); err != nil { c.CloseNow() return nil, nil, err } l.info("hello sent", "protocol", offer) rctx, rcancel := context.WithTimeout(ctx, 15*time.Second) _, raw, err := c.Read(rctx) rcancel() if err != nil { c.CloseNow() if websocket.CloseStatus(err) == websocket.StatusPolicyViolation { return nil, nil, err } return nil, nil, closeError(err) } wf, body, err := wire.ParseFrame(raw) welcome, ok := body.(*wire.Welcome) if err != nil || !ok || wf.Type != wire.FrameWelcome || welcome.Generation < 1 { c.CloseNow() return nil, nil, errors.New("runner stream: no welcome") } spoken, role := wire.Spoken(welcome.Protocol), welcome.Role if welcome.Protocol == 0 { spoken, role = wire.Protocol1, wire.RolePrimary } worker := l.workerOnly(ctx) if spoken < wire.Protocol2 && worker { c.CloseNow() return nil, nil, ErrInstanceTooOld } if role != wire.RoleWorker && l.knownWorker(ctx) { c.CloseNow() return nil, nil, ErrRoleMismatch } if role != "" { // The instance's word at protocol 2: kept, so a later rollback // cannot make a worker a primary. if err := l.State.setMeta(ctx, metaRole, role); err != nil { c.CloseNow() return nil, nil, err } } l.mu.Lock() l.proto, l.role = min(spoken, offer), role 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 { l.helloSoon = true } l.mu.Unlock() l.info("welcome", "protocol", min(spoken, offer), "role", role, "generation", welcome.Generation) return c, welcome, nil } // info logs one line of a connection's start (a few per reconnect). func (l *Link) info(msg string, args ...any) { if l.Logger != nil { l.Logger.Info(msg, args...) } } // originHost is the origin's host and port alone, for a log line. func originHost(origin string) string { u, err := url.Parse(origin) if err != nil { return "" } return u.Host } // serve runs one connection after its welcome. func (l *Link) serve(ctx context.Context, c *websocket.Conn, welcome *wire.Welcome) (time.Duration, error) { defer c.CloseNow() c.SetReadLimit(wire.MaxFrameBytes) parent := ctx ctx, stop := context.WithCancel(ctx) defer stop() // On shutdown say goodbye, so the instance (through any proxy) marks // the runner offline at once instead of waiting for silence. defer func() { if parent.Err() != nil { done := make(chan struct{}) go func() { c.Close(websocket.StatusGoingAway, "stopping"); close(done) }() select { case <-done: case <-time.After(2 * time.Second): } } }() l.mu.Lock() l.generation, l.conn = welcome.Generation, c l.mu.Unlock() defer func() { l.mu.Lock() l.conn, l.lookups = nil, nil l.mu.Unlock() }() if err := l.State.SaveGeneration(ctx, welcome.Generation); err != nil { return 0, err } if l.Welcomed != nil { l.Welcomed(*welcome) } sync, err := l.State.Sync(ctx) if err == nil && l.Hello != nil { sync.Connections = l.Hello().Connections } if err != nil { return 0, err } f, _ := wire.NewFrame(l.State.prefix+"-sync-"+time.Now().UTC().Format("150405.000000"), wire.FrameSync, sync) if err = l.send(ctx, c, f); err != nil { return 0, err } if l.Connected != nil { l.Connected(true) } if l.Steps != nil { // On every sync, re-probe attempts still waiting for their proof. go l.Steps.Probe(ctx) } if l.Synced != nil { go l.Synced() } type outcome struct { retry time.Duration err error } done := make(chan outcome, 1) go func() { retry, err := l.read(ctx, c) done <- outcome{retry, err} stop() }() err = l.write(ctx, c) stop() out := <-done if out.err != nil || out.retry > 0 { return out.retry, out.err } return 0, err } func closeError(err error) error { switch websocket.CloseStatus(err) { case wire.CloseSuperseded: return ErrSuperseded case wire.CloseRevoked: return ErrRevoked } return err } // laneSpoken says a message of kind in lane may run at protocol proto: // the coordinator's always, the Assistant's from 19, a well-formed job // lane from 22. Moving in and exploring are the coordinator's alone. func laneSpoken(lane, kind string, proto int) bool { _, job := wire.JobOf(lane) switch { case lane == wire.LaneCoordinator: return true case kind == wire.TurnMoveIn || kind == wire.TurnExplore: return false case lane == wire.LaneAssistant: return proto >= wire.ProtocolAssistant default: return job && proto >= wire.ProtocolJobs } } // read applies instance frames, acking durable ones after commit. func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, error) { for { _, raw, err := c.Read(ctx) if err != nil { return 0, closeError(err) } f, body, err := wire.ParseFrame(raw) if err != nil { return 0, err } if wire.ConnectionCommands[f.Type] { if proto, role := l.Spoken(); (l.WorkerOnly || role == wire.RoleWorker) && proto < wire.ProtocolMacEngineering { // A worker takes no connection command below 37: not acted // on and not acked, it waits for a connection that speaks it. continue } } switch v := body.(type) { case *wire.AttachmentChunk: // Written and recorded before the ack; chunks precede the // message frame that names them, on this one reader. if l.Files == nil { _, err = l.State.SeenResult(ctx, f.ID) } else { err = l.Files.Accept(ctx, f.ID, *v) } if err != nil { return 0, err } case *wire.MessageCommand: if proto, _ := l.Spoken(); !laneSpoken(v.Lane, v.Kind, proto) { // An instance below 19 has no Assistant, one below 22 no // job lanes, there is no other lane, and only the person's // own conversation moves in: such a message is never run, // least of all as a coordinator turn. l.info("message in an unknown lane dropped", "protocol", proto) continue } if err = l.State.Accept(ctx, f.ID, *v); err != nil { return 0, err } if l.Engine != nil { l.Engine.Wake(v.Person, v.Lane) } case *wire.ResetCommand: // Recorded durably with the frame id before the ack; the // person's worker applies it before running any later turn // (a turn in flight may still need this reader for its tools). if _, err := l.State.AcceptReset(ctx, f.ID, v.Person); err != nil { return 0, err } l.Engine.Wake(v.Person, wire.LaneCoordinator) case *wire.DispatchCommand: if proto, _ := l.Spoken(); proto < wire.ProtocolSandboxConsent { // An older instance never carries the person's choice to run // outside the sandbox: its dispatch is no consent. v.Unsandboxed = false } if err = l.State.AcceptDispatch(ctx, f.ID, *v); err != nil { return 0, err } // A report held below 37 may be classified now (a cancel that // came before this dispatch): offered again. l.mu.Lock() held := l.heldStep l.heldStep, l.rewind = false, l.rewind || held l.dispatches++ l.mu.Unlock() if held { l.Notify() } if l.Steps != nil { l.Steps.Wake() } case *wire.CancelStepCommand: if err = l.State.RequestStepCancel(ctx, f.ID, *v); err != nil { return 0, err } if l.Steps != nil { l.Steps.Cancel(v.StepID, v.Attempt) l.Steps.Wake() } case *wire.AskCommand: if err = l.State.AcceptAsk(ctx, f.ID, *v); err != nil { return 0, err } if l.Steps != nil { l.Steps.Wake() } case *wire.CancelAskCommand: if err = l.State.RequestAskCancel(ctx, f.ID, *v); err != nil { return 0, err } if l.Steps != nil { l.Steps.CancelAsk(v.QuestionID, v.Attempt) l.Steps.Wake() } case *wire.ForgetTaskCommand: dirs, err := l.State.ForgetTask(ctx, f.ID, *v) if err != nil { return 0, err } if l.Forget != nil { l.Forget(dirs) } if l.TaskEnded != nil && !v.KeepPreview { // Its preview link comes down (devbox), off the read loop, // unless the instance keeps it up until the person answers // Publish; a later forget_task without KeepPreview takes it // down. go l.TaskEnded(context.WithoutCancel(ctx), v.TaskID) } case *wire.WatchMergeCommand: if err = l.State.AcceptWatch(ctx, f.ID, *v); err != nil { return 0, err } case *wire.AccessCommand: if err = l.acceptAccess(ctx, f.ID, *v); err != nil { return 0, err } case *wire.RecheckCommand: fresh, err := l.State.SeenResult(ctx, f.ID) if err != nil { return 0, err } if fresh && l.Recheck != nil { go l.Recheck() } case *wire.CancelCommand: if _, err = l.State.RequestCancel(ctx, f.ID, *v); err != nil { return 0, err } l.Engine.Cancel(v.Person, v.TurnID, v.Attempt) l.Engine.Wake(v.Person, l.State.runLane(ctx, v.TurnID)) case *wire.Refused: l.resolve(v.ID, firstNonEmpty(v.Reason, "refused")) continue case *wire.Blob: if err = l.State.AcceptChunk(ctx, f.ID, *v); err != nil { return 0, err } if l.Steps != nil { l.Steps.Wake() } if l.Relay != nil { l.Relay.Wake() } case *wire.SendPackCommand: if err = l.State.AcceptUpload(ctx, f.ID, *v); err != nil { return 0, err } if l.Relay != nil { l.Relay.Wake() } case *wire.PublishCommand: if err = l.State.AcceptPublish(ctx, f.ID, *v); err != nil { return 0, err } if l.Relay != nil { l.Relay.Wake() } case *wire.PrepareBaseCommand: // Mac Engineering on a worker (protocol 37): the primary resolves // the attempt's base, durably, and reports it once per attempt. if err = l.State.AcceptPrepareBase(ctx, f.ID, *v); err != nil { return 0, err } if l.Relay != nil { l.Relay.Wake() } case *wire.Ack: if l.resolve(v.ID, "") { continue } if err = l.State.Acked(ctx, v.ID); err != nil { return 0, err } if l.Steps != nil { // A step's final report acked: its files can go. l.Steps.Wake() } continue case *wire.ToolResult: fresh, err := l.State.SeenResult(ctx, f.ID) if err != nil { return 0, err } if fresh { l.deliverTool(*v) } case *wire.ConnectCommand: if l.Connector == nil { continue } if err = l.Connector.Accept(ctx, f.ID, *v); err != nil { return 0, err } case *wire.DisconnectCommand: if l.Connector == nil { continue } if err = l.Connector.Disconnect(ctx, f.ID, *v); err != nil { return 0, err } case *wire.CheckCommand: if l.Connector == nil || l.Connector.Conns == nil { continue } if err = l.Connector.Check(ctx, f.ID, *v); err != nil { return 0, err } case *wire.PreferenceCommand: if l.Connector == nil || l.Connector.Conns == nil { continue } if err = l.Connector.Conns.Prefer(ctx, f.ID, *v); err != nil { return 0, err } l.wakeHeld(ctx) case *wire.ReleaseCommand: // Run now: kept for its step revision, consumed with the // admission it causes; a stale or replayed one is acked and // ignored. if _, err = l.State.Release(ctx, f.ID, *v); err != nil { return 0, err } l.wakeHeld(ctx) case *wire.PriorityCommand: if _, err = l.State.SetPriority(ctx, f.ID, *v); err != nil { return 0, err } l.wakeHeld(ctx) case *wire.SecretCommand: // Acked only once the secret is committed (or refused). if l.Connector == nil { continue } if err = l.Connector.Secret(ctx, f.ID, *v); err != nil { return 0, err } case *wire.ModelCommand: if l.Connector == nil { continue } if err = l.Connector.Model(ctx, f.ID, *v); err != nil { return 0, err } case *wire.ModelsCommand: // Acked once applied (ยง16.1): until then the instance shows the // set pending beside the applied one. if l.Connector == nil { continue } if err = l.Connector.Models(ctx, f.ID, *v); err != nil { return 0, err } case *wire.BudgetCommand: // Acked once applied: the instance shows it applied then. if l.Connector == nil { continue } if err = l.Connector.Budget(ctx, f.ID, *v); err != nil { return 0, err } case *wire.ResumeSpendCommand: if l.Connector == nil { continue } if err = l.Connector.ResumeSpend(ctx, f.ID, *v); err != nil { return 0, err } case *wire.CancelConnectCommand: if l.Connector == nil { continue } if err = l.Connector.Cancel(ctx, f.ID, *v); err != nil { return 0, err } case *wire.WarmCommand: // The person opened Base: warm their Assistant now. Below 24 // the instance has no such command, so one is not acted on. if proto, _ := l.Spoken(); proto < wire.ProtocolWarm { continue } l.Engine.WarmAssistant(v.Person) case *wire.LookupStep: // A lookup step: run beside everything else, its result sent // live on this connection. Below 36 the instance sends none. if proto, _ := l.Spoken(); proto < wire.ProtocolLookup || l.Engine == nil { continue } step := *v go func() { l.lookupResult(c, l.Engine.Lookup(ctx, step)) }() case *wire.Drain: return time.Duration(max(v.RetryAfter, 1)) * time.Second, nil default: continue } ack, _ := wire.NewFrame("a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID}) if err = l.send(ctx, c, ack); err != nil { return 0, err } } } // afterTake, set only by tests, runs in a flush right after it takes // what is queued. var afterTake func() // write sends unacked outbox frames, then new ones, deltas and heartbeats. func (l *Link) write(ctx context.Context, c *websocket.Conn) error { var sent int64 hello := time.NewTicker(HelloInterval) defer hello.Stop() batch := time.NewTicker(100 * time.Millisecond) defer batch.Stop() var seq int64 sendHello := func() error { h := l.Hello() l.mu.Lock() h.Generation = l.generation l.mu.Unlock() f, _ := wire.NewFrame(l.State.prefix+"-hello", wire.FrameHello, h) return l.send(ctx, c, f) } flush := func() error { // Glances first: a delta queued after one goes after it. glances, acts, deltas, hello := l.takeQueued() if afterTake != nil { afterTake() } if hello { if err := sendHello(); err != nil { return err } } for _, g := range glances { seq++ f, _ := wire.NewFrame(l.State.prefix+"-g-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameGlance, g) if err := l.send(ctx, c, f); err != nil { return err } } for _, r := range l.takeLookups(c) { seq++ f, _ := wire.NewFrame(l.State.prefix+"-l-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameLookupResult, r) if err := l.send(ctx, c, f); err != nil { return err } } for _, a := range acts { seq++ f, _ := wire.NewFrame(l.State.prefix+"-a-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameActivity, a) if err := l.send(ctx, c, f); err != nil { return err } } for _, a := range l.takeStepActivity() { seq++ f, _ := wire.NewFrame(l.State.prefix+"-sa-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameStepActivity, a) if err := l.send(ctx, c, f); err != nil { return err } } for _, d := range deltas { seq++ f, _ := wire.NewFrame(l.State.prefix+"-d-"+time.Now().UTC().Format("150405.000000")+"-"+itoa(seq), wire.FrameDelta, d) if err := l.send(ctx, c, f); err != nil { return err } } return nil } for { // Streamed text goes before the reply that replaces it. if err := flush(); err != nil { return err } l.mu.Lock() if l.rewind { // Held step reports are offered again from the start; a frame // already sent and not acked may go twice, as after a // reconnect. sent, l.rewind = 0, false } l.mu.Unlock() frames, last, err := l.State.Unacked(ctx, sent) if err != nil { return err } for _, f := range frames { if err = l.send(ctx, c, f); err != nil { return err } } sent = last select { case <-ctx.Done(): return nil case <-hello.C: if err = sendHello(); err != nil { return err } case <-batch.C: case <-l.notify: } } } func itoa(n int64) string { b, _ := json.Marshal(n) return string(b) } // wakeHeld makes the steps the scheduler holds look again (a fact // changed: a release, a priority, a preference). func (l *Link) wakeHeld(ctx context.Context) { if l.Steps == nil { return } if err := l.State.wakeHeld(ctx); err != nil && l.Logger != nil { l.Logger.Warn("step holds", "err", sanitize(err)) } l.Steps.Wake() }