carlos / platform Public

console: the box door and the splice; the sweep clears dead sessions (rootfs plan 6)

GET /api/box/interactive/{id}: a host-claim console answers 409 C35; an
invalid, inactive (reserved, ended, pending, pruned, unknown) id, a wrong
session token, or a fleet session without its own fleet's active box
identity in a fleet the session's account owns (fleetIdentityOK, PF-16)
all get the same 404; a second attach gets 409. The door is lifetimes
exempt (PF-4) and hands the upgraded box to the waiting session, whose
single CLI reader the splice takes over.

The splice sends the CLI's Open as sent, forwards status, data and the
box's end one way and data and resize the other, answers keepalives per
leg, and writes each leg from one synchronous writer so nothing queues.
Endings: CLI gone hangs up the box and waits for its End; box gone is
lost; past MaxDuration + 1 min is limit.

The run sweep clears markers of other boots and of unheld sessions past
PickupBy (lost row unless ended; endPending left to its own pass), and
housekeeping deletes day-old grants no record names on a complete read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 419ba4fa3d877b71d01bf27be0ac6785d4b75191 parent 6f1d087
14 files changed, +2,190 −41
  • internal/console/apiinteractive.go +26 −11
  • internal/console/apiinteractive_lifetimes_test.go +154 −12
  • internal/console/apiinteractivebox.go +131 −0
  • internal/console/apiinteractivebox_test.go +975 −0
  • internal/console/claim_invariant_fixtures_test.go +13 −0
  • internal/console/interactivehub.go +377 −4
  • internal/console/jobs_test.go +2 −1
  • internal/console/lifetimes_cutover.go +9 −1
  • internal/console/runsweep.go +155 −11
  • internal/console/runsweep_test.go +327 −0
  • internal/console/server.go +8 −0
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/console/view.go +1 −0
  • internal/provision/rootfs_apps_6_census_test.go +11 −1

Intent

Human

<task-notification> <task-id>a7099b6064086f5c2</task-id> <tool-use-id>toolu_01TBxz4CGaPF3xwDjsxvyCja</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a7099b6064086f5c2.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 10: console session door" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>The serial bump no longer holds the session's admission; it now runs after the admission step returns, outside any lifetimes unit. Status: **DONE**. **Commit:** 6f1d0877 (fix round 2, on 37691fcf). Not pushed. **Tests:** the new `TestTheSerialBumpHoldsNoAdmission` failed first and passes now. With the serial PUT hanging, the admission's unit is released and the session is active within OpenWait + 2 s, and the bump still lands afterwards. The mutation that moves the bump back inside the unit is killed. The session-door and lifetimes tests pass under `-race -count=3`, including the request budget (still 18/21, +2 for `carlos console`). The console claim-route, role and cutover tests pass, as do the darwin/arm64, windows/amd64 and linux/arm64 builds. **Bound:** admission holds its reservation and unit for at most OpenWait plus the store's fixed 2 s change-index tail, which every console write shares. This is stated beside the admission step's deadline in `serveInteractive` and in the report. The bump's failure handling is unchanged. **Census:** `admitSession` is re-pinned with the same class. The root-read card is clean (seal f02fd204 unchanged), so the overlay was not re-proposed. **Concerns:** none new. As ruled, I left the audit-insert error swallowing at `server.go:4908` alone. The fix report is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/rootfs-apps-6/.superpowers/sdd/2026-10-24-rootfs-apps-6-interactive/task-10-report.md`.</result> <usage><subagent_tokens>433096</subagent_tokens><tool_uses>8</tool_uses><duration_ms>405521</duration_ms></usage> </task-notification>

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/342481.sock" from-name="platform-f6" from-mode="bypass"> FYI: a flaky test on main from #471. internal/tunnelclient TestRoundTripUpgradeEndsWithItsContext/during_the_handshake fails intermittently with "hijack: http2: stream closed" and "the box conn's Read did not fail within 1 s: the stream was not reset" (upgrade_hub_test.go:65/555). It reproduces on a clean origin/main b4d8db83 checkout with go test ./internal/tunnelclient -run TestRoundTripUpgradeEndsWithItsContext -count=10 on DOCS-T1, and it failed CI on my branch design-devbox-mode at 8116455e, which doesn't touch tunnelclient. I'm just re-running CI on my side; flagging it in case it's yours to fix. </cross-session-message>

Attributed to this commit: 19.1 g CO₂e (2,339,532 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on rootfs-apps-6-interactive, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/apiinteractive.go b/internal/console/apiinteractive.go
index 527d37554..cc24bf631 100644
--- a/internal/console/apiinteractive.go
+++ b/internal/console/apiinteractive.go
@@ -27,6 +27,7 @@ import (
"log"
"net/http"
"os"
+ "sync/atomic"
"time"
"golang.org/x/net/websocket"
@@ -181,7 +182,7 @@ func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d in
return
}
sess := &hubSession{acct: d.acct.Sqid, app: d.app, host: d.host, by: d.by, account: d.acct,
- open: open, argv: open.Argv, cli: ws, attach: make(chan *boxConn)}
+ open: open, argv: open.Argv, cli: ws, attach: make(chan *boxConn), over: make(chan struct{})}
if open.Process == release.ProcessConsole {
argv, version, refusal := s.resolveConsole(ctx, d)
if refusal != nil {
@@ -379,35 +380,47 @@ func admissionRefusal(err error, sess *hubSession) *interactive.End {
return &interactive.End{Detail: interactiveFailedMsg}
}
-// awaitBox holds the waiting session until its pickup window closes or its
-// CLI goes. Receive is the connection's only reader, on its own goroutine;
-// any error from it ends the connection. Until a box attaches there is no
-// terminal: a keepalive is answered and any other frame is dropped.
+// awaitBox holds the waiting session until a box attaches, its pickup
+// window closes or its CLI goes. Receive is the connection's only reader, on
+// its own goroutine, for the whole session: when a box attaches, the splice
+// takes its frames (sess.cliLeg), and no second reader ever runs. Any error
+// from it ends the connection. Until a box attaches there is no terminal: a
+// keepalive is answered and any other frame is dropped.
func (s *Server) awaitBox(ws *websocket.Conn, sess *hubSession) {
- frames := make(chan byte)
+ frames := make(chan ixFrame)
gone := make(chan struct{})
stop := make(chan struct{})
defer close(stop)
+ lost := new(atomic.Int64)
go func() {
defer close(gone)
for {
- kind, _, err := interactive.Receive(ws)
+ kind, payload, err := interactive.Receive(ws)
if err != nil {
return
}
+ // Spliced, the leg's read deadline is refreshed on every frame.
+ if d := lost.Load(); d > 0 {
+ _ = ws.SetReadDeadline(time.Now().Add(time.Duration(d)))
+ }
select {
- case frames <- kind:
+ case frames <- ixFrame{kind: kind, payload: payload}:
case <-stop:
return
}
}
}()
+ sess.cliLeg = &cliLeg{in: frames, gone: gone, lost: lost}
pickup := time.NewTimer(time.Until(sess.pickupBy))
defer pickup.Stop()
for {
select {
- case kind := <-frames:
- if kind != interactive.KindAlive {
+ case box := <-sess.attach:
+ pickup.Stop()
+ s.endSession(ws, sess, s.interactive.splice(context.Background(), sess, box))
+ return
+ case f := <-frames:
+ if f.kind != interactive.KindAlive {
continue
}
if err := sendSession(ws, interactive.KindAlive, nil); err != nil {
@@ -429,7 +442,9 @@ func (s *Server) awaitBox(ws *websocket.Conn, sess *hubSession) {
// own write step. If the gate refuses that step (draining), or its record
// write fails, the id waits in endPending and the sweep finishes it.
func (s *Server) endSession(ws *websocket.Conn, sess *hubSession, e interactive.End) {
- e.Ended = time.Now().UTC()
+ if e.Ended.IsZero() {
+ e.Ended = time.Now().UTC()
+ }
_ = sendSessionJSON(ws, interactive.KindEnd, e)
ws.Close()
h := s.interactive
diff --git a/internal/console/apiinteractive_lifetimes_test.go b/internal/console/apiinteractive_lifetimes_test.go
index 17a9dd5d8..3a6709a0a 100644
--- a/internal/console/apiinteractive_lifetimes_test.go
+++ b/internal/console/apiinteractive_lifetimes_test.go
@@ -18,6 +18,8 @@ import (
"testing"
"time"
+ "golang.org/x/net/websocket"
+
"github.com/carlosframework/platform/internal/appconfig"
"github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/provision"
@@ -271,6 +273,122 @@ func TestASessionsEndStepIsItsOwnUnit(t *testing.T) {
}
}
+// ixPingPong carries one data frame each way across a spliced session.
+func ixPingPong(t *testing.T, cli, box *websocket.Conn, tag string) {
+ t.Helper()
+ if err := interactive.Send(cli, interactive.KindData, []byte("cli "+tag)); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, box, interactive.KindData); string(p) != "cli "+tag {
+ t.Fatalf("%s: box data %q", tag, p)
+ }
+ if err := interactive.Send(box, interactive.KindData, []byte("box "+tag)); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, cli, interactive.KindData); string(p) != "box "+tag {
+ t.Fatalf("%s: CLI data %q", tag, p)
+ }
+}
+
+func TestCutoverDrainsWhileASplicedSessionRuns(t *testing.T) {
+ fx, clock := newIxLtFx(t, "code-ixb-lt-drain")
+ g := fx.srv.cutover
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, grant := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(grant.Token))
+ ixPingPong(t, cli, box, "before")
+ if p := g.status().Pending; p != 0 {
+ t.Fatalf("a spliced session holds %d units, want none", p)
+ }
+ ixCutover(t, fx)
+ select {
+ case <-g.drainedCh():
+ case <-time.After(time.Second):
+ t.Fatal("the drain did not close within 1 s: the spliced session holds a unit")
+ }
+ if st := g.status().State; st != "draining" {
+ t.Fatalf("the gate is %s before the settle, want draining", st)
+ }
+ ixPingPong(t, cli, box, "draining")
+ ixActivate(t, fx, clock)
+ ixPingPong(t, cli, box, "on")
+ if p := g.status().Pending; p != 0 {
+ t.Fatalf("%d units counted while spliced", p)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("the session ended across the cutover: %+v", evs)
+ }
+ steps := hookSteps(t)
+ ixFinish(t, fx, cli, box, 1)
+ if s := steps(); len(s) != 1 || s[0].mode != cutoverOn || !s[0].judged || !s[0].own {
+ t.Fatalf("the end's write steps %+v, want one judged unit of its own", s)
+ }
+}
+
+func TestAnEndRefusedWhileDrainingIsFinishedByTheSweep(t *testing.T) {
+ fx, clock := newIxLtFx(t, "code-ixb-lt-pending")
+ h := fx.srv.interactive
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, grant := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(grant.Token))
+ held, ok, _ := fx.srv.lifetimesAdmit(context.Background(), true)
+ if !ok || held.mode != cutoverBefore {
+ t.Fatal("the test's legacy unit was not admitted")
+ }
+ released := false
+ t.Cleanup(func() {
+ if !released {
+ held.done()
+ }
+ })
+ ixCutover(t, fx)
+ boxEnd(t, box, interactive.End{Reason: interactive.EndExited})
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Reason != interactive.EndExited || e.Exit != 0 {
+ t.Fatalf("CLI end %+v, want exited 0 at once", e)
+ }
+ ixWaitHub(t, h, id, "pending")
+ key := interactive.GrantKey(fx.acct, "shop", id)
+ stays := func(what string) {
+ t.Helper()
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive == nil || rec.Interactive.ID != id {
+ t.Fatalf("%s: marker %+v, want %s kept", what, rec.Interactive, id)
+ }
+ if _, _, err := fx.rel.Get(context.Background(), key); err != nil {
+ t.Fatalf("%s: the grant: %v", what, err)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("%s: end rows %+v", what, evs)
+ }
+ }
+ stays("while draining")
+ if ixSweep(fx) {
+ t.Fatal("a sweep pass was admitted while draining")
+ }
+ stays("after a refused sweep pass")
+ held.done()
+ released = true
+ ixActivate(t, fx, clock)
+ if !ixSweep(fx) {
+ t.Fatal("the sweep pass was not admitted after activation")
+ }
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive != nil {
+ t.Fatalf("marker %+v left after the sweep", rec.Interactive)
+ }
+ if gs := ixGrants(t, fx); len(gs) != 0 {
+ t.Fatalf("grants %v left after the sweep", gs)
+ }
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || ixEndRow(t, evs[0]).Reason != interactive.EndExited || ixEndRow(t, evs[0]).ID != id || ixEndRow(t, evs[0]).Box != "box-1" {
+ t.Fatalf("end rows %+v, want one exited from box-1 (not lost)", evs)
+ }
+ if !ixSweep(fx) {
+ t.Fatal("the second sweep pass was not admitted")
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 1 {
+ t.Fatalf("a second pass wrote again: %+v", evs)
+ }
+}
+
// ---- the request budget (PF-22) -------------------------------------------
// ixBudgetClass names the object a store request touched.
@@ -298,13 +416,15 @@ func ixBudgetClass(path string) string {
// TestInteractiveRequestBudget counts, at the production deployment store's
// wire (an s3fake behind NewDeploymentS3Store, change index on), every store
-// request one ordinary session makes: admitted, waiting, ended. Judged is
-// lifetimes on (the record read is the record GET and the slot GET), legacy
-// is the gate before. carlos console adds the channel pointer and the
-// manifest. Any request beyond these is a defect.
+// request one ordinary session makes: admitted, attached, ended by its box.
+// Judged is lifetimes on (the record read is the record GET and the slot
+// GET), legacy is the gate before. carlos console adds the channel pointer
+// and the manifest. Any request beyond these is a defect.
//
-// The box's attach (Task 11) adds no console request: the box door reads
-// the hub, the token and the registry, and writes nothing.
+// The box's attach (Task 11) adds no store request: the box door reads the
+// hub, the token and, for a fleet box, the registry (SQLite, no bucket),
+// and writes nothing; the splice moves frames only. The fleet case proves
+// it on a fleet box's credential.
func TestInteractiveRequestBudget(t *testing.T) {
type counts map[string]int
legacy := counts{
@@ -329,13 +449,15 @@ func TestInteractiveRequestBudget(t *testing.T) {
name string
judged bool
console bool
+ fleet bool
want counts
total int
}{
- {"legacy", false, false, legacy, 18},
- {"legacy console", false, true, plus(legacy, console), 20},
- {"judged", true, false, judged, 21},
- {"judged console", true, true, plus(judged, console), 23},
+ {"legacy", false, false, false, legacy, 18},
+ {"legacy console", false, true, false, plus(legacy, console), 20},
+ {"judged", true, false, false, judged, 21},
+ {"judged console", true, true, false, plus(judged, console), 23},
+ {"judged fleet", true, false, true, judged, 21},
} {
t.Run(c.name, func(t *testing.T) {
clock := useLifetimesClock(t)
@@ -343,6 +465,10 @@ func TestInteractiveRequestBudget(t *testing.T) {
fx := newInteractiveFxWith(t, 7, "code-ix-budget", consoleFixtureOptions{WithKey: true, S3: lat})
ixWorld(t, fx)
o := ixOpenArgv()
+ var fleetBearer string
+ if c.fleet {
+ fleetBearer, _, _ = ixFleetWorld(t, fx, fx.acct)
+ }
if c.console {
no := false
ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "uk"})
@@ -366,8 +492,24 @@ func TestInteractiveRequestBudget(t *testing.T) {
return 0, nil
})
ws := ixStart(t, fx, fx.alice, o)
- ws.Close()
- ixWaitEvents(t, fx, "interactive-end", 1)
+ // The test's own reads go to the seeded DirStore, not the wire.
+ id, g := ixSessionGrant(t, fx, ixHost)
+ hdr := boxHeader(g.Token)
+ if c.fleet {
+ hdr = fleetHeader(g.Token, "home/b1", fleetBearer)
+ }
+ mu.Lock()
+ before := len(log)
+ mu.Unlock()
+ box, _ := boxAttach(t, fx, id, hdr)
+ ixPingPong(t, ws, box, "budget")
+ mu.Lock()
+ attached := len(log) - before
+ mu.Unlock()
+ if attached != 0 {
+ t.Fatalf("the attach and the splice made %d store requests, want none", attached)
+ }
+ ixFinish(t, fx, ws, box, 1)
lat.Fake().OnRequest(nil)
mu.Lock()
defer mu.Unlock()
diff --git a/internal/console/apiinteractivebox.go b/internal/console/apiinteractivebox.go
new file mode 100644
index 000000000..638288669
--- /dev/null
+++ b/internal/console/apiinteractivebox.go
@@ -0,0 +1,131 @@
+// The console's box door (rootfs apps spec §5.10/C9, Plan 6 Task 11): GET
+// /api/box/interactive/{id}, a WebSocket. The box that owns a session's
+// instance dials it from the session's grant (Task 12) and the console
+// splices it to the waiting CLI (interactivehub.go).
+//
+// GATE: the box authenticates with the session's own token
+// (X-Carlos-Session-Token, the grant's bearer, checked against the hash the
+// hub keeps, in constant time) and, for an instance placed on a fleet, with
+// a fleet identity of that fleet: the store door's two headers,
+// "Authorization: Bearer <token>" and "Carlos-Tunnel-Name: <fleet>/<label>",
+// of an active box of the fleet the session's record names, in a fleet the
+// session's account owns (fleetIdentityOK). Every refusal is the same
+// http.NotFound, so the door says nothing about which ids exist, which are
+// ended, or whose they are; a second attach to a live session is 409.
+//
+// LIFETIMES (PF-4): the door reads and writes no instance record. It checks
+// the hub, the token and the registry, against the fleet Task 10 stored on
+// the hub session at admission, so lifetimesExempt names its prefix and the
+// box's leg, open as long as the session, holds no unit. The session's end
+// is Task 10's end step, in its own unit.
+package console
+
+import (
+ "crypto/subtle"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// boxLabelShape bounds a platform box's X-Carlos-Box header, which is used
+// only in the End and the audit row: anything else is dropped.
+var boxLabelShape = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
+
+// handleBoxInteractive is the box door. Before the upgrade, in order: a
+// host-claim console (409 RFS-6-C35); an id that is not a session id, not
+// active in this console's hub (reserved, ended, pending, pruned or
+// unknown), a wrong session token, or a fleet session without its fleet's
+// identity (404, all the same); a session a box already took (409). Then
+// the WebSocket, handed to the waiting session, which splices it.
+func (s *Server) handleBoxInteractive(w http.ResponseWriter, r *http.Request) {
+ if s.cfg.HostClaim {
+ jsonError(w, http.StatusConflict, claimInteractiveUnsupportedMsg)
+ return
+ }
+ h := s.interactive
+ id := r.PathValue("id")
+ if !interactive.ValidID(id) {
+ http.NotFound(w, r)
+ return
+ }
+ sess := h.activeSession(id)
+ if sess == nil || !interactive.TokenMatches(r.Header.Get(interactive.HeaderToken), sess.tokenHash) {
+ http.NotFound(w, r)
+ return
+ }
+ label := ""
+ if sess.fleet != "" {
+ name := r.Header.Get("Carlos-Tunnel-Name")
+ token, bearer := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
+ reg, err := h.registry(s.cfg.Registry)
+ if !bearer || err != nil || !fleetIdentityOK(reg, name, token, sess.fleet, sess.acct) {
+ http.NotFound(w, r)
+ return
+ }
+ _, label, _ = strings.Cut(name, "/")
+ } else if b := r.Header.Get("X-Carlos-Box"); boxLabelShape.MatchString(b) {
+ label = b
+ }
+ if !h.claimAttach(id) {
+ // Either a box already took it (409), or the session ended since the
+ // lookup above (404, as any ended id).
+ if h.activeSession(id) == nil {
+ http.NotFound(w, r)
+ return
+ }
+ http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
+ return
+ }
+ box := &boxConn{box: label, done: make(chan struct{})}
+ upgraded := false
+ interactive.NewServer(func(ws *websocket.Conn) {
+ upgraded = true
+ // The hijacked connection keeps the server's ReadTimeout deadlines;
+ // the splice sets the leg's own.
+ _ = ws.SetDeadline(time.Time{})
+ box.ws = ws
+ if h.beforeHandoff != nil {
+ h.beforeHandoff(id)
+ }
+ select {
+ case sess.attach <- box:
+ <-box.done
+ case <-sess.over:
+ // The session ended before it took the box: nothing was sent.
+ }
+ }).ServeHTTP(w, r)
+ if !upgraded {
+ // The handshake refused (no subprotocol, not an upgrade): the
+ // session is free for its box.
+ h.releaseAttach(id)
+ }
+}
+
+// fleetIdentityOK reports whether name and token are a fleet identity the
+// box door accepts for a session on wantFleet of wantAccount (PF-16): name
+// is "<fleet>/<label>" with fleet wantFleet; the fleets table says
+// wantFleet belongs to wantAccount (FleetOwners, the hub's rule from fleet
+// public routes; an error reading it refuses); the box is registered and
+// active; and the sha256 hex of token is its TokenHash (mintFleetToken's
+// convention), compared in constant time.
+func fleetIdentityOK(reg consoleRegistry, name, token, wantFleet, wantAccount string) bool {
+ fleet, label, ok := strings.Cut(name, "/")
+ if !ok || fleet != wantFleet || !registry.ValidTunnelName(label) || token == "" || wantAccount == "" {
+ return false
+ }
+ owners, err := reg.FleetOwners()
+ if err != nil || owners[wantFleet] != wantAccount {
+ return false
+ }
+ box, err := findFleetBox(reg, fleet, label)
+ if err != nil || box == nil || box.Status != "active" {
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(hashToken(token)), []byte(box.TokenHash)) == 1
+}
diff --git a/internal/console/apiinteractivebox_test.go b/internal/console/apiinteractivebox_test.go
new file mode 100644
index 000000000..50ee0348d
--- /dev/null
+++ b/internal/console/apiinteractivebox_test.go
@@ -0,0 +1,975 @@
+package console
+
+// The console's box door and the splice (rootfs apps Plan 6 Task 11): GET
+// /api/box/interactive/{id}, its refusals before the upgrade, the fleet
+// box's credential, one box per session, and the splice that carries frames
+// both ways until one end goes. Every test goes through the real console
+// (newConsoleFixture's NewServer, its mux and serveAdmitted), the real
+// session door for the CLI leg and a real WebSocket for the box. Account
+// bah (and baj as another account), app shop, host shop.example.com.
+
+import (
+ "bytes"
+ "context"
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "runtime"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// boxURL is the box door for session id.
+func (fx *interactiveFx) boxURL(id string) string {
+ return fx.ts.URL + interactive.AttachPathPrefix + id
+}
+
+// ixSessionGrant is the session open on host: its id and its grant, read
+// from the bucket and verified under the release key, as a box reads it.
+func ixSessionGrant(t *testing.T, fx *interactiveFx, host string) (string, interactive.Grant) {
+ t.Helper()
+ rec, _ := ixRecord(t, fx, host)
+ if rec.Interactive == nil {
+ t.Fatalf("no session marker on %s", host)
+ }
+ wire, _, err := fx.rel.Get(context.Background(), interactive.GrantKey(fx.acct, "shop", rec.Interactive.ID))
+ if err != nil {
+ t.Fatalf("the grant: %v", err)
+ }
+ g, err := interactive.VerifyGrant(fx.pub, wire, time.Now())
+ if err != nil {
+ t.Fatalf("the grant: %v", err)
+ }
+ return rec.Interactive.ID, g
+}
+
+// boxHeader is a platform box's attach headers.
+func boxHeader(token string) http.Header {
+ return http.Header{interactive.HeaderToken: {token}, "X-Carlos-Box": {"box-1"}}
+}
+
+// fleetHeader is a fleet box's attach headers: the session token and the
+// fleet credential, the store door's two headers.
+func fleetHeader(token, name, bearer string) http.Header {
+ h := http.Header{interactive.HeaderToken: {token}, "Carlos-Tunnel-Name": {name}}
+ if bearer != "" {
+ h.Set("Authorization", "Bearer "+bearer)
+ }
+ return h
+}
+
+// boxDial dials the box door for id with hdr, as a box does. The
+// connection is closed when the test ends.
+func boxDial(t *testing.T, fx *interactiveFx, id string, hdr http.Header) (*websocket.Conn, error) {
+ t.Helper()
+ wsURL, err := interactive.WebSocketURL(fx.boxURL(id))
+ if err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ ws, err := interactive.Dial(ctx, wsURL, fx.ts.URL, hdr)
+ if err == nil {
+ t.Cleanup(func() { ws.Close() })
+ }
+ return ws, err
+}
+
+// boxProbe is the door's answer to a WebSocket upgrade request for id
+// with hdr: its status and body. It is for refusals: a 101 is closed at
+// once (and claims the session).
+func boxProbe(t *testing.T, fx *interactiveFx, id string, hdr http.Header) (int, string) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodGet, fx.boxURL(id), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header = hdr.Clone()
+ var key [16]byte
+ _, _ = rand.Read(key[:])
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ req.Header.Set("Sec-WebSocket-Version", "13")
+ req.Header.Set("Sec-WebSocket-Key", base64.StdEncoding.EncodeToString(key[:]))
+ req.Header.Set("Sec-WebSocket-Protocol", interactive.Subprotocol)
+ req.Header.Set("Origin", fx.ts.URL)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode == http.StatusSwitchingProtocols {
+ return res.StatusCode, ""
+ }
+ body, _ := io.ReadAll(res.Body)
+ return res.StatusCode, string(body)
+}
+
+// boxRefused wants http.NotFound's answer for id with hdr, and no upgrade
+// for a real dial either.
+func boxRefused(t *testing.T, fx *interactiveFx, what, id string, hdr http.Header) {
+ t.Helper()
+ if code, body := boxProbe(t, fx, id, hdr); code != http.StatusNotFound || body != "404 page not found\n" {
+ t.Fatalf("%s: %d %q, want http.NotFound's 404", what, code, body)
+ }
+ if ws, err := boxDial(t, fx, id, hdr); err == nil {
+ ws.Close()
+ t.Fatalf("%s: the dial upgraded", what)
+ }
+}
+
+// ixFrameOf reads the next frame that is not a keepalive, within 10 s.
+func ixFrameOf(ws *websocket.Conn) (byte, []byte, error) {
+ for {
+ kind, payload, err := ixRecv(ws)
+ if err != nil || kind != interactive.KindAlive {
+ return kind, payload, err
+ }
+ }
+}
+
+// boxWant reads the next frame that is not a keepalive and wants kind.
+func boxWant(t *testing.T, ws *websocket.Conn, kind byte) []byte {
+ t.Helper()
+ k, p, err := ixFrameOf(ws)
+ if err != nil || k != kind {
+ t.Fatalf("frame %q (%q) %v, want %q", k, p, err, kind)
+ }
+ return p
+}
+
+// boxAttach dials the box door and wants the Open the CLI sent.
+func boxAttach(t *testing.T, fx *interactiveFx, id string, hdr http.Header) (*websocket.Conn, interactive.Open) {
+ t.Helper()
+ ws, err := boxDial(t, fx, id, hdr)
+ if err != nil {
+ t.Fatalf("attach: %v", err)
+ }
+ var o interactive.Open
+ if err := json.Unmarshal(boxWant(t, ws, interactive.KindOpen), &o); err != nil {
+ t.Fatal(err)
+ }
+ return ws, o
+}
+
+// endOf decodes an End frame's payload.
+func endOf(t *testing.T, p []byte) interactive.End {
+ t.Helper()
+ var e interactive.End
+ if err := json.Unmarshal(p, &e); err != nil {
+ t.Fatal(err)
+ }
+ return e
+}
+
+// boxEnd sends the box's End.
+func boxEnd(t *testing.T, ws *websocket.Conn, e interactive.End) {
+ t.Helper()
+ if err := interactive.SendJSON(ws, interactive.KindEnd, e); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// ixStartOn opens a waiting session on host as token.
+func ixStartOn(t *testing.T, fx *interactiveFx, host, token string) *websocket.Conn {
+ t.Helper()
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(host), token)
+ if err != nil {
+ t.Fatalf("dial: %v", err)
+ }
+ ixSendOpen(t, ws, ixOpenArgv())
+ ixWantWaiting(t, ws)
+ return ws
+}
+
+// hubAttached reports whether the hub holds id with a box attached.
+func hubAttached(h *interactiveHub, id string) bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ s := h.byID[id]
+ return s != nil && s.attached
+}
+
+// ixStillWaits proves the CLI's session is still open and unattached: the
+// hub holds it active and the console answers its keepalive.
+func ixStillWaits(t *testing.T, fx *interactiveFx, cli *websocket.Conn, id string) {
+ t.Helper()
+ if st := hubState(fx.srv.interactive, id); st != "active" {
+ t.Fatalf("hub: %q, want active", st)
+ }
+ if hubAttached(fx.srv.interactive, id) {
+ t.Fatal("the hub has the session attached")
+ }
+ if err := interactive.Send(cli, interactive.KindAlive, nil); err != nil {
+ t.Fatal(err)
+ }
+ if k, _, err := ixRecv(cli); err != nil || k != interactive.KindAlive {
+ t.Fatalf("the CLI's keepalive: %q %v", k, err)
+ }
+}
+
+// ixFinish ends a spliced session from the box with exited 0 and wants the
+// CLI to get it, then the n-th interactive-end row.
+func ixFinish(t *testing.T, fx *interactiveFx, cli, box *websocket.Conn, n int) {
+ t.Helper()
+ boxEnd(t, box, interactive.End{Reason: interactive.EndExited})
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Reason != interactive.EndExited {
+ t.Fatalf("CLI end %+v", e)
+ }
+ ixWaitEvents(t, fx, "interactive-end", n)
+}
+
+func TestBoxDoorRefusesWithoutTheToken(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-token")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ other, _, _ := interactive.MintToken()
+ for _, c := range []struct {
+ what string
+ id string
+ hdr http.Header
+ }{
+ {"no token", id, http.Header{"X-Carlos-Box": {"box-1"}}},
+ {"empty token", id, boxHeader("")},
+ {"wrong token", id, boxHeader(other)},
+ {"the token as a bearer", id, http.Header{"Authorization": {"Bearer " + g.Token}}},
+ {"unknown id", "tty_aaaaaaaaaaaaaaaaaaaaaaaaaa", boxHeader(g.Token)},
+ {"bad id", "tty_short", boxHeader(g.Token)},
+ {"upper-case id", strings.ToUpper(id), boxHeader(g.Token)},
+ } {
+ boxRefused(t, fx, c.what, c.id, c.hdr)
+ ixStillWaits(t, fx, cli, id)
+ }
+ box, o := boxAttach(t, fx, id, boxHeader(g.Token))
+ if strings.Join(o.Argv, " ") != "bin/rails db:migrate:status" {
+ t.Fatalf("open %+v", o)
+ }
+ ixFinish(t, fx, cli, box, 1)
+}
+
+func TestBoxDoorOnAHostClaimConsole(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-claim")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ fx.srv.cfg.HostClaim = true
+ code, body := boxProbe(t, fx, id, boxHeader(g.Token))
+ fx.srv.cfg.HostClaim = false
+ if code != http.StatusConflict || interactiveError(t, body) != claimInteractiveUnsupportedMsg {
+ t.Fatalf("%d %q, want 409 RFS-6-C35", code, body)
+ }
+ ixStillWaits(t, fx, cli, id)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ ixFinish(t, fx, cli, box, 1)
+}
+
+// A session only reserved (its CAS landed, not yet active) is not one a
+// box may attach to: the same 404 as an unknown id (finding 10).
+func TestBoxDoorRefusesAReservedSession(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-reserved")
+ h := fx.srv.interactive
+ var probed atomic.Bool
+ h.afterAdmit = func(id string) {
+ wire, _, err := fx.rel.Get(context.Background(), interactive.GrantKey(fx.acct, "shop", id))
+ if err != nil {
+ t.Errorf("the grant at afterAdmit: %v", err)
+ return
+ }
+ g, err := interactive.VerifyGrant(fx.pub, wire, time.Now())
+ if err != nil {
+ t.Errorf("the grant: %v", err)
+ return
+ }
+ if st := hubState(h, id); st != "reserved" {
+ t.Errorf("hub: %q at afterAdmit, want reserved", st)
+ }
+ if code, body := boxProbe(t, fx, id, boxHeader(g.Token)); code != http.StatusNotFound || body != "404 page not found\n" {
+ t.Errorf("a reserved session: %d %q, want 404", code, body)
+ }
+ probed.Store(true)
+ }
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ h.afterAdmit = nil
+ if !probed.Load() {
+ t.Fatal("afterAdmit never ran")
+ }
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ ixFinish(t, fx, cli, box, 1)
+}
+
+// ixFleetWorld places shop.example.com on fleet/home, owned by owner, with
+// box b1 active and b2 detached, and fleet away (bah's) with box a1. It
+// returns the three boxes' bearer tokens.
+func ixFleetWorld(t *testing.T, fx *interactiveFx, owner string) (b1, b2, a1 string) {
+ t.Helper()
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mint := func() (string, string) {
+ plain, hash, err := mintFleetToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return plain, hash
+ }
+ for _, f := range []registry.Fleet{{Name: "home", Account: owner, Bucket: "home-data"}, {Name: "away", Account: fx.acct, Bucket: "away-data"}} {
+ if ok, err := reg.CreateFleet(f); err != nil || !ok {
+ t.Fatalf("create fleet %s: %v %v", f.Name, ok, err)
+ }
+ }
+ var h1, h2, ha string
+ b1, h1 = mint()
+ b2, h2 = mint()
+ a1, ha = mint()
+ for _, b := range []registry.FleetBox{{Fleet: "home", Label: "b1", TokenHash: h1}, {Fleet: "home", Label: "b2", TokenHash: h2}, {Fleet: "away", Label: "a1", TokenHash: ha}} {
+ if err := reg.AddFleetBox(b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := reg.SetFleetBoxStatus("home", "b2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ no := false
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "fleet/home"})
+ return b1, b2, a1
+}
+
+func TestBoxDoorNeedsTheFleetsOwnCredential(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-fleet")
+ b1, b2, a1 := ixFleetWorld(t, fx, fx.acct)
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ for _, c := range []struct {
+ what string
+ hdr http.Header
+ }{
+ {"no credential", boxHeader(g.Token)},
+ {"a name and no bearer", fleetHeader(g.Token, "home/b1", "")},
+ {"a bearer with no name", fleetHeader(g.Token, "", b1)},
+ {"a bearer without its Bearer prefix", http.Header{interactive.HeaderToken: {g.Token}, "Carlos-Tunnel-Name": {"home/b1"}, "Authorization": {b1}}},
+ {"the right box with another box's bearer", fleetHeader(g.Token, "home/b1", a1)},
+ {"the fleet name alone", fleetHeader(g.Token, "home", b1)},
+ {"an unknown box", fleetHeader(g.Token, "home/b9", b1)},
+ {"another fleet's box", fleetHeader(g.Token, "away/a1", a1)},
+ {"another fleet's box under this fleet's name", fleetHeader(g.Token, "home/a1", a1)},
+ {"a detached box", fleetHeader(g.Token, "home/b2", b2)},
+ {"the right box without the session token", fleetHeader("", "home/b1", b1)},
+ } {
+ boxRefused(t, fx, c.what, id, c.hdr)
+ ixStillWaits(t, fx, cli, id)
+ }
+ box, _ := boxAttach(t, fx, id, fleetHeader(g.Token, "home/b1", b1))
+ boxEnd(t, box, interactive.End{Reason: interactive.EndExited, Box: "claimed-by-the-box"})
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Reason != interactive.EndExited || e.Box != "b1" {
+ t.Fatalf("CLI end %+v, want exited from b1, the fleet name's label", e)
+ }
+ if d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0]); d.Box != "b1" {
+ t.Fatalf("end row %+v, want box b1", d)
+ }
+}
+
+// failingOwners is the registry with FleetOwners failing; owners, when
+// set, is still returned beside the error.
+type failingOwners struct {
+ consoleRegistry
+ owners map[string]string
+}
+
+func (f failingOwners) FleetOwners() (map[string]string, error) {
+ return f.owners, errors.New("injected fleet owners failure")
+}
+
+func TestBoxDoorRefusesAFleetOfAnotherAccount(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-owner")
+ baj := domains.Sqid(8)
+ b1, _, a1 := ixFleetWorld(t, fx, baj)
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ boxRefused(t, fx, "home belongs to baj", id, fleetHeader(g.Token, "home/b1", b1))
+ ixStillWaits(t, fx, cli, id)
+ cli.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+
+ // The same session shape on bah's own fleet away: refused while the
+ // owners cannot be read, attached once they can.
+ no := false
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "fleet/away"})
+ cli = ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g = ixSessionGrant(t, fx, ixHost)
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for what, owners := range map[string]map[string]string{"no owners": nil, "owners beside the error": {"away": fx.acct}} {
+ fx.srv.interactive.boxRegistry = func() (consoleRegistry, error) { return failingOwners{reg, owners}, nil }
+ boxRefused(t, fx, "FleetOwners failing, "+what, id, fleetHeader(g.Token, "away/a1", a1))
+ ixStillWaits(t, fx, cli, id)
+ }
+ fx.srv.interactive.boxRegistry = func() (consoleRegistry, error) { return nil, errors.New("injected registry open failure") }
+ boxRefused(t, fx, "the registry not opening", id, fleetHeader(g.Token, "away/a1", a1))
+ fx.srv.interactive.boxRegistry = nil
+ box, _ := boxAttach(t, fx, id, fleetHeader(g.Token, "away/a1", a1))
+ ixFinish(t, fx, cli, box, 2)
+}
+
+func TestBoxDoorTakesOneBox(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-one")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ if code, body := boxProbe(t, fx, id, boxHeader(g.Token)); code != http.StatusConflict {
+ t.Fatalf("a second attach: %d %q, want 409", code, body)
+ }
+ if ws, err := boxDial(t, fx, id, boxHeader(g.Token)); err == nil {
+ ws.Close()
+ t.Fatal("a second attach upgraded")
+ }
+ // The first box still carries the session.
+ if err := interactive.Send(box, interactive.KindData, []byte("hello\r\n")); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, cli, interactive.KindData); string(p) != "hello\r\n" {
+ t.Fatalf("CLI data %q", p)
+ }
+ ixFinish(t, fx, cli, box, 1)
+}
+
+// A dial whose upgrade fails (no subprotocol) does not take the session:
+// the right box still attaches after it.
+func TestBoxDoorAFailedUpgradeLeavesTheSessionFree(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-noproto")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ code, _, _ := rawReqHeader(t, http.MethodGet, fx.boxURL(id), "", "", map[string]string{interactive.HeaderToken: g.Token,
+ "Connection": "Upgrade", "Upgrade": "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ=="})
+ if code == http.StatusSwitchingProtocols || code == http.StatusNotFound || code == http.StatusConflict {
+ t.Fatalf("an upgrade with no subprotocol answered %d", code)
+ }
+ ixStillWaits(t, fx, cli, id)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ ixFinish(t, fx, cli, box, 1)
+}
+
+func TestBoxDoorRefusesAnEndedSessionBeforeItsPickupBy(t *testing.T) {
+ fx, clock := newIxLtFx(t, "code-ixb-ended")
+ h := fx.srv.interactive
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ held, ok, _ := fx.srv.lifetimesAdmit(context.Background(), true)
+ if !ok {
+ t.Fatal("the test's legacy unit was not admitted")
+ }
+ released := false
+ t.Cleanup(func() {
+ if !released {
+ held.done()
+ }
+ })
+ ixCutover(t, fx)
+ boxEnd(t, box, interactive.End{Reason: interactive.EndExited})
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Reason != interactive.EndExited {
+ t.Fatalf("CLI end %+v", e)
+ }
+ ixWaitHub(t, h, id, "pending")
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive == nil || rec.Interactive.ID != id {
+ t.Fatalf("marker %+v, want %s kept while draining", rec.Interactive, id)
+ }
+ if !g.PickupBy.After(time.Now()) {
+ t.Fatal("the grant's PickupBy has passed: the test proves nothing")
+ }
+ boxRefused(t, fx, "an ended session, pending", id, boxHeader(g.Token))
+ if st := hubState(h, id); st != "pending" {
+ t.Fatalf("hub: %q after the refused dial, want pending", st)
+ }
+ held.done()
+ released = true
+ ixActivate(t, fx, clock)
+ if !ixSweep(fx) {
+ t.Fatal("the sweep pass was not admitted after activation")
+ }
+ if st := hubState(h, id); st != "ended" {
+ t.Fatalf("hub: %q after the sweep, want ended", st)
+ }
+ boxRefused(t, fx, "an ended session, finished", id, boxHeader(g.Token))
+ if st := hubState(h, id); st != "ended" {
+ t.Fatalf("hub: %q, want ended (never active again)", st)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 1 || ixEndRow(t, evs[0]).Reason != interactive.EndExited {
+ t.Fatalf("end rows %+v, want one exited", evs)
+ }
+}
+
+func TestSpliceCarriesBothWays(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-splice")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, o := boxAttach(t, fx, id, boxHeader(g.Token))
+ if want := ixOpenArgv(); o.Schema != 1 || strings.Join(o.Argv, " ") != strings.Join(want.Argv, " ") || o.Process != "" ||
+ o.Term != want.Term || o.Cols != want.Cols || o.Rows != want.Rows {
+ t.Fatalf("the box's Open %+v, want the CLI's %+v", o, want)
+ }
+ if !hubAttached(fx.srv.interactive, id) {
+ t.Fatal("the hub does not have the session attached")
+ }
+ // CLI to box: data and a resize.
+ if err := interactive.Send(cli, interactive.KindData, []byte("puts 1\r")); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, box, interactive.KindData); string(p) != "puts 1\r" {
+ t.Fatalf("box data %q", p)
+ }
+ if err := interactive.Send(cli, interactive.KindResize, interactive.ResizePayload(120, 40)); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, box, interactive.KindResize); !bytes.Equal(p, interactive.ResizePayload(120, 40)) {
+ t.Fatalf("box resize %v", p)
+ }
+ // A keepalive is answered on its own leg, never forwarded.
+ if err := interactive.Send(cli, interactive.KindAlive, nil); err != nil {
+ t.Fatal(err)
+ }
+ if k, _, err := ixRecv(cli); err != nil || k != interactive.KindAlive {
+ t.Fatalf("the CLI's keepalive: %q %v", k, err)
+ }
+ if err := interactive.Send(box, interactive.KindAlive, nil); err != nil {
+ t.Fatal(err)
+ }
+ if k, _, err := ixRecv(box); err != nil || k != interactive.KindAlive {
+ t.Fatalf("the box's keepalive: %q %v", k, err)
+ }
+ // An Open from the CLI after the start is not a terminal frame: dropped.
+ ixSendOpen(t, cli, ixOpenArgv())
+ // Box to CLI: status, data and the end.
+ for _, st := range []string{interactive.StateStarting, interactive.StateStarted} {
+ if err := interactive.SendJSON(box, interactive.KindStatus, interactive.Status{State: st}); err != nil {
+ t.Fatal(err)
+ }
+ if state, end, err := ixNext(cli); err != nil || end != nil || state != st {
+ t.Fatalf("CLI status %q %+v %v, want %s", state, end, err, st)
+ }
+ }
+ if err := interactive.Send(box, interactive.KindData, []byte("1\r\n=> nil\r\n")); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, cli, interactive.KindData); string(p) != "1\r\n=> nil\r\n" {
+ t.Fatalf("CLI data %q", p)
+ }
+ if err := interactive.Send(cli, interactive.KindData, []byte("exit\r")); err != nil {
+ t.Fatal(err)
+ }
+ if p := boxWant(t, box, interactive.KindData); string(p) != "exit\r" {
+ t.Fatalf("box data %q (the dropped Open reached it?)", p)
+ }
+ started := time.Now().UTC().Add(-time.Second).Truncate(time.Second)
+ ended := time.Now().UTC().Truncate(time.Second)
+ boxEnd(t, box, interactive.End{Reason: interactive.EndExited, Exit: 3, Started: started, Ended: ended})
+ e := endOf(t, boxWant(t, cli, interactive.KindEnd))
+ if e.Reason != interactive.EndExited || e.Exit != 3 || e.Box != "box-1" || !e.Started.Equal(started) || !e.Ended.Equal(ended) {
+ t.Fatalf("CLI end %+v", e)
+ }
+ d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0])
+ if d.ID != id || d.Reason != interactive.EndExited || d.Exit != 3 || d.Box != "box-1" {
+ t.Fatalf("end row %+v", d)
+ }
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive != nil {
+ t.Fatalf("marker %+v left", rec.Interactive)
+ }
+ if gs := ixGrants(t, fx); len(gs) != 0 {
+ t.Fatalf("grants %v left", gs)
+ }
+ if st := hubState(fx.srv.interactive, id); st != "ended" {
+ t.Fatalf("hub: %q, want ended", st)
+ }
+
+ // carlos console: the box gets the Open as the CLI sent it, Process
+ // console and no argv, never the resolved command.
+ no := false
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "uk"})
+ shipShopRootfs(t, fx, "r1", []string{"bin/rails", "console"})
+ console := interactive.Open{Schema: 1, Process: release.ProcessConsole, Term: "xterm-256color", Cols: 100, Rows: 30}
+ cli = ixStart(t, fx, fx.alice, console)
+ id, g = ixSessionGrant(t, fx, ixHost)
+ box, o = boxAttach(t, fx, id, boxHeader(g.Token))
+ if o.Process != release.ProcessConsole || o.Argv != nil || o.Cols != 100 || o.Rows != 30 {
+ t.Fatalf("the box's Open %+v, want Process console and no argv", o)
+ }
+ ixFinish(t, fx, cli, box, 2)
+}
+
+func TestSpliceAppliesBackpressure(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-pressure")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+
+ const total = 64 << 20
+ const chunk = 32 << 10
+ var sent atomic.Int64
+ pushed := make(chan error, 1)
+ runtime.GC()
+ var before runtime.MemStats
+ runtime.ReadMemStats(&before)
+ go func() {
+ buf := bytes.Repeat([]byte("x"), chunk)
+ _ = box.SetWriteDeadline(time.Time{})
+ for sent.Load() < total {
+ if err := interactive.Send(box, interactive.KindData, buf); err != nil {
+ pushed <- err
+ return
+ }
+ sent.Add(chunk)
+ }
+ pushed <- nil
+ }()
+ // The CLI reads nothing: once the transport's buffers are full, the
+ // box's Send blocks and the count stops.
+ deadline := time.Now().Add(30 * time.Second)
+ last, still := int64(-1), 0
+ for still < 4 {
+ if time.Now().After(deadline) {
+ t.Fatalf("the box's sends never stalled: %d bytes sent", sent.Load())
+ }
+ time.Sleep(150 * time.Millisecond)
+ if n := sent.Load(); n == last {
+ still++
+ } else {
+ last, still = n, 0
+ }
+ }
+ if last >= total {
+ t.Fatalf("the box sent all %d bytes to a CLI that reads nothing", total)
+ }
+ runtime.GC()
+ var during runtime.MemStats
+ runtime.ReadMemStats(&during)
+ if grew := int64(during.HeapAlloc) - int64(before.HeapAlloc); grew > 4<<20 {
+ t.Fatalf("the heap grew %d bytes while the box pushed %d (stalled), want under 4 MiB", grew, last)
+ }
+ t.Logf("stalled after %d bytes; heap %d -> %d", last, before.HeapAlloc, during.HeapAlloc)
+ // The CLI reads again: every byte arrives, in order and whole.
+ var got int64
+ for got < total {
+ k, p, err := ixFrameOf(cli)
+ if err != nil || k != interactive.KindData {
+ t.Fatalf("CLI frame %q %v after %d bytes", k, err, got)
+ }
+ if bytes.IndexFunc(p, func(r rune) bool { return r != 'x' }) >= 0 {
+ t.Fatalf("CLI data corrupted after %d bytes", got)
+ }
+ got += int64(len(p))
+ }
+ if err := <-pushed; err != nil {
+ t.Fatal(err)
+ }
+ if got != total {
+ t.Fatalf("CLI got %d bytes, want %d", got, total)
+ }
+ ixFinish(t, fx, cli, box, 1)
+}
+
+func TestCLIGoneHangsUpTheBox(t *testing.T) {
+ t.Run("the box answers", func(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-hangup")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ cli.Close()
+ if e := endOf(t, boxWant(t, box, interactive.KindEnd)); e.Reason != interactive.EndHangup {
+ t.Fatalf("box end %+v, want hangup", e)
+ }
+ boxEnd(t, box, interactive.End{Reason: interactive.EndHangup, Exit: 129})
+ d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0])
+ if d.ID != id || d.Reason != interactive.EndHangup || d.Exit != 129 || d.Box != "box-1" {
+ t.Fatalf("end row %+v, want the box's hangup End", d)
+ }
+ })
+ t.Run("the box does not answer", func(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-hangup-quiet")
+ fx.srv.interactive.hangupWait = 300 * time.Millisecond
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ cli.Close()
+ if e := endOf(t, boxWant(t, box, interactive.KindEnd)); e.Reason != interactive.EndHangup {
+ t.Fatalf("box end %+v, want hangup", e)
+ }
+ d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0])
+ if d.ID != id || d.Reason != interactive.EndHangup || d.Box != "box-1" {
+ t.Fatalf("end row %+v, want hangup", d)
+ }
+ })
+}
+
+func TestBoxGoneEndsTheCLIAsLost(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-lost")
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ box.Close()
+ e := endOf(t, boxWant(t, cli, interactive.KindEnd))
+ if e.Reason != interactive.EndLost || e.Box != "box-1" || e.Ended.IsZero() {
+ t.Fatalf("CLI end %+v, want lost from box-1", e)
+ }
+ d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0])
+ if d.ID != id || d.Reason != interactive.EndLost || d.Box != "box-1" {
+ t.Fatalf("end row %+v", d)
+ }
+}
+
+// ixChatter sends a keepalive on ws every 50 ms until stop closes.
+func ixChatter(ws *websocket.Conn, stop <-chan struct{}) {
+ go func() {
+ t := time.NewTicker(50 * time.Millisecond)
+ defer t.Stop()
+ for {
+ select {
+ case <-stop:
+ return
+ case <-t.C:
+ if interactive.Send(ws, interactive.KindAlive, nil) != nil {
+ return
+ }
+ }
+ }
+ }()
+}
+
+func TestSilentLegIsLost(t *testing.T) {
+ short := func(fx *interactiveFx) {
+ fx.srv.interactive.keepaliveEvery = 50 * time.Millisecond
+ fx.srv.interactive.keepaliveLost = 400 * time.Millisecond
+ }
+ t.Run("both legs talking outlive KeepaliveLost", func(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-chatty")
+ short(fx)
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ // Before either leg says anything, the console's own keepalives
+ // arrive on both, every KeepaliveEvery.
+ var wg sync.WaitGroup
+ for name, ws := range map[string]*websocket.Conn{"cli": cli, "box": box} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ alive := 0
+ until := time.Now().Add(300 * time.Millisecond)
+ for {
+ _ = ws.SetReadDeadline(until)
+ k, _, err := interactive.Receive(ws)
+ if err != nil {
+ break
+ }
+ if k == interactive.KindAlive {
+ alive++
+ }
+ }
+ if alive < 3 {
+ t.Errorf("%s: %d keepalives from the console in 300 ms, want one every 50 ms", name, alive)
+ }
+ }()
+ }
+ wg.Wait()
+ if t.Failed() {
+ t.FailNow()
+ }
+ stop := make(chan struct{})
+ ixChatter(cli, stop)
+ ixChatter(box, stop)
+ // Read both legs for three times KeepaliveLost: only keepalives, the
+ // console's own among them.
+ for name, ws := range map[string]*websocket.Conn{"cli": cli, "box": box} {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ until := time.Now().Add(1200 * time.Millisecond)
+ for time.Now().Before(until) {
+ _ = ws.SetReadDeadline(until)
+ k, _, err := interactive.Receive(ws)
+ if err != nil {
+ if ne, ok := err.(interface{ Timeout() bool }); ok && ne.Timeout() {
+ return
+ }
+ t.Errorf("%s: %v", name, err)
+ return
+ }
+ if k != interactive.KindAlive {
+ t.Errorf("%s: frame %q, want only keepalives", name, k)
+ return
+ }
+ }
+ }()
+ }
+ wg.Wait()
+ close(stop)
+ if st := hubState(fx.srv.interactive, id); st != "active" {
+ t.Fatalf("hub: %q, want the session still open", st)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("the session ended: %+v", evs)
+ }
+ })
+ t.Run("a silent box is lost", func(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-silent-box")
+ short(fx)
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ boxAttach(t, fx, id, boxHeader(g.Token))
+ stop := make(chan struct{})
+ defer close(stop)
+ ixChatter(cli, stop)
+ alive := 0
+ until := time.Now().Add(10 * time.Second)
+ for {
+ if time.Now().After(until) {
+ t.Fatal("no End within 10 s of a silent box")
+ }
+ k, p, err := ixRecv(cli)
+ if err != nil {
+ t.Fatalf("CLI: %v", err)
+ }
+ if k == interactive.KindAlive {
+ alive++
+ continue
+ }
+ if k != interactive.KindEnd {
+ t.Fatalf("CLI frame %q", k)
+ }
+ if e := endOf(t, p); e.Reason != interactive.EndLost {
+ t.Fatalf("CLI end %+v, want lost", e)
+ }
+ break
+ }
+ if alive < 3 {
+ t.Fatalf("the CLI got %d keepalives before the end, want the console's own every 50 ms", alive)
+ }
+ if d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0]); d.Reason != interactive.EndLost {
+ t.Fatalf("end row %+v", d)
+ }
+ })
+ t.Run("a silent CLI hangs up the box", func(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-silent-cli")
+ short(fx)
+ ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ stop := make(chan struct{})
+ defer close(stop)
+ ixChatter(box, stop)
+ if e := endOf(t, boxWant(t, box, interactive.KindEnd)); e.Reason != interactive.EndHangup {
+ t.Fatalf("box end %+v, want hangup", e)
+ }
+ boxEnd(t, box, interactive.End{Reason: interactive.EndHangup, Exit: 129})
+ if d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0]); d.Reason != interactive.EndHangup {
+ t.Fatalf("end row %+v", d)
+ }
+ })
+}
+
+func TestSpliceEndsAtTheLimit(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-limit")
+ fx.srv.interactive.maxDuration = 300 * time.Millisecond
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, boxHeader(g.Token))
+ if e := endOf(t, boxWant(t, box, interactive.KindEnd)); e.Reason != interactive.EndLimit {
+ t.Fatalf("box end %+v, want limit", e)
+ }
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Reason != interactive.EndLimit || e.Box != "box-1" {
+ t.Fatalf("CLI end %+v, want limit", e)
+ }
+ if d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", 1)[0]); d.Reason != interactive.EndLimit {
+ t.Fatalf("end row %+v", d)
+ }
+}
+
+// A platform box's X-Carlos-Box is used only in the End and the audit row,
+// and only when it has a box name's shape.
+func TestBoxDoorDropsAMalformedBoxLabel(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-label")
+ for i, label := range []string{"box 1", strings.Repeat("b", 65), "-box", "box\"1"} {
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, _ := boxAttach(t, fx, id, http.Header{interactive.HeaderToken: {g.Token}, "X-Carlos-Box": {label}})
+ boxEnd(t, box, interactive.End{Reason: interactive.EndExited})
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Box != "" {
+ t.Fatalf("%q: CLI end %+v, want no box", label, e)
+ }
+ if d := ixEndRow(t, ixWaitEvents(t, fx, "interactive-end", i+1)[0]); d.Box != "" {
+ t.Fatalf("%q: end row %+v, want no box", label, d)
+ }
+ }
+}
+
+// A box upgraded for a session that ends before it is handed over (here,
+// its pickup window closes) gives up: its connection is closed with no Open.
+func TestBoxDoorGivesUpOnASessionThatEnds(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-handoff")
+ h := fx.srv.interactive
+ h.pickupWindow = time.Second
+ release := make(chan struct{})
+ h.beforeHandoff = func(string) { <-release }
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ id, g := ixSessionGrant(t, fx, ixHost)
+ box, err := boxDial(t, fx, id, boxHeader(g.Token))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if e := endOf(t, boxWant(t, cli, interactive.KindEnd)); e.Reason != interactive.EndExpired {
+ t.Fatalf("CLI end %+v, want expired", e)
+ }
+ ixWaitHub(t, h, id, "ended")
+ close(release)
+ if k, p, err := ixRecv(box); err == nil {
+ t.Fatalf("the box got %q %q, want its connection closed", k, p)
+ } else if ne, ok := err.(interface{ Timeout() bool }); ok && ne.Timeout() {
+ t.Fatal("the box door still holds the connection")
+ }
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+// fleetIdentityOK's rule, on the registry the door reads.
+func TestFleetIdentityOK(t *testing.T) {
+ fx := newIxFx(t, "code-ixb-identity")
+ b1, b2, a1 := ixFleetWorld(t, fx, fx.acct)
+ reg, err := openRegistry(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range []struct {
+ what string
+ reg consoleRegistry
+ name, token, account string
+ want bool
+ }{
+ {"the right box", reg, "home/b1", b1, fx.acct, true},
+ {"another account", reg, "home/b1", b1, domains.Sqid(8), false},
+ {"a detached box", reg, "home/b2", b2, fx.acct, false},
+ {"another fleet", reg, "away/a1", a1, fx.acct, false},
+ {"a wrong token", reg, "home/b1", a1, fx.acct, false},
+ {"no token", reg, "home/b1", "", fx.acct, false},
+ {"no label", reg, "home/", b1, fx.acct, false},
+ {"a label with a slash", reg, "home/b1/x", b1, fx.acct, false},
+ {"owners failing", failingOwners{reg, map[string]string{"home": fx.acct}}, "home/b1", b1, fx.acct, false},
+ } {
+ if got := fleetIdentityOK(c.reg, c.name, c.token, "home", c.account); got != c.want {
+ t.Errorf("%s: %v, want %v", c.what, got, c.want)
+ }
+ }
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index 40ebee291..e604595b9 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1662,6 +1662,19 @@ var claimFixtures = map[string]claimFixture{
status: http.StatusConflict,
msg: claimInteractiveUnsupportedMsg,
}},
+ // The interactive sessions' box door (apiinteractivebox.go): refused on
+ // a host-claim console first, before the session id is read. Its
+ // session would be bab/shop's, enrolled as the CLI door's is.
+ "route GET /api/box/interactive/{id}": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"),
+ setup: func(t *testing.T, cx *claimCase) {
+ t.Helper()
+ cx.enroll(t, "bab", "shop")
+ },
+ do: claimRefusedAPI(http.MethodGet, "/api/box/interactive/tty_aaaaaaaaaaaaaaaaaaaaaaaaaa", ""),
+ status: http.StatusConflict,
+ msg: claimInteractiveUnsupportedMsg,
+ }},
"route GET /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}": {refused: &claimRefusalFixture{
apps: claimRefs("bab/titogo"),
do: claimRefusedAPI(http.MethodGet, "/api/cli/apps/bab/titogo/instances/acme.example.com/runs/run_aaaaaaaaaaaaaaaaaaaaaaaaaa", ""),
diff --git a/internal/console/interactivehub.go b/internal/console/interactivehub.go
index 27bc1fa0f..d0c83e345 100644
--- a/internal/console/interactivehub.go
+++ b/internal/console/interactivehub.go
@@ -1,9 +1,12 @@
package console
import (
+ "context"
"crypto/rand"
"encoding/hex"
+ "encoding/json"
"sync"
+ "sync/atomic"
"time"
"golang.org/x/net/websocket"
@@ -68,6 +71,19 @@ type interactiveHub struct {
afterAdmit func(id string)
pickupWindow time.Duration
openWaitFor time.Duration
+
+ //
+ // keepaliveEvery, keepaliveLost, maxDuration and hangupWait, when not
+ // 0, replace the splice's interactive.KeepaliveEvery, KeepaliveLost,
+ // MaxDuration + 1 minute and HangupGrace + 30 s. boxRegistry, when set,
+ // replaces the box door's openRegistry. beforeHandoff runs in the box
+ // door once its connection is upgraded, before it is handed over.
+ keepaliveEvery time.Duration
+ keepaliveLost time.Duration
+ maxDuration time.Duration
+ hangupWait time.Duration
+ boxRegistry func() (consoleRegistry, error)
+ beforeHandoff func(id string)
}
// hubSession is one session this console admitted.
@@ -85,17 +101,28 @@ type hubSession struct {
version string // the release a console process resolved from, for the audit row
cli *websocket.Conn
// attach is where the box door hands the box's connection (Task 11).
- attach chan *boxConn
+ attach chan *boxConn
+ // over is closed when the hub ends the session (end), so a box door
+ // waiting to hand its connection over gives up.
+ over chan struct{}
pickupBy time.Time
// active is false while the id is only reserved (finding 10): the box
// door attaches only to an active session.
active bool
+ // attached is set, under the hub's lock, once a box door has passed
+ // every check for this session: a second attach is 409 (door rule 3).
+ attached bool
+ // cliLeg is the CLI connection's single reader, which the waiting
+ // session hands to the splice.
+ cliLeg *cliLeg
}
-// boxConn is a box's attached connection (Task 11's door builds it).
+// boxConn is a box's attached connection: the box door builds it and waits
+// on done, which the splice closes when the session is over with the box.
type boxConn struct {
- ws *websocket.Conn
- box string
+ ws *websocket.Conn
+ box string // the box's label, for the End and the audit row only
+ done chan struct{}
}
func newInteractiveHub() *interactiveHub {
@@ -196,6 +223,36 @@ func (h *interactiveHub) activeSession(id string) *hubSession {
return nil
}
+// claimAttach takes an active, unattached session id for a box: false for
+// any other id (door rules 2 and 3 tell them apart by activeSession).
+func (h *interactiveHub) claimAttach(id string) bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ sess, ok := h.byID[id]
+ if !ok || !sess.active || sess.attached {
+ return false
+ }
+ sess.attached = true
+ return true
+}
+
+// releaseAttach gives up a claim whose upgrade failed: no box is attached.
+func (h *interactiveHub) releaseAttach(id string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if sess, ok := h.byID[id]; ok {
+ sess.attached = false
+ }
+}
+
+// registry is the registry the box door checks a fleet box against.
+func (h *interactiveHub) registry(path string) (consoleRegistry, error) {
+ if h.boxRegistry != nil {
+ return h.boxRegistry()
+ }
+ return openRegistry(path)
+}
+
// end takes id out of the live set and marks it ended until its PickupBy.
// Called as a session ends, before its end step's writes: from then on no
// admission finds it live and the box door finds nothing to attach to.
@@ -211,6 +268,9 @@ func (h *interactiveHub) end(id string) {
}
delete(h.byID, id)
until = sess.pickupBy
+ if sess.over != nil {
+ close(sess.over)
+ }
}
h.ended[id] = until
}
@@ -268,6 +328,30 @@ func (h *interactiveHub) finished(id string) {
}
}
+// What the hub holds of an id, for the sweep.
+const (
+ hubUnknown = iota // never held here, released, or pruned
+ hubHeld // reserved or active
+ hubPending // ended, its end's writes waiting in endPending
+ hubEnded // ended, its writes done or under way
+)
+
+// stateOf is what the hub holds of id.
+func (h *interactiveHub) stateOf(id string) int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if _, ok := h.byID[id]; ok {
+ return hubHeld
+ }
+ if _, ok := h.endPending[id]; ok {
+ return hubPending
+ }
+ if _, ok := h.ended[id]; ok {
+ return hubEnded
+ }
+ return hubUnknown
+}
+
// prune forgets every ended id whose pickup window has passed by now.
func (h *interactiveHub) prune(now time.Time) {
h.mu.Lock()
@@ -282,3 +366,292 @@ func (h *interactiveHub) pruneLocked(now time.Time) {
}
}
}
+
+// ---- the splice (Task 11) ----------------------------------------------------
+
+// ixFrame is one session frame on its way from a reader to a writer.
+type ixFrame struct {
+ kind byte
+ payload []byte
+ // written, when not nil, gets the Send's outcome.
+ written chan error
+}
+
+// cliLeg is the CLI connection's single reader, as the waiting session runs
+// it (awaitBox): in carries each frame, gone closes when Receive fails (the
+// connection is done), and lost, once not 0, is the read deadline the
+// reader sets after every frame.
+type cliLeg struct {
+ in <-chan ixFrame
+ gone <-chan struct{}
+ lost *atomic.Int64
+}
+
+// legWriter is one leg's only writer: one goroutine, one frame at a time,
+// each Send synchronous and bounded by the leg's write deadline. Its input
+// is unbuffered, so a slow reader on the leg stalls whoever forwards to it,
+// back to the other leg's socket, and nothing queues in the console.
+type legWriter struct {
+ in chan ixFrame
+ dead chan struct{} // closed when a Send failed: the leg is gone
+ // gone is closed (shut) once the splice knows the leg's peer has gone:
+ // frames for it are dropped rather than waiting on a dead socket.
+ gone chan struct{}
+ shutOnce sync.Once
+ stop <-chan struct{}
+}
+
+func startLegWriter(ws *websocket.Conn, wait time.Duration, stop <-chan struct{}) *legWriter {
+ w := &legWriter{in: make(chan ixFrame), dead: make(chan struct{}), gone: make(chan struct{}), stop: stop}
+ go func() {
+ for {
+ select {
+ case f := <-w.in:
+ _ = ws.SetWriteDeadline(time.Now().Add(wait))
+ err := interactive.Send(ws, f.kind, f.payload)
+ if f.written != nil {
+ f.written <- err
+ }
+ if err != nil {
+ close(w.dead)
+ return
+ }
+ case <-stop:
+ return
+ }
+ }
+ }()
+ return w
+}
+
+// send hands one frame to the writer, waiting while it writes the one
+// before. It is false once the leg is gone or the splice is over.
+func (w *legWriter) send(kind byte, payload []byte) bool {
+ select {
+ case w.in <- ixFrame{kind: kind, payload: payload}:
+ return true
+ case <-w.dead:
+ case <-w.gone:
+ case <-w.stop:
+ }
+ return false
+}
+
+// shut drops every later frame for the leg.
+func (w *legWriter) shut() { w.shutOnce.Do(func() { close(w.gone) }) }
+
+// sendWait sends one frame and waits until it is written.
+func (w *legWriter) sendWait(kind byte, payload []byte) bool {
+ done := make(chan error, 1)
+ select {
+ case w.in <- ixFrame{kind: kind, payload: payload, written: done}:
+ return <-done == nil
+ case <-w.dead:
+ case <-w.stop:
+ }
+ return false
+}
+
+// offer sends a keepalive only if the writer is idle: a leg busy writing is
+// talking already, and one stalled is bounded by its write deadline.
+func (w *legWriter) offer() {
+ select {
+ case w.in <- ixFrame{kind: interactive.KindAlive}:
+ default:
+ }
+}
+
+func (h *interactiveHub) aliveEvery() time.Duration {
+ if h.keepaliveEvery > 0 {
+ return h.keepaliveEvery
+ }
+ return interactive.KeepaliveEvery
+}
+
+func (h *interactiveHub) aliveLost() time.Duration {
+ if h.keepaliveLost > 0 {
+ return h.keepaliveLost
+ }
+ return interactive.KeepaliveLost
+}
+
+// limit is how long a spliced session may run: the run design's maximum
+// duration and a minute, after which the console ends it.
+func (h *interactiveHub) limit() time.Duration {
+ if h.maxDuration > 0 {
+ return h.maxDuration
+ }
+ return interactive.MaxDuration + time.Minute
+}
+
+// hangupWaitFor is how long a hung-up box has to send its End.
+func (h *interactiveHub) hangupWaitFor() time.Duration {
+ if h.hangupWait > 0 {
+ return h.hangupWait
+ }
+ return interactive.HangupGrace + 30*time.Second
+}
+
+// splice joins the waiting session's CLI to the box that attached, until
+// one end goes, and returns the session's End for the caller's end step
+// (endSession, which sends it to the CLI). Before it returns, the box's
+// connection is closed and box.done released.
+//
+// - The box gets the Open the CLI sent (sess.open: Process kept, never the
+// resolved argv).
+// - Box to CLI: Status, Data and the box's End. CLI to box: Data and a
+// well-formed Resize. A keepalive is answered on its own leg and never
+// forwarded; any other frame is dropped.
+// - Each leg has one reader (the CLI's is the waiting session's, handed
+// over through sess.cliLeg) and one writer (legWriter). Each read
+// deadline is KeepaliveLost, refreshed on every frame; the console sends
+// a keepalive to each leg every KeepaliveEvery.
+// - Endings: the CLI gone (or silent) sends End hangup to the box and
+// waits up to HangupGrace + 30 s for the box's End, which is then the
+// session's, else hangup; the box gone (or silent) is End lost; past
+// MaxDuration + 1 minute, End limit goes to the box and is the
+// session's; otherwise the box's End is the session's. ctx ending
+// (production passes none that does) hangs up the box as interrupted.
+//
+// Every End carries the box's label from the door.
+func (h *interactiveHub) splice(ctx context.Context, sess *hubSession, box *boxConn) interactive.End {
+ every, lost := h.aliveEvery(), h.aliveLost()
+ stop := make(chan struct{})
+ defer func() {
+ close(stop)
+ box.ws.Close()
+ close(box.done)
+ }()
+ stamp := func(e interactive.End) interactive.End {
+ if e.Ended.IsZero() {
+ e.Ended = time.Now().UTC()
+ }
+ if box.box != "" {
+ e.Box = box.box
+ }
+ return e
+ }
+ toCLI := startLegWriter(sess.cli, lost, stop)
+ toBox := startLegWriter(box.ws, lost, stop)
+ open, _ := json.Marshal(sess.open)
+ if !toBox.sendWait(interactive.KindOpen, open) {
+ return stamp(interactive.End{Reason: interactive.EndLost})
+ }
+ // The CLI's reader refreshes its deadline from here on.
+ leg := sess.cliLeg
+ leg.lost.Store(int64(lost))
+ _ = sess.cli.SetReadDeadline(time.Now().Add(lost))
+
+ // The box's reader, its only one. It forwards synchronously, so a CLI
+ // that stops reading stops it reading the box.
+ boxEnd := make(chan interactive.End, 1)
+ boxGone := make(chan struct{})
+ go func() {
+ for {
+ _ = box.ws.SetReadDeadline(time.Now().Add(lost))
+ kind, payload, err := interactive.Receive(box.ws)
+ if err != nil {
+ close(boxGone)
+ return
+ }
+ switch kind {
+ case interactive.KindStatus, interactive.KindData:
+ toCLI.send(kind, payload)
+ case interactive.KindAlive:
+ toBox.send(interactive.KindAlive, nil)
+ case interactive.KindEnd:
+ var e interactive.End
+ if json.Unmarshal(payload, &e) != nil || e.Reason == "" {
+ e = interactive.End{Reason: interactive.EndLost}
+ }
+ boxEnd <- e
+ return
+ }
+ }
+ }()
+ // The CLI's frames, from its reader.
+ go func() {
+ for {
+ select {
+ case f := <-leg.in:
+ switch f.kind {
+ case interactive.KindData:
+ toBox.send(f.kind, f.payload)
+ case interactive.KindResize:
+ if _, _, ok := interactive.ParseResize(f.payload); ok {
+ toBox.send(f.kind, f.payload)
+ }
+ case interactive.KindAlive:
+ toCLI.send(interactive.KindAlive, nil)
+ }
+ case <-stop:
+ return
+ }
+ }
+ }()
+
+ // hangUp ends the session from the console's side: End e to the box,
+ // then its End within the wait, if it sends one.
+ hangUp := func(e interactive.End) interactive.End {
+ e.Ended = time.Now().UTC()
+ raw, _ := json.Marshal(e)
+ if toBox.sendWait(interactive.KindEnd, raw) {
+ wait := time.NewTimer(h.hangupWaitFor())
+ defer wait.Stop()
+ select {
+ case got := <-boxEnd:
+ return stamp(got)
+ case <-boxGone:
+ case <-toBox.dead:
+ case <-wait.C:
+ }
+ }
+ return stamp(e)
+ }
+ // boxLost settles a box leg that failed: its End, if its reader had one.
+ boxLost := func() interactive.End {
+ select {
+ case e := <-boxEnd:
+ return stamp(e)
+ default:
+ }
+ return stamp(interactive.End{Reason: interactive.EndLost})
+ }
+ limit := time.NewTimer(h.limit())
+ defer limit.Stop()
+ tick := time.NewTicker(every)
+ defer tick.Stop()
+ for {
+ select {
+ case e := <-boxEnd:
+ return stamp(e)
+ case <-boxGone:
+ return boxLost()
+ case <-toBox.dead:
+ // The write failed: the reader errors at once or within lost.
+ select {
+ case e := <-boxEnd:
+ return stamp(e)
+ case <-boxGone:
+ case <-time.After(lost):
+ }
+ return boxLost()
+ case <-leg.gone:
+ toCLI.shut()
+ return hangUp(interactive.End{Reason: interactive.EndHangup})
+ case <-toCLI.dead:
+ toCLI.shut()
+ return hangUp(interactive.End{Reason: interactive.EndHangup})
+ case <-limit.C:
+ e := interactive.End{Reason: interactive.EndLimit, Ended: time.Now().UTC()}
+ raw, _ := json.Marshal(e)
+ toBox.sendWait(interactive.KindEnd, raw)
+ return stamp(e)
+ case <-ctx.Done():
+ return hangUp(interactive.End{Reason: interactive.EndInterrupted})
+ case <-tick.C:
+ toCLI.offer()
+ toBox.offer()
+ }
+ }
+}
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index c9b17d3a8..2b3c70fef 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -51,7 +51,8 @@ var jobPassFuncs = map[string][]string{
"StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan"},
"PublishPlansMarker": {"publishPlansMarkerOnce"},
"StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns",
- "orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd"},
+ "orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd",
+ "finishPendingInteractiveEnds", "interactiveSweep", "clearDeadMarker", "sweepOrphanGrants"},
"StartSeedsPass": {"seedsPass", "abandonSeed"},
"StartLifetimesCutoverWatch": {"lifetimesWatchOnce", "lifetimesFloorWatch", "materializeAppsOnce", "materializeAppsJudged",
"MaterializeApps"},
diff --git a/internal/console/lifetimes_cutover.go b/internal/console/lifetimes_cutover.go
index f4f345a3b..b15c4f9f1 100644
--- a/internal/console/lifetimes_cutover.go
+++ b/internal/console/lifetimes_cutover.go
@@ -14,6 +14,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/alerting"
+ "github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -367,13 +368,20 @@ func (s *Server) lifetimesStep(ctx context.Context, mutating bool, f func(contex
// lifetimesExempt are the paths that never read or write an instance record:
// health, sign-in, SES ingest, and the cutover door itself, which must answer
-// while admission is closed.
+// while admission is closed. And the interactive sessions' box door (PF-4):
+// it reads and writes no instance record. It checks the hub, the session's
+// token and the registry, against the fleet the session door stored on the
+// hub session at admission, so the box's leg, open as long as the session,
+// holds no unit and never holds a cutover's drain; the session's end is the
+// session door's own write step.
func lifetimesExempt(path string) bool {
switch {
case path == "/healthz", path == "/api/ses/events", path == lifetimesCutoverPath:
return true
case strings.HasPrefix(path, "/auth/"), strings.HasPrefix(path, "/static/"):
return true
+ case strings.HasPrefix(path, interactive.AttachPathPrefix):
+ return true
}
return false
}
diff --git a/internal/console/runsweep.go b/internal/console/runsweep.go
index eca0ff870..ebb2a5179 100644
--- a/internal/console/runsweep.go
+++ b/internal/console/runsweep.go
@@ -10,6 +10,7 @@ import (
"strings"
"time"
+ "github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/runs"
@@ -77,6 +78,12 @@ func (s *Server) runSweep(ctx context.Context, now time.Time) { s.runSweepPass(c
// every write, and the orphan phase's listing of runs/, stays on the bucket,
// and so does the re-read of an orphan's owning record before it is deleted
// (orphanConfirmed).
+//
+// Interactive sessions (rootfs apps Plan 6, Task 11) ride the same pass:
+// first the ends the draining gate refused (finishPendingInteractiveEnds),
+// then every pass the markers of dead sessions (interactiveSweep), and with
+// housekeeping the grants no record names (sweepOrphanGrants), on the same
+// complete read and the same app narrowing as the run orphan phase.
func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping bool) {
if s.cfg.Releases == nil {
return
@@ -96,7 +103,9 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
if !complete {
log.Printf("console: run sweep: some records could not be read; their runs wait for a later pass, and no orphan run is deleted on this one")
}
+ s.interactiveSweep(ctx, recs, now)
named := map[string]bool{}
+ grants := map[string]bool{}
apps := map[[2]string]bool{}
for _, rec := range recs {
if ctx.Err() != nil {
@@ -104,6 +113,9 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
return
}
apps[[2]string{rec.Account, rec.App}] = true
+ if m := rec.Interactive; m != nil {
+ grants[interactive.GrantKey(rec.Account, rec.App, m.ID)] = true
+ }
r := rec.ActiveRun
if r == nil {
continue
@@ -131,7 +143,8 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
if !housekeeping || !complete {
return
}
- candidates, full := s.orphanCandidates(ctx, apps, now)
+ candidates, full := s.orphanCandidates(ctx, apps, now, "run-start")
+ grantApps, _ := s.orphanCandidates(ctx, apps, now, "interactive-start")
for app := range candidates {
if ctx.Err() != nil {
log.Printf("console: run sweep: pass cut short: %v", ctx.Err())
@@ -139,28 +152,36 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
}
s.sweepOrphanRuns(ctx, app[0], app[1], named, now, viewed)
}
+ for app := range grantApps {
+ if ctx.Err() != nil {
+ log.Printf("console: run sweep: pass cut short: %v", ctx.Err())
+ return
+ }
+ s.sweepOrphanGrants(ctx, app[0], app[1], grants, now)
+ }
if full && s.recordView != nil {
s.lastOrphanFull = now
}
}
-// orphanCandidates is the apps whose runs/ the orphan phase lists, out of
-// apps, every app with records, and whether that is all of them. Disarmed it
-// is all of them, as before the index. Armed (S3 change-index design §4.6,
-// codex R2-1) it is only those with a run-start row in the last
+// orphanCandidates is the apps whose runs/ (action "run-start") or
+// interactive/ ("interactive-start") an orphan phase lists, out of apps,
+// every app with records, and whether that is all of them. Disarmed it is
+// all of them, as before the index. Armed (S3 change-index design §4.6,
+// codex R2-1) it is only those with an action row in the last
// orphanCandidateWindow, except on the first housekeeping after start and
// then once every orphanFullSweepEvery, which take every app, as does a
// failed read of the rows. Orphans are still found by age, not by index
-// movement: runs/ is outside every scope. The narrowed set is always a
-// subset of apps, so it never lists an app the full sweep would not.
-func (s *Server) orphanCandidates(ctx context.Context, apps map[[2]string]bool, now time.Time) (map[[2]string]bool, bool) {
+// movement. The narrowed set is always a subset of apps, so it never lists
+// an app the full sweep would not.
+func (s *Server) orphanCandidates(ctx context.Context, apps map[[2]string]bool, now time.Time, action string) (map[[2]string]bool, bool) {
if s.recordView == nil || s.lastOrphanFull.IsZero() || now.Sub(s.lastOrphanFull) >= orphanFullSweepEvery {
return apps, true
}
- recent, err := s.store.AppsWithActionSince("run-start", now.Add(-orphanCandidateWindow))
+ recent, err := s.store.AppsWithActionSince(action, now.Add(-orphanCandidateWindow))
if err != nil {
- log.Printf("console: run sweep: recent runs: %v (every app's runs are swept this pass)", err)
- jobFailed(ctx, fmt.Errorf("run sweep: recent runs: %w (every app's runs are swept this pass)", err))
+ log.Printf("console: run sweep: recent %s rows: %v (every app is swept this pass)", action, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: recent %s rows: %w (every app is swept this pass)", action, err))
return apps, true
}
out := map[[2]string]bool{}
@@ -427,3 +448,126 @@ func (s *Server) strayIsOld(ctx context.Context, dir string, now time.Time) bool
}
return now.Sub(newest) > runs.KeepFor
}
+
+// ---- interactive sessions (rootfs apps Plan 6, Task 11) ---------------------
+
+// interactiveSweep is the marker phase: it clears the marker of every dead
+// session in recs and deletes its grant. A marker is dead when another
+// console process admitted it (Console is not this boot: its hub is gone
+// with it), or when its PickupBy has passed and this console's hub does not
+// hold its id. An id the hub holds in endPending is left to
+// finishPendingInteractiveEnds, which ran first in this pass with the
+// session's own End. An interactive-end row with reason lost is written for
+// each marker it clears, unless the hub has the id as ended (its own end
+// step writes that row).
+func (s *Server) interactiveSweep(ctx context.Context, recs []provision.Record, now time.Time) {
+ h := s.interactive
+ if h == nil {
+ return
+ }
+ for _, rec := range recs {
+ m := rec.Interactive
+ if m == nil {
+ continue
+ }
+ if ctx.Err() != nil {
+ log.Printf("console: run sweep: interactive phase cut short: %v", ctx.Err())
+ return
+ }
+ state := h.stateOf(m.ID)
+ if state == hubPending {
+ continue
+ }
+ if m.Console == s.bootID && (state == hubHeld || !now.After(m.PickupBy)) {
+ continue
+ }
+ s.clearDeadMarker(ctx, rec, *m, now, state == hubEnded)
+ }
+}
+
+// clearDeadMarker clears one dead session's marker (InteractiveClear), then
+// deletes its grant, then writes its lost row unless ended. A marker that
+// changed since the read (another session replaced it, or it was cleared,
+// or the record went) is not this phase's to clear: the old grant is still
+// deleted, and no row is written, since who ended it is unknown. A grant
+// delete that fails after the clear landed leaves the rest to
+// finishPendingInteractiveEnds (endPending), so the row is written once,
+// after the delete.
+func (s *Server) clearDeadMarker(ctx context.Context, rec provision.Record, m provision.InteractiveState, now time.Time, ended bool) {
+ acct, err := s.store.AccountBySqid(rec.Account)
+ if err != nil {
+ log.Printf("console: run sweep: account %s: %v", rec.Account, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: account %s: %w", rec.Account, err))
+ return // no marker is cleared before its row can be written
+ }
+ if acct == nil {
+ return
+ }
+ sess := &hubSession{id: m.ID, acct: rec.Account, app: rec.App, host: rec.Host, by: m.By, account: acct, pickupBy: m.PickupBy}
+ ctx, cancel := runWriteCtx(ctx)
+ defer cancel()
+ _, err = provision.SetRecordInteractive(ctx, s.cfg.Releases, rec.Account, rec.App, rec.Host, provision.InteractiveClear(m.ID))
+ switch {
+ case errors.Is(err, provision.ErrInteractiveConflict) || errors.Is(err, os.ErrNotExist):
+ if err := s.deleteGrant(ctx, sess); err != nil {
+ log.Printf("console: run sweep: %s/%s/%s: interactive %s grant: %v", rec.Account, rec.App, rec.Host, m.ID, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: %s/%s/%s: interactive %s grant: %w", rec.Account, rec.App, rec.Host, m.ID, err))
+ }
+ return
+ case err != nil:
+ log.Printf("console: run sweep: %s/%s/%s: clear interactive %s: %v", rec.Account, rec.App, rec.Host, m.ID, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: %s/%s/%s: clear interactive %s: %w", rec.Account, rec.App, rec.Host, m.ID, err))
+ return
+ }
+ e := interactive.End{Reason: interactive.EndLost, Ended: now.UTC()}
+ if err := s.deleteGrant(ctx, sess); err != nil {
+ log.Printf("console: run sweep: %s/%s/%s: interactive %s grant waits for a later pass: %v", rec.Account, rec.App, rec.Host, m.ID, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: %s/%s/%s: interactive %s grant: %w", rec.Account, rec.App, rec.Host, m.ID, err))
+ if ended {
+ s.interactive.pendGrant(sess)
+ } else {
+ s.interactive.pend(sess, e)
+ }
+ return
+ }
+ if ended {
+ return
+ }
+ s.auditActivity(acct, rec.App, m.By, Activity{Action: "interactive-end", TargetType: "instance", Target: rec.Host,
+ Detail: interactiveEndDetail(m.ID, e)})
+}
+
+// sweepOrphanGrants deletes the session grants under acct/app's interactive/
+// that no record names and that are older than runs.KeepFor: grants of
+// sessions whose end was cut short, of admissions that lost their CAS, of
+// markers a later admission replaced. Only keys of the grant shape
+// (interactive.GrantKey of a valid id, which holds no slash) are touched.
+// Age is the object's modification time, from the one listing; a store
+// that cannot list modification times leaves every grant alone. A session
+// lasts at most its pickup window and MaxDuration and a minute, so a
+// day-old grant is never a live one, whatever a stale record view says,
+// and an endPending grant it deletes first is one the pending pass then
+// finds already gone.
+func (s *Server) sweepOrphanGrants(ctx context.Context, acct, app string, named map[string]bool, now time.Time) {
+ ml, ok := s.cfg.Releases.(release.ModLister)
+ if !ok {
+ return
+ }
+ prefix := interactive.Prefix(acct, app)
+ objs, err := ml.ListMod(ctx, prefix)
+ if err != nil {
+ log.Printf("console: run sweep: %s/%s: list interactive grants: %v", acct, app, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: %s/%s: list interactive grants: %w", acct, app, err))
+ return
+ }
+ for _, o := range objs {
+ id, ok := strings.CutSuffix(strings.TrimPrefix(o.Key, prefix), ".json")
+ if !ok || !interactive.ValidID(id) || named[o.Key] || now.Sub(o.Mod) <= runs.KeepFor {
+ continue
+ }
+ if err := s.cfg.Releases.Delete(ctx, o.Key); err != nil && !errors.Is(err, os.ErrNotExist) {
+ log.Printf("console: run sweep: %s/%s: delete orphan grant %s: %v", acct, app, id, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: %s/%s: delete orphan grant %s: %w", acct, app, id, err))
+ }
+ }
+}
diff --git a/internal/console/runsweep_test.go b/internal/console/runsweep_test.go
index 92c4b0460..025d82a0e 100644
--- a/internal/console/runsweep_test.go
+++ b/internal/console/runsweep_test.go
@@ -5,6 +5,8 @@ import (
"context"
"encoding/json"
"errors"
+ "os"
+ "path/filepath"
"reflect"
"sort"
"strings"
@@ -12,6 +14,7 @@ import (
"testing"
"time"
+ "github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/runs"
@@ -601,6 +604,11 @@ func (c *listCountingStore) ListDirs(ctx context.Context, prefix string) ([]stri
return c.DirStore.ListDirs(ctx, prefix)
}
+func (c *listCountingStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) {
+ c.note("ListMod", prefix)
+ return c.DirStore.ListMod(ctx, prefix)
+}
+
func (c *listCountingStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
c.note("ListETags", prefix)
return c.DirStore.ListETags(ctx, prefix)
@@ -813,3 +821,322 @@ func TestRunSweepKeepsTheRunOfARecordMigratedAfterTheSnapshot(t *testing.T) {
t.Fatalf("record's run = %+v, want %s", r, id)
}
}
+
+// ---- the interactive phase (rootfs apps Plan 6 Task 11) ---------------------
+
+// ixPutGrant writes a stand-in grant object for session id of bah's shop.
+func ixPutGrant(t *testing.T, fx *interactiveFx, id string) string {
+ t.Helper()
+ key := interactive.GrantKey(fx.acct, "shop", id)
+ if _, err := fx.rel.Put(context.Background(), key, []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ return key
+}
+
+// ixHasObject reports whether key is in the bucket.
+func ixHasObject(t *testing.T, fx *interactiveFx, key string) bool {
+ t.Helper()
+ _, _, err := fx.rel.Get(context.Background(), key)
+ switch {
+ case err == nil:
+ return true
+ case errors.Is(err, os.ErrNotExist):
+ return false
+ }
+ t.Fatal(err)
+ return false
+}
+
+// ixMarker is the session marker on host, or nil.
+func ixMarker(t *testing.T, fx *interactiveFx, host string) *provision.InteractiveState {
+ t.Helper()
+ rec, _ := ixRecord(t, fx, host)
+ return rec.Interactive
+}
+
+func TestSweepClearsMarkersOfOtherBoots(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-boots")
+ ctx := context.Background()
+ const dead = "tty_bbbbbbbbbbbbbbbbbbbbbbbbbb"
+ // Another console process's session, its PickupBy still ahead: dead by
+ // its Console alone.
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk",
+ Interactive: &provision.InteractiveState{ID: dead, By: "bob@keymail.dev", Console: "old", PickupBy: time.Now().Add(time.Minute)}})
+ deadGrant := ixPutGrant(t, fx, dead)
+ // This process's session, held in the hub, past its PickupBy by the
+ // pass's clock: left alone.
+ const other = "other.example.com"
+ ixPutRecord(t, fx, provision.Record{Host: other, Channel: "stable", Region: "uk"})
+ cli := ixStartOn(t, fx, other, fx.alice)
+ liveID, _ := ixSessionGrant(t, fx, other)
+ liveGrant := interactive.GrantKey(fx.acct, "shop", liveID)
+
+ fx.srv.runSweepPass(ctx, time.Now().Add(2*time.Minute), false)
+ if m := ixMarker(t, fx, ixHost); m != nil {
+ t.Fatalf("the other boot's marker %+v survived", m)
+ }
+ if ixHasObject(t, fx, deadGrant) {
+ t.Fatal("the other boot's grant survived")
+ }
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || evs[0].Target != ixHost || evs[0].Address != "bob@keymail.dev" {
+ t.Fatalf("end rows %+v, want one for bob's session on %s", evs, ixHost)
+ }
+ if d := ixEndRow(t, evs[0]); d.ID != dead || d.Reason != interactive.EndLost || d.Ended.IsZero() {
+ t.Fatalf("end row %+v, want %s lost", d, dead)
+ }
+ if m := ixMarker(t, fx, other); m == nil || m.ID != liveID {
+ t.Fatalf("the held session's marker is %+v, want %s", m, liveID)
+ }
+ if !ixHasObject(t, fx, liveGrant) {
+ t.Fatal("the held session's grant was deleted")
+ }
+ if st := hubState(fx.srv.interactive, liveID); st != "active" {
+ t.Fatalf("hub: %q, want the held session active", st)
+ }
+ // A second pass writes nothing.
+ fx.srv.runSweepPass(ctx, time.Now().Add(2*time.Minute), false)
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 1 {
+ t.Fatalf("a second pass wrote again: %+v", evs)
+ }
+ cli.Close()
+ ixWaitEvents(t, fx, "interactive-end", 2)
+}
+
+func TestSweepClearsThisBootsDeadMarkers(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-mine")
+ ctx := context.Background()
+ h := fx.srv.interactive
+ boot := fx.srv.bootID
+ now := time.Now()
+ const (
+ lostHost = ixHost
+ aheadHost = "other.example.com"
+ endedHost = "admin.example.com"
+ lostID = "tty_cccccccccccccccccccccccccc"
+ aheadID = "tty_dddddddddddddddddddddddddd"
+ endedID = "tty_eeeeeeeeeeeeeeeeeeeeeeeeee"
+ )
+ put := func(host, id string, pickupBy time.Time) string {
+ ixPutRecord(t, fx, provision.Record{Host: host, Channel: "stable", Region: "uk",
+ Interactive: &provision.InteractiveState{ID: id, By: "alice@keymail.dev", Console: boot, PickupBy: pickupBy}})
+ return ixPutGrant(t, fx, id)
+ }
+ // Never held here (an admission whose outcome was unknown), past its
+ // PickupBy: lost.
+ lostGrant := put(lostHost, lostID, now.Add(-time.Minute))
+ // Never held, PickupBy ahead: left for a later pass.
+ aheadGrant := put(aheadHost, aheadID, now.Add(time.Minute))
+ // Ended in the hub (its end step writes its own row), past PickupBy:
+ // cleared with no row.
+ endedGrant := put(endedHost, endedID, now.Add(-time.Minute))
+ h.mu.Lock()
+ h.ended[endedID] = now.Add(time.Hour)
+ h.mu.Unlock()
+
+ fx.srv.runSweepPass(ctx, now, false)
+ if m := ixMarker(t, fx, lostHost); m != nil || ixHasObject(t, fx, lostGrant) {
+ t.Fatalf("the unheld past-pickup session: marker %+v, grant kept %v", m, ixHasObject(t, fx, lostGrant))
+ }
+ if m := ixMarker(t, fx, aheadHost); m == nil || m.ID != aheadID || !ixHasObject(t, fx, aheadGrant) {
+ t.Fatalf("the session before its PickupBy: marker %+v, grant kept %v", m, ixHasObject(t, fx, aheadGrant))
+ }
+ if m := ixMarker(t, fx, endedHost); m != nil || ixHasObject(t, fx, endedGrant) {
+ t.Fatalf("the ended session: marker %+v, grant kept %v", m, ixHasObject(t, fx, endedGrant))
+ }
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || evs[0].Target != lostHost {
+ t.Fatalf("end rows %+v, want one for %s", evs, lostHost)
+ }
+ if d := ixEndRow(t, evs[0]); d.ID != lostID || d.Reason != interactive.EndLost {
+ t.Fatalf("end row %+v", d)
+ }
+ // Past the ahead session's PickupBy, it is lost too.
+ fx.srv.runSweepPass(ctx, now.Add(2*time.Minute), false)
+ if m := ixMarker(t, fx, aheadHost); m != nil || ixHasObject(t, fx, aheadGrant) {
+ t.Fatalf("the session past its PickupBy: marker %+v", m)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 2 {
+ t.Fatalf("end rows %+v, want two", evs)
+ }
+}
+
+// An id the hub holds in endPending is the pending pass's: the marker phase
+// writes nothing for it, whatever its PickupBy.
+func TestSweepLeavesAPendingEndToItsOwnPass(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-pending")
+ h := fx.srv.interactive
+ const id = "tty_ffffffffffffffffffffffffff"
+ m := &provision.InteractiveState{ID: id, By: "alice@keymail.dev", Console: fx.srv.bootID, PickupBy: time.Now().Add(-time.Minute)}
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Interactive: m})
+ grant := ixPutGrant(t, fx, id)
+ acct, err := fx.st.AccountBySqid(fx.acct)
+ if err != nil || acct == nil {
+ t.Fatal(acct, err)
+ }
+ h.pend(&hubSession{id: id, acct: fx.acct, app: "shop", host: ixHost, by: "alice@keymail.dev", account: acct, pickupBy: m.PickupBy},
+ interactive.End{Reason: interactive.EndExited, Ended: time.Now().UTC()})
+ rec, _ := ixRecord(t, fx, ixHost)
+ rec.Account, rec.App = fx.acct, "shop"
+ fx.srv.interactiveSweep(context.Background(), []provision.Record{rec}, time.Now())
+ if got := ixMarker(t, fx, ixHost); got == nil || got.ID != id || !ixHasObject(t, fx, grant) {
+ t.Fatalf("the marker phase acted on a pending end: marker %+v", got)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("rows %+v", evs)
+ }
+ // The pass finishes it with its own End.
+ fx.srv.runSweepPass(context.Background(), time.Now(), false)
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || ixEndRow(t, evs[0]).Reason != interactive.EndExited {
+ t.Fatalf("rows %+v, want one exited", evs)
+ }
+}
+
+// A marker the phase read that has changed since (a later admission
+// replaced it, from a stale read) is not cleared: the new marker stays, the
+// old grant goes, and no row is written, since who ended the old session
+// is unknown.
+func TestSweepLeavesAReplacedMarkerAlone(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-replaced")
+ const old = "tty_jjjjjjjjjjjjjjjjjjjjjjjjjj"
+ oldGrant := ixPutGrant(t, fx, old)
+ stale, _ := ixRecord(t, fx, ixHost)
+ stale.Interactive = &provision.InteractiveState{ID: old, By: "bob@keymail.dev", Console: "old", PickupBy: time.Now().Add(-time.Minute)}
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ liveID, _ := ixSessionGrant(t, fx, ixHost)
+ fx.srv.interactiveSweep(context.Background(), []provision.Record{stale}, time.Now())
+ if m := ixMarker(t, fx, ixHost); m == nil || m.ID != liveID {
+ t.Fatalf("marker %+v, want the new session %s kept", m, liveID)
+ }
+ if ixHasObject(t, fx, oldGrant) {
+ t.Fatal("the replaced session's grant survived")
+ }
+ if !ixHasObject(t, fx, interactive.GrantKey(fx.acct, "shop", liveID)) {
+ t.Fatal("the new session's grant was deleted")
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("rows %+v, want none", evs)
+ }
+ cli.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+// ixAge sets key's modification time d in the past.
+func ixAge(t *testing.T, fx *interactiveFx, key string, d time.Duration) {
+ t.Helper()
+ ds, ok := fx.rel.(*deletableStore)
+ if !ok {
+ t.Fatalf("fixture store is %T", fx.rel)
+ }
+ at := time.Now().Add(-d)
+ if err := os.Chtimes(filepath.Join(ds.root, filepath.FromSlash(key)), at, at); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestSweepDeletesOrphanGrants(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-grants")
+ ctx := context.Background()
+ day := runs.KeepFor + time.Hour
+ old := ixPutGrant(t, fx, "tty_gggggggggggggggggggggggggg")
+ ixAge(t, fx, old, day)
+ young := ixPutGrant(t, fx, "tty_hhhhhhhhhhhhhhhhhhhhhhhhhh")
+ notes := interactive.Prefix(fx.acct, "shop") + "notes.txt"
+ badID := interactive.Prefix(fx.acct, "shop") + "tty_short.json"
+ nested := interactive.Prefix(fx.acct, "shop") + "runs/tty_iiiiiiiiiiiiiiiiiiiiiiiiii.json"
+ for _, k := range []string{notes, badID, nested} {
+ if _, err := fx.rel.Put(ctx, k, []byte(`{}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ ixAge(t, fx, k, day)
+ }
+ // A live session's grant, aged past the day: its record names it.
+ cli := ixStart(t, fx, fx.alice, ixOpenArgv())
+ liveID, _ := ixSessionGrant(t, fx, ixHost)
+ live := interactive.GrantKey(fx.acct, "shop", liveID)
+ ixAge(t, fx, live, day)
+ kept := func(what string, keys ...string) {
+ t.Helper()
+ for _, k := range keys {
+ if !ixHasObject(t, fx, k) {
+ t.Fatalf("%s: %s was deleted", what, k)
+ }
+ }
+ }
+
+ fx.srv.runSweepPass(ctx, time.Now(), false)
+ kept("a pass without housekeeping", old, young, notes, badID, nested, live)
+
+ fx.srv.cfg.Releases = plainStore{fx.rel}
+ fx.srv.runSweepPass(ctx, time.Now(), true)
+ fx.srv.cfg.Releases = fx.rel
+ kept("a store that cannot say how old an object is", old, young, notes, badID, nested, live)
+
+ const other = "other.example.com"
+ ixPutRecord(t, fx, provision.Record{Host: other, Channel: "stable", Region: "uk"})
+ unreadable := provision.RecordKey(fx.acct, "shop", other)
+ ds := fx.rel.(*deletableStore)
+ ds.setGetHook(func(_ context.Context, key string) error {
+ if key == unreadable {
+ return errors.New("slow down")
+ }
+ return nil
+ })
+ fx.srv.runSweepPass(ctx, time.Now(), true)
+ kept("a pass that could not read every record", old, young, notes, badID, nested, live)
+ ds.setGetHook(func(context.Context, string) error { return nil })
+
+ fx.srv.runSweepPass(ctx, time.Now(), true)
+ if ixHasObject(t, fx, old) {
+ t.Fatal("a day-old grant no record names survived")
+ }
+ kept("a full pass", young, notes, badID, nested, live)
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("deleting an orphan grant wrote rows %+v", evs)
+ }
+ cli.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+// interactiveListings keeps the listings under an interactive/ prefix.
+func interactiveListings(lists []string) []string {
+ var out []string
+ for _, l := range lists {
+ if strings.Contains(l, "/interactive/") {
+ out = append(out, l)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+// Armed, between daily full sweeps, orphan grant housekeeping lists
+// interactive/ only for apps with an interactive-start row in the last 48
+// hours, as the run orphan phase does with run-start rows.
+func TestOrphanGrantHousekeepingListsOnlyRecentSessionApps(t *testing.T) {
+ fx := newIxFx(t, "code-ixs-recent")
+ cs := indexedDeployment(t, fx.consoleFixture)
+ rec := provision.Record{Schema: 1, Host: "cafe.example.com", Slug: "cafe", App: "cafe", Account: fx.acct, Channel: "stable", CreatedAt: time.Now().UTC()}
+ if err := provision.CreateRecord(context.Background(), cs, rec); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := fx.st.RecordActivity(fx.acctID, "shop", "alice@keymail.dev", Activity{Action: "interactive-start"}, now.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ armRecordView(t, fx.srv, cs)
+ all := []string{"ListMod " + interactive.Prefix(fx.acct, "cafe"), "ListMod " + interactive.Prefix(fx.acct, "shop")}
+
+ cs.taken()
+ fx.srv.runSweepPass(context.Background(), now, true)
+ if got := interactiveListings(cs.taken()); !reflect.DeepEqual(got, all) {
+ t.Fatalf("first housekeeping listed %q, want every app with records %q", got, all)
+ }
+ fx.srv.runSweepPass(context.Background(), now.Add(10*time.Minute), true)
+ want := []string{"ListMod " + interactive.Prefix(fx.acct, "shop")}
+ if got := interactiveListings(cs.taken()); !reflect.DeepEqual(got, want) {
+ t.Fatalf("narrowed housekeeping listed %q, want %q", got, want)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 39c6b6567..b6721038e 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1989,6 +1989,14 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// label-aware SigningCertURL host check, and a verified signature,
// all run before any field of the message is trusted.
s.registerRoute("POST /api/ses/events", s.handleSESEvents)
+ // The box door of interactive sessions (apiinteractivebox.go, rootfs
+ // apps spec §5.10): no console principal either. The box that owns a
+ // session's instance proves itself with the session's own token from
+ // its grant and, on a fleet, its fleet identity; every refusal is the
+ // same 404. lifetimesExempt names its prefix (interactive.
+ // AttachPathPrefix, the path every grant's Attach URL carries): it
+ // touches no record.
+ s.registerRoute("GET /api/box/interactive/{id}", s.handleBoxInteractive)
// Billing webhook (billingwebhook.go, plans 6a): UNAUTHENTICATED for
// the same reason; the provider's signature is checked before anything
// in the body is used, and the body only names what to re-read. Always
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index ff8ce89d1..8c486892c 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -42,6 +42,7 @@ route GET /a/{sqid}/team
route GET /a/{sqid}/trash
route GET /a/{sqid}/{$}
route GET /accounts/new
+route GET /api/box/interactive/{id}
route GET /api/cli/accounts/{account}/plan
route GET /api/cli/apps
route GET /api/cli/apps/{account}/list
diff --git a/internal/console/view.go b/internal/console/view.go
index b74dd8b42..7f91211ae 100644
--- a/internal/console/view.go
+++ b/internal/console/view.go
@@ -532,6 +532,7 @@ type consoleRegistry interface {
CreateFleet(registry.Fleet) (bool, error)
GetFleet(string) (*registry.Fleet, error)
ListFleets() ([]registry.Fleet, error)
+ FleetOwners() (map[string]string, error)
SetFleetSecretsKey(name, pub, fp, by string, at int64) error
AddFleetBox(registry.FleetBox) error
ListFleetBoxes(string) ([]registry.FleetBox, error)
diff --git a/internal/provision/rootfs_apps_6_census_test.go b/internal/provision/rootfs_apps_6_census_test.go
index 82f05b7ae..0f76f169e 100644
--- a/internal/provision/rootfs_apps_6_census_test.go
+++ b/internal/provision/rootfs_apps_6_census_test.go
@@ -44,12 +44,21 @@ package provision
// - Task 10 fix round 2: admitSession no longer bumps the serial (the
// bump runs after the admission step, outside any unit). The same one
// SetRecordInteractive; re-pinned.
+// - Task 11: the box door and the sweep's interactive phase.
+// Server.clearDeadMarker (internal/console/runsweep.go) is a
+// record-writer: its one record write is
+// SetRecordInteractive(InteractiveClear) of a dead session's marker,
+// under the run sweep pass's unit (lifetimesIteration, mutating; judged
+// when lifetimes are on), through runWriteCtx as the sweep's other
+// transitions. NewServer registers GET /api/box/interactive/{id} (the
+// box door reads the hub, the token and the registry, and touches no
+// record); re-pinned, the same lit:instances.
func rootfsApps6WriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), fleetPublicRoutesWriteCensusInventory()...)
replacements := []censusEntry{
{"internal/provision/reconcile.go", "Reconcile", "key-site", "key:ParseRecordKey,key:RecordKey,lit:instances", "be1b699f14a2f8d6935d959dee168bdf6fb556cd78da458f5ba8a1c0e8512a17"},
{"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "ede525ff628efe3f32e655448c3b1633975fd7312205e7418c60c8ed5be2894e"},
- {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "4ef5168b1506ffcc8e0a7769ac3b188925bc1b79603d632575972e7f1548f17d"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "fdbd52b5b193ae308aa24b1506b3ea91869b65f549a0d10115a521b868509f6f"},
{"internal/instanceexec/exit.go", "parseExitArgs", "key-site", "lit:instances", "be3a7828e292b4977c42f21d8283fc9d185505ced9ffdf2543267a88bc8033a9"},
{"internal/host/runexec.go", "runsWorker.finish", "record-writer", "key:SetRecordRun", "f586bc77d175652d19bed1e7cceb7ecad523f7a1125bc798c19109e0a4f55ee2"},
}
@@ -74,6 +83,7 @@ func rootfsApps6WriteCensusInventory() []censusEntry {
{"internal/console/apiinteractive.go", "Server.endWrites", "record-writer", "key:SetRecordInteractive", "6a183621b60073e45f698e046a177adca2f536b47a365bdb66de5548257b9fea"},
{"internal/console/apiinteractive.go", "Server.putGrant", "nonrecord", "sel:Put", "22a18ef45051da8cfb8a6a62ad8891afd28e3bf71cc26a541639cd2a1dc0a1ff"},
{"internal/console/server.go", "consolePerfSkip", "key-site", "lit:instances", "d4b65473d3702b49d79a799d46f078e4491b6e86a59a101dd4c1ce4d50f698e7"},
+ {"internal/console/runsweep.go", "Server.clearDeadMarker", "record-writer", "key:SetRecordInteractive", "d0e66bf2e33b4086f435ded4d44750a9eacf8a1b6d1e661c09481be1b54580ee"},
}
for _, a := range added {
for _, e := range entries {