carlos / platform Public

console: the interactive session door, admission and audit (rootfs plan 6)

Task 10, the CLI leg: GET /api/cli/apps/{account}/{app}/instances/{host}/interactive,
a WebSocket for people only (zero role set). Eleven refusals before the
upgrade, in order; the Open within OpenWait (C36), the console process
resolved from the channel's manifest (C33); the id reserved in the hub
before the grant and the record CAS (finding 10); activate, the serial
bump and the interactive-start row; End expired at PickupBy or cancelled.

Lifetimes (PF-4): the upgrade ends the request's unit; the admission and
each end are their own mutating write steps (lifetimesStep); an admission
refused while draining ends with C37, an end refused waits in endPending
and the run sweep finishes it. instanceClassRefusal is factored from
runClassRefusal (D4: sessions are admitted on fleets; runs unchanged).
consolePerfSkip skips both session doors (PF-23). Request budget pinned at
the S3 wire: 18 legacy, 21 judged, +2 for carlos console (PF-22).

Built copy: RFS-6-C27, C32 to C37 (file cells rewritten, PF-12). Record-write
census: admitSession, endWrites, putGrant, consolePerfSkip; registerCLIRoutes
and NewServer re-pinned. Root-read census unchanged (seal f02fd204).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 70254b072c55ec510baad7d54db4595476e3954f parent fa303ff
17 files changed, +2,278 −16
  • approved_rootfs_copy_test.go +3 −0
  • docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md +7 −7
  • internal/console/apiinteractive.go +527 −0
  • internal/console/apiinteractive_lifetimes_test.go +397 −0
  • internal/console/apiinteractive_test.go +992 −0
  • internal/console/apiinteractivesetting_test.go +7 −1
  • internal/console/apiruns.go +15 −3
  • internal/console/authcli.go +6 −0
  • internal/console/claim_invariant_fixtures_test.go +14 −0
  • internal/console/claim_invariant_test.go +2 −0
  • internal/console/interactivehub.go +216 −0
  • internal/console/lifetimes_cutover.go +37 −0
  • internal/console/runsweep.go +3 −0
  • internal/console/server.go +27 −2
  • internal/console/svcroutes_test.go +7 −2
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/provision/rootfs_apps_6_census_test.go +17 −1

Intent

Human

<task-notification> <task-id>a5f785381244b0779</task-id> <tool-use-id>toolu_01DspJgrEPMJ6kWmKCwNd7Hk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a5f785381244b0779.output</output-file> <status>completed</status> <summary>Agent "Plan 6 Task 9: session writer lifecycle" 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>Status: DONE Commit: `fa303fff` (on top of `5aa80f3a`). Not pushed. Tests: both new release tests failed before the fix and pass now; they, the touched release tests and the fix-2 lease witnesses pass `-race -count=20`. The activator suite, the guards and the provision census pass, and the darwin/arm64, windows/amd64 and linux/arm64 builds are clean. What changed, per the ruling: - **Release admission:** it refuses again while either role's start is in flight, as swap admission does. The comment at the check explains the start window and the ruling. - **Started commands:** the busy check still counts only an attached run. A started session never holds up a release. - **Tests:** a new one runs the full release path. With a session start blocked, the release is refused, nothing executes and no record is left. Once the start returns, the same release runs and passes. Fix 1's admission test is replaced by one that checks both states. - **Mutations:** both were killed. One is the fix-1 form (checking only the run's start); the other has a started session refuse the release. Census: re-proposed. The seal went from `9272ccd3` to `f02fd204`. `releaseAdmitLocked`'s claim goes back to its Task 9 meaning and cites the ruling; the other 46 claims are carried over unchanged. No approval requested. The ruling is recorded in the fix-round-2 section appended to `task-9-report.md`. Concerns: none new. As the ruling accepts, a release is put off for as long as a session takes to start.</result> <usage><subagent_tokens>385572</subagent_tokens><tool_uses>12</tool_uses><duration_ms>451143</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a2ffac1fc9286a733</task-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a2ffac1fc9286a733.output</output-file> <status>completed</status> <summary>Agent "Release v0.32.1 to dev" 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>v0.32.1 is cut, published and rolled to dev only. Every dev check passed and nothing was rolled back. Flagship and Tito were not touched. - **Tag:** v0.32.1 is tag object 1601d282, pointing at d937c467. No hold message came from the controller. I logged "ABOUT TO TAG" in roll-log.md just before tagging. - **Before tagging:** main was still at d937c467 and nothing newer than v0.32.0 existed. Main CI at d937c467 passed. The branch tip 00584e58 has the same tree (e8b5470d). - **Release:** [https://github.com/carlosframework/releases/releases/tag/v0.32.1](https://github.com/carlosframework/releases/releases/tag/v0.32.1), published 03:39:35Z as Latest with 10 assets. The public download's signature verified and its sums match my build. - **Homebrew and apt:** homebrew-tap PR #74 is merged. apt v0.32.1-1 is live (latest.txt reads v0.32.1, and the served deb matches the signed one). - **Release notes:** three Luna passes. Pass 1 approved everything. I then narrowed one sentence myself: the "release that cannot carry WebSockets" cause only shows once the hub is updated and the box is not. Pass 2 rewrote one sentence (applied verbatim) and pass 3 approved everything. The dormant-switch paragraph is carried over unchanged, and the notes have no em dashes. - **Builds:** CLI linux-arm64 is 583e2fc5. Console is de4b3920, with the full commit d937c467 stamped in. - **Boxes:** all four report v0.32.1 current. - sophie (canary) started at 03:51:12Z. - Stable: leo 03:56:31Z, dennis 03:57:44Z, and box-1 updated itself by 03:56:14Z (read from `carlos system status` only). - Each checked box: REFUSING, LEASE HELD and ERROR all 0, NRestarts 0, host.env sha8 unchanged, CARLOS_POOLS unchanged. - The bootstrap/carlos warning appeared, so I copied the v0.32.1 binary over it and the warning cleared. - **Console:** restart took 1.85 s from stop to listening (03:59:52.71Z to 03:59:54.56Z). It runs v0.32.1 de4b3920. All 13 drop-ins and files on sophie are identical before and after. The rollback target, v0.32.0 7f1139f3, was not needed. - **Probe across the console restart:** 1,186 requests, none failed. Requests during the restart were held for 1.71 s at most. - **Dev checks, all PASS:** - platform.dev.carlosframework.com returns x-carlos-version v0.32.1. - Billing webhook returns 400. - hosts-used is active with 36 recorded, and the floor is unchanged. - The static site and wakecheck answers are unchanged. - A throwaway app (relcheck-v0321) was created, deployed, then trashed; its host returned 404 afterwards. - instances list, analytics and fleets ls are unchanged. - sophie's edge journal has 0 ERROR lines mentioning upgrade, tunnel, forward, fleet or binding. - **box-1 reconnect:** sophie logged box-1 connecting at 03:51:13Z, still on v0.32.0. After both ends were updated, it reconnected at 03:56:02Z. The "ping failed (EOF)" line at 03:56:03Z is box-1's old process handing its tunnel over, the same as during the v0.32.0 roll. - **shop:** `/up` returned 200 v1 before the roll, after sophie, after the boxes and after the console. Its WebSocket was not checked; that is your #471 Task 10 live check. - **railsdemo:** returned 200 r3b at the same four points. Odd things, none acted on: 1. When sophie's edge started (03:51:12Z) it logged one "shop is not served: forward row on a box that is not the hub" line. This is known issue #480: a false message at hub startup, and shop kept serving. It didn't show at v0.32.0's start because shop's forward row didn't exist yet. 2. The new console happens to be exactly the same size in bytes as v0.32.0's, but the contents differ. 3. I fixed one cosmetic error in the copied flag.sh helper (it said barbara is uk and iris is au; it's the other way round) and logged it as a ruling. That helper wasn't used here. No process is left running, and the scratch files I made are removed. The changelog and website step was not mine and is not done. Full detail is in /home/paulca/.cache/release-v0.32.1/roll-log.md, with supporting captures in /home/paulca/.cache/release-v0.32.1/tmp/.</result> <usage><subagent_tokens>165971</subagent_tokens><tool_uses>78</tool_uses><duration_ms>1895353</duration_ms></usage> </task-notification>

Attributed to this commit: 48.5 g CO₂e (2,481,897 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/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 88d4d7eed..7d5aca54a 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -259,6 +259,9 @@ var rootfsCopyBuilt = []string{
// Plan 6 Task 7a: carlos run on rootfs rows, the rootfs argv on the
// image's PATH (docs/site/cli.md)
"RFS-3-C27",
+ // Plan 6 Task 10: the console's session door
+ // (internal/console/apiinteractive.go)
+ "RFS-6-C27", "RFS-6-C32", "RFS-6-C33", "RFS-6-C34", "RFS-6-C35", "RFS-6-C36", "RFS-6-C37",
}
func mustParseRootfsRecord(t *testing.T) []copyRow {
diff --git a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
index 09072efa5..afe8bea1a 100644
--- a/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
+++ b/docs/superpowers/plans/2026-10-24-rootfs-apps-copy.md
@@ -497,17 +497,17 @@ From the plan: Every string is human text the plan introduces. Existing approved
| RFS-6-C24 | sessionExit | %s: the box is not on the nested layout yet, so it cannot open a session | approved |
| RFS-6-C25 | sessionExit | %s: the box has host claims armed. it cannot open a session yet | approved |
| RFS-6-C26 | sessionExit | %s: the instance did not wake. %s | approved |
-| RFS-6-C27 | console door and `sessionExit` | interactive sessions are off for %s. an owner can turn them on with carlos apps set %s --interactive on | approved |
+| RFS-6-C27 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10; `sessionExit` is Task 13's) | interactive sessions are off for %s. an owner can turn them on with carlos apps set %s --interactive on | approved |
| RFS-6-C28 | sessionExit | %s was deleted and created again after this session was requested. the session did not start | approved |
| RFS-6-C29 | sessionExit | %s is an import that is not committed yet. the session did not start | approved |
| RFS-6-C30 | sessionExit | %s: its box is still closing the last session. try again in a minute | approved |
| RFS-6-C31 | sessionExit | carlos run: the box did not open the session: %s | approved |
-| RFS-6-C32 | console door | %s already has an interactive session open, started by %s | approved |
-| RFS-6-C33 | console door | %s runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app %s --instance %s -- <command> | approved |
-| RFS-6-C34 | console door | interactive sessions need this console to hold the release signing key | approved |
-| RFS-6-C35 | console doors, host-claim | interactive sessions are not available on this console yet. they need the host-claim launch protocol | approved |
-| RFS-6-C36 | console door | the session request is malformed | approved |
-| RFS-6-C37 | console door | could not open the session. try again | approved |
+| RFS-6-C32 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | %s already has an interactive session open, started by %s | approved |
+| RFS-6-C33 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | %s runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app %s --instance %s -- <command> | approved |
+| RFS-6-C34 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | interactive sessions need this console to hold the release signing key | approved |
+| RFS-6-C35 | internal/console/apiinteractive.go (console doors on a host-claim console, built by Plan 6 Task 10; the box door is Task 11's) | interactive sessions are not available on this console yet. they need the host-claim launch protocol | approved |
+| RFS-6-C36 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | the session request is malformed | approved |
+| RFS-6-C37 | internal/console/apiinteractive.go (console door, built by Plan 6 Task 10) | could not open the session. try again | approved |
| RFS-6-C38 | internal/console/apiinteractivesetting.go (setting door) | only an owner of the account can turn interactive sessions on | approved |
| RFS-6-C39 | internal/console/apiinteractivesetting.go (setting door) | say whether interactive sessions are on or off | approved |
| RFS-6-C40 | internal/console/apiinteractivesetting.go (setting door audit detail) | turned interactive sessions %s for %s (%s) | approved |
diff --git a/internal/console/apiinteractive.go b/internal/console/apiinteractive.go
new file mode 100644
index 000000000..da41dd2cb
--- /dev/null
+++ b/internal/console/apiinteractive.go
@@ -0,0 +1,527 @@
+// The console's session door, the CLI leg (rootfs apps spec §5.10/C9, Plan
+// 6 Task 10): GET /api/cli/apps/{account}/{app}/instances/{host}/interactive,
+// a WebSocket. `carlos run -it` and `carlos console` dial it; the console
+// admits the session on the instance's record, writes a signed grant that
+// sends the owning box to the box door (Task 11), and holds the CLI's
+// connection until the box attaches or the pickup window closes.
+//
+// GATE: a person only. The route's zero role set refuses every service
+// credential at the mux, and the handler refuses any principal that is not
+// a person with the byte-identical 404: a session is a live shell into
+// production data. apiAccountApp proves membership; the app's own setting
+// (apps set --interactive) must be on.
+//
+// LIFETIMES (PF-4): the request is admitted as a read by serveAdmitted, so
+// the refusals before the upgrade read the record judged as any GET does.
+// The upgrade ends the request's unit (endRequestUnit): a session open for
+// hours never holds a cutover's drain. The admission's writes are one write
+// step (lifetimesStep, mutating), and so is each end's; an end the draining
+// gate refuses waits in the hub's endPending for the sweep.
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "os"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/runs"
+)
+
+const (
+ // RFS-6-C27: the app's setting is off. The app, then the app.
+ interactiveOffMsg = "interactive sessions are off for %s. an owner can turn them on with carlos apps set %s --interactive on"
+ // RFS-6-C32: a live session holds the instance. The host, then who
+ // opened it.
+ interactiveBusyMsg = "%s already has an interactive session open, started by %s"
+ // RFS-6-C33: carlos console on a release with no console process. The
+ // host, the app, the host.
+ interactiveNoConsoleMsg = "%s runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app %s --instance %s -- <command>"
+ // RFS-6-C34: no key to sign the grant with.
+ interactiveNoKeyMsg = "interactive sessions need this console to hold the release signing key"
+ // RFS-6-C35: every session door on a host-claim console.
+ claimInteractiveUnsupportedMsg = "interactive sessions are not available on this console yet. they need the host-claim launch protocol"
+ // RFS-6-C36: the Open frame did not come, or did not pass Check.
+ interactiveMalformedMsg = "the session request is malformed"
+ // RFS-6-C37: the console could not open the session.
+ interactiveFailedMsg = "could not open the session. try again"
+)
+
+const (
+ // interactiveEndTimeout bounds one end step's writes.
+ interactiveEndTimeout = 30 * time.Second
+ // interactiveSendWait bounds one frame the console sends a CLI, so a
+ // CLI that stops reading cannot hold the session past its window.
+ interactiveSendWait = 10 * time.Second
+)
+
+// interactiveDoor is what the refusals before the upgrade established.
+type interactiveDoor struct {
+ acct *Account
+ app, host string
+ by string
+ rec *provision.Record
+}
+
+// handleAPIInteractive is the session door. Its refusals before the upgrade
+// come as JSON errors, in this order, each with its own status: not a
+// person (404), membership (apiAccountApp), a host-claim console (409), the
+// rate (429), no bucket or no key (503), the host's shape or no record
+// (404), the record's class, a move, the app's setting, an uncommitted
+// import and a live session (409). Then the WebSocket.
+func (s *Server) handleAPIInteractive(w http.ResponseWriter, r *http.Request) {
+ p, ok := principalFrom(r.Context())
+ if !ok || p.Kind != PrincipalUser {
+ http.NotFound(w, r)
+ return
+ }
+ actor, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return
+ }
+ if s.cfg.HostClaim {
+ jsonError(w, http.StatusConflict, claimInteractiveUnsupportedMsg)
+ return
+ }
+ if !s.cli.instances.allow(hashToken(bearer(r)), time.Now()) {
+ jsonError(w, http.StatusTooManyRequests, runTooManyMsg)
+ return
+ }
+ if s.cfg.Releases == nil {
+ jsonError(w, http.StatusServiceUnavailable, interactiveFailedMsg)
+ return
+ }
+ if s.cfg.Key == nil {
+ jsonError(w, http.StatusServiceUnavailable, interactiveNoKeyMsg)
+ return
+ }
+ ctx := r.Context()
+ host := r.PathValue("host")
+ notInstance := fmt.Sprintf("%s is not an instance of %s", host, app)
+ if !provision.ValidHostShape(host) {
+ jsonError(w, http.StatusNotFound, notInstance)
+ return
+ }
+ rec, _, err := s.readRecord(ctx, acct.Sqid, app, host)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ jsonError(w, http.StatusNotFound, notInstance)
+ return
+ case err != nil:
+ log.Printf("console: api interactive %s/%s/%s: read record: %v", acct.Sqid, app, host, err)
+ jsonError(w, http.StatusBadGateway, interactiveFailedMsg)
+ return
+ }
+ if msg := instanceClassRefusal(*rec); msg != "" {
+ jsonError(w, http.StatusConflict, msg)
+ return
+ }
+ if rec.Move != nil {
+ jsonError(w, http.StatusConflict, runMovingMsg(host))
+ return
+ }
+ // The setting lives in the default bundle only (appconfig.GetInteractive).
+ on, err := appconfig.GetInteractive(ctx, s.cfg.Releases, acct.Sqid, app)
+ if err != nil {
+ log.Printf("console: api interactive %s/%s: read the setting: %v", acct.Sqid, app, err)
+ jsonError(w, http.StatusBadGateway, interactiveFailedMsg)
+ return
+ }
+ if !on {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(interactiveOffMsg, app, app))
+ return
+ }
+ if rec.ImportUncommitted() {
+ jsonError(w, http.StatusConflict, runImportMsg(host))
+ return
+ }
+ if m := rec.Interactive; m != nil && s.interactive.live(*m, s.bootID) {
+ jsonError(w, http.StatusConflict, fmt.Sprintf(interactiveBusyMsg, host, m.By))
+ return
+ }
+ if s.interactive.afterChecks != nil {
+ s.interactive.afterChecks()
+ }
+ door := interactiveDoor{acct: acct, app: app, host: host, by: actor, rec: rec}
+ interactive.NewServer(func(ws *websocket.Conn) {
+ s.serveInteractive(ctx, ws, door)
+ }).ServeHTTP(w, r)
+}
+
+// serveInteractive is the session after the upgrade, on the CLI's
+// connection, until it ends.
+func (s *Server) serveInteractive(rctx context.Context, ws *websocket.Conn, d interactiveDoor) {
+ // The request's unit ends here (PF-4), and nothing below reads or
+ // writes under the request's context: each write is a step of its own,
+ // on a context that carries no unit and no judge.
+ endRequestUnit(rctx)
+ h := s.interactive
+ h.sessions.Add(1)
+ defer h.sessions.Done()
+ defer ws.Close()
+ // The hijacked connection keeps the deadlines the server's ReadTimeout
+ // set on it; a session outlives them.
+ _ = ws.SetDeadline(time.Time{})
+ ctx := context.Background()
+
+ open, ok := receiveOpen(ws, h.openWait())
+ if !ok {
+ refuseSession(ws, interactive.End{Detail: interactiveMalformedMsg})
+ 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)}
+ if open.Process == release.ProcessConsole {
+ argv, version, refusal := s.resolveConsole(ctx, d)
+ if refusal != nil {
+ refuseSession(ws, *refusal)
+ return
+ }
+ sess.argv, sess.version = argv, version
+ }
+ if fleet, ok := registry.FleetPlacement(d.rec.Region); ok {
+ sess.fleet = fleet
+ }
+ inc, err := provision.Incarnation(d.rec.Account, d.rec.App, d.rec.Host, d.rec.CreatedAt)
+ if err != nil {
+ log.Printf("console: api interactive %s/%s/%s: incarnation: %v", d.acct.Sqid, d.app, d.host, err)
+ refuseSession(ws, interactive.End{Detail: interactiveFailedMsg})
+ return
+ }
+ sess.incarnation = inc
+ id, err := interactive.MintID()
+ var token string
+ if err == nil {
+ token, sess.tokenHash, err = interactive.MintToken()
+ }
+ if err != nil {
+ log.Printf("console: api interactive %s/%s/%s: mint: %v", d.acct.Sqid, d.app, d.host, err)
+ refuseSession(ws, interactive.End{Detail: interactiveFailedMsg})
+ return
+ }
+ sess.id = id
+
+ // Reserved before the grant and the CAS (finding 10), so every other
+ // admission on this console that reads the marker, from the moment the
+ // CAS lands, finds it live. Every failure from here to activate
+ // releases it.
+ h.reserve(sess)
+ activated := false
+ defer func() {
+ if !activated {
+ h.release(sess.id)
+ }
+ }()
+ var refusal *interactive.End
+ err = s.lifetimesStep(ctx, true, func(sctx context.Context) error {
+ sctx, cancel := context.WithTimeout(sctx, interactive.OpenWait)
+ defer cancel()
+ refusal = s.admitSession(sctx, sess, token)
+ activated = refusal == nil
+ return nil
+ })
+ if err != nil {
+ // The gate would not admit the write (it is draining): nothing was
+ // written, and the reservation is released.
+ log.Printf("console: api interactive %s/%s/%s: %v", d.acct.Sqid, d.app, d.host, err)
+ refuseSession(ws, interactive.End{Detail: interactiveFailedMsg})
+ return
+ }
+ if refusal != nil {
+ refuseSession(ws, *refusal)
+ return
+ }
+ if err := sendSessionJSON(ws, interactive.KindStatus, interactive.Status{State: interactive.StateWaiting}); err != nil {
+ s.endSession(ws, sess, interactive.End{Reason: interactive.EndCancelled})
+ return
+ }
+ s.awaitBox(ws, sess)
+}
+
+// receiveOpen reads the CLI's first frame within wait (OpenWait): an Open
+// whose normalized form passes Check, returned as the CLI sent it. The read
+// deadline is cleared after it: a waiting session may be idle for its whole
+// pickup window.
+func receiveOpen(ws *websocket.Conn, wait time.Duration) (interactive.Open, bool) {
+ _ = ws.SetReadDeadline(time.Now().Add(wait))
+ kind, payload, err := interactive.Receive(ws)
+ if err != nil || kind != interactive.KindOpen {
+ return interactive.Open{}, false
+ }
+ var o interactive.Open
+ if err := json.Unmarshal(payload, &o); err != nil || o.Normalized().Check() != nil {
+ return interactive.Open{}, false
+ }
+ _ = ws.SetReadDeadline(time.Time{})
+ return o, true
+}
+
+// resolveConsole is the console process's command: the processes entry of
+// the manifest of the version the record's channel serves. It is used only
+// for the audit row and this check; the box gets the Open as sent.
+func (s *Server) resolveConsole(ctx context.Context, d interactiveDoor) ([]string, string, *interactive.End) {
+ ctx, cancel := context.WithTimeout(ctx, interactive.OpenWait)
+ defer cancel()
+ none := &interactive.End{Detail: fmt.Sprintf(interactiveNoConsoleMsg, d.host, d.app, d.host)}
+ failed := &interactive.End{Detail: interactiveFailedMsg}
+ if d.rec.Channel == "" {
+ return nil, "", none
+ }
+ ptr, err := release.Channel(ctx, s.cfg.Releases, s.cfg.ReleasePub, d.acct.Sqid, d.app, d.rec.Channel)
+ switch {
+ case errors.Is(err, os.ErrNotExist) || err == nil && ptr == nil:
+ return nil, "", none
+ case err != nil:
+ log.Printf("console: api interactive %s/%s/%s: channel %s: %v", d.acct.Sqid, d.app, d.host, d.rec.Channel, err)
+ return nil, "", failed
+ }
+ m, err := release.GetManifest(ctx, s.cfg.Releases, d.acct.Sqid, d.app, ptr.Version)
+ if err != nil {
+ log.Printf("console: api interactive %s/%s/%s: manifest %s: %v", d.acct.Sqid, d.app, d.host, ptr.Version, err)
+ return nil, "", failed
+ }
+ p, ok := m.Processes[release.ProcessConsole]
+ if !ok || len(p.Command) == 0 {
+ return nil, "", none
+ }
+ return p.Command, ptr.Version, nil
+}
+
+// admitSession is the admission's write step (steps 4 to 6): the signed
+// grant, the record CAS, activate, the serial bump and the
+// interactive-start row. A refusal is the End to send, with the grant
+// deleted and nothing else left behind.
+func (s *Server) admitSession(ctx context.Context, sess *hubSession, token string) *interactive.End {
+ h := s.interactive
+ now := time.Now().UTC()
+ sess.pickupBy = now.Add(h.window())
+ g := interactive.Grant{V: 1, ID: sess.id, Account: sess.acct, App: sess.app, Host: sess.host,
+ Incarnation: sess.incarnation, Attach: interactive.AttachURL(s.cfg.Origin, sess.id), Token: token,
+ By: sess.by, IssuedAt: now, PickupBy: sess.pickupBy}
+ failed := &interactive.End{Detail: interactiveFailedMsg}
+ wire, err := interactive.SignGrant(s.cfg.Key, g)
+ if err != nil {
+ log.Printf("console: api interactive %s/%s/%s: sign the grant: %v", sess.acct, sess.app, sess.host, err)
+ return failed
+ }
+ if err := s.putGrant(ctx, sess, wire); err != nil {
+ log.Printf("console: api interactive %s/%s/%s: write the grant %s: %v", sess.acct, sess.app, sess.host, sess.id, err)
+ s.deleteGrant(ctx, sess) // the write may have landed
+ return failed
+ }
+ _, err = provision.SetRecordInteractive(ctx, s.cfg.Releases, sess.acct, sess.app, sess.host,
+ provision.InteractiveAdmit(provision.InteractiveAdmission{ID: sess.id, By: sess.by, Console: s.bootID, PickupBy: sess.pickupBy,
+ Live: func(st provision.InteractiveState) bool { return h.live(st, s.bootID) }}))
+ // updateRecord's retry after a lost response finds this admission's own
+ // marker, live because the id is reserved: that is the admission.
+ var open *provision.InteractiveOpenError
+ if errors.As(err, &open) && open.State.ID == sess.id {
+ err = nil
+ }
+ if err != nil {
+ // A failure whose outcome is unknown may have landed the marker; with
+ // the id released it is dead (not live), so the next admission
+ // replaces it and the sweep clears it.
+ s.deleteGrant(ctx, sess)
+ return admissionRefusal(err, sess)
+ }
+ if h.afterAdmit != nil {
+ h.afterAdmit(sess.id)
+ }
+ if !h.activate(sess.id) {
+ // Unreachable: only this goroutine releases or ends its id.
+ log.Printf("console: api interactive %s/%s/%s: %s was not reserved at activation", sess.acct, sess.app, sess.host, sess.id)
+ }
+ s.bumpSerial(ctx)
+ s.auditActivity(sess.account, sess.app, sess.by, Activity{Action: "interactive-start", TargetType: "instance", Target: sess.host,
+ Detail: interactiveStartDetail(sess)})
+ return nil
+}
+
+// admissionRefusal is the End for a record CAS that did not admit.
+func admissionRefusal(err error, sess *hubSession) *interactive.End {
+ var open *provision.InteractiveOpenError
+ switch {
+ case errors.As(err, &open):
+ return &interactive.End{Refused: interactive.RefusedBusy, Detail: fmt.Sprintf(interactiveBusyMsg, sess.host, open.State.By)}
+ case errors.Is(err, provision.ErrRunMoving):
+ return &interactive.End{Detail: runMovingMsg(sess.host)}
+ case errors.Is(err, provision.ErrRunImport):
+ return &interactive.End{Refused: runs.RefusedImport, Detail: runImportMsg(sess.host)}
+ case errors.Is(err, os.ErrNotExist):
+ return &interactive.End{Detail: fmt.Sprintf("%s is not an instance of %s", sess.host, sess.app)}
+ }
+ log.Printf("console: api interactive %s/%s/%s: admit %s: %v", sess.acct, sess.app, sess.host, sess.id, err)
+ 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.
+func (s *Server) awaitBox(ws *websocket.Conn, sess *hubSession) {
+ frames := make(chan byte)
+ gone := make(chan struct{})
+ stop := make(chan struct{})
+ defer close(stop)
+ go func() {
+ defer close(gone)
+ for {
+ kind, _, err := interactive.Receive(ws)
+ if err != nil {
+ return
+ }
+ select {
+ case frames <- kind:
+ case <-stop:
+ return
+ }
+ }
+ }()
+ pickup := time.NewTimer(time.Until(sess.pickupBy))
+ defer pickup.Stop()
+ for {
+ select {
+ case kind := <-frames:
+ if kind != interactive.KindAlive {
+ continue
+ }
+ if err := sendSession(ws, interactive.KindAlive, nil); err != nil {
+ s.endSession(ws, sess, interactive.End{Reason: interactive.EndCancelled})
+ return
+ }
+ case <-gone:
+ s.endSession(ws, sess, interactive.End{Reason: interactive.EndCancelled})
+ return
+ case <-pickup.C:
+ s.endSession(ws, sess, interactive.End{Reason: interactive.EndExpired})
+ return
+ }
+ }
+}
+
+// endSession ends an admitted session: the CLI gets its End at once, the
+// hub takes the id out of the live set, and the end's writes run as their
+// 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()
+ _ = sendSessionJSON(ws, interactive.KindEnd, e)
+ ws.Close()
+ h := s.interactive
+ h.end(sess.id)
+ err := s.lifetimesStep(context.Background(), true, func(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, interactiveEndTimeout)
+ defer cancel()
+ return s.endWrites(ctx, sess, e)
+ })
+ if err != nil {
+ log.Printf("console: api interactive %s/%s/%s: end %s (%s) waits for the sweep: %v", sess.acct, sess.app, sess.host, sess.id, e.Reason, err)
+ h.pend(sess, e)
+ }
+}
+
+// endWrites are an end's writes: the marker cleared (InteractiveClear: a
+// marker already gone, or replaced by a newer session, is left as it is),
+// the grant deleted and the interactive-end row. A record write that fails
+// is returned before anything else is done, so a retry repeats all three.
+func (s *Server) endWrites(ctx context.Context, sess *hubSession, e interactive.End) error {
+ _, err := provision.SetRecordInteractive(ctx, s.cfg.Releases, sess.acct, sess.app, sess.host, provision.InteractiveClear(sess.id))
+ if err != nil && !errors.Is(err, provision.ErrInteractiveConflict) && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ s.deleteGrant(ctx, sess)
+ s.auditActivity(sess.account, sess.app, sess.by, Activity{Action: "interactive-end", TargetType: "instance", Target: sess.host,
+ Detail: interactiveEndDetail(sess.id, e)})
+ return nil
+}
+
+// finishPendingInteractiveEnds makes the writes of every end the gate
+// refused, under the sweep pass's own unit, and ends each id that lands.
+func (s *Server) finishPendingInteractiveEnds(ctx context.Context) {
+ if s.interactive == nil {
+ return
+ }
+ for sess, e := range s.interactive.pending() {
+ if err := s.endWrites(ctx, sess, e); err != nil {
+ log.Printf("console: run sweep: interactive end %s/%s/%s %s: %v", sess.acct, sess.app, sess.host, sess.id, err)
+ jobFailed(ctx, fmt.Errorf("run sweep: interactive end %s: %w", sess.id, err))
+ continue
+ }
+ s.interactive.finished(sess.id)
+ }
+}
+
+// putGrant writes a session's signed grant to its GrantKey: an object
+// under the app's interactive/ prefix, never a record.
+func (s *Server) putGrant(ctx context.Context, sess *hubSession, wire []byte) error {
+ _, err := s.cfg.Releases.Put(ctx, interactive.GrantKey(sess.acct, sess.app, sess.id), wire, "")
+ return err
+}
+
+// deleteGrant deletes a session's grant, best effort: Task 11's housekeeping
+// deletes a grant no record names.
+func (s *Server) deleteGrant(ctx context.Context, sess *hubSession) {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), interactiveEndTimeout)
+ defer cancel()
+ if err := s.cfg.Releases.Delete(ctx, interactive.GrantKey(sess.acct, sess.app, sess.id)); err != nil && !errors.Is(err, os.ErrNotExist) {
+ log.Printf("console: api interactive %s/%s/%s: delete the grant %s: %v", sess.acct, sess.app, sess.host, sess.id, err)
+ }
+}
+
+// refuseSession ends a session that was never admitted with End refused.
+func refuseSession(ws *websocket.Conn, e interactive.End) {
+ e.Reason, e.Ended = interactive.EndRefused, time.Now().UTC()
+ _ = sendSessionJSON(ws, interactive.KindEnd, e)
+}
+
+func sendSession(ws *websocket.Conn, kind byte, payload []byte) error {
+ _ = ws.SetWriteDeadline(time.Now().Add(interactiveSendWait))
+ return interactive.Send(ws, kind, payload)
+}
+
+func sendSessionJSON(ws *websocket.Conn, kind byte, v any) error {
+ b, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ return sendSession(ws, kind, b)
+}
+
+// interactiveStartDetail is the interactive-start row's detail: the session
+// id, the command it runs, the process when it is the console, and the
+// release that process resolved from.
+func interactiveStartDetail(sess *hubSession) string {
+ raw, _ := json.Marshal(struct {
+ ID string `json:"id"`
+ Argv []string `json:"argv"`
+ Process string `json:"process,omitempty"`
+ Version string `json:"version,omitempty"`
+ }{sess.id, sess.argv, sess.open.Process, sess.version})
+ return string(raw)
+}
+
+// interactiveEndDetail is the interactive-end row's detail.
+func interactiveEndDetail(id string, e interactive.End) string {
+ raw, _ := json.Marshal(struct {
+ ID string `json:"id"`
+ Reason string `json:"reason"`
+ Refused string `json:"refused,omitempty"`
+ Exit int `json:"exit"`
+ Started time.Time `json:"started,omitzero"`
+ Ended time.Time `json:"ended"`
+ Box string `json:"box,omitempty"`
+ }{id, e.Reason, e.Refused, e.Exit, e.Started, e.Ended, e.Box})
+ return string(raw)
+}
diff --git a/internal/console/apiinteractive_lifetimes_test.go b/internal/console/apiinteractive_lifetimes_test.go
new file mode 100644
index 000000000..4cb5c9a56
--- /dev/null
+++ b/internal/console/apiinteractive_lifetimes_test.go
@@ -0,0 +1,397 @@
+package console
+
+// The session door and the lifetimes cutover (rootfs apps Plan 6 Task 10,
+// PF-4): a session holds no unit past its upgrade, each admission and each
+// end is its own write step, and an end the draining gate refuses waits in
+// endPending for the sweep. Through the real gate: the cutover door, the
+// gate's clock (useLifetimesClock), lifetimesWatchOnce and the sweep's
+// lifetimesIteration. Also the request budget (PF-22), counted at the
+// production S3 store's wire.
+
+import (
+ "context"
+ "net/http"
+ "sort"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// newIxLtFx is the session world on a console whose gate runs on the
+// test's clock, with paul an operator for the cutover door.
+func newIxLtFx(t *testing.T, code string) (*interactiveFx, *lifetimesClock) {
+ t.Helper()
+ clock := useLifetimesClock(t)
+ fx := newIxFx(t, code)
+ if err := fx.st.SetOperator("paul@keymail.dev", true); err != nil {
+ t.Fatal(err)
+ }
+ if got := fx.srv.cutover.status().State; got != "before" {
+ t.Fatalf("the gate starts %s, want before", got)
+ }
+ return fx, clock
+}
+
+// ixCutover asks the cutover door as the operator: the gate drains.
+func ixCutover(t *testing.T, fx *interactiveFx) {
+ t.Helper()
+ code, _, body := rawReq(t, http.MethodPost, fx.ts.URL+lifetimesCutoverPath, fx.owner, "")
+ if code != http.StatusOK {
+ t.Fatalf("cutover = %d %s", code, body)
+ }
+ if st := fx.srv.cutover.status().State; st != "draining" {
+ t.Fatalf("after the cutover door the gate is %s, want draining", st)
+ }
+}
+
+// ixActivate moves the gate's clock past the settle and runs one watch pass.
+func ixActivate(t *testing.T, fx *interactiveFx, clock *lifetimesClock) {
+ t.Helper()
+ clock.Advance(lifetimeSettle + time.Second)
+ fx.srv.lifetimesWatchOnce(context.Background())
+ if !fx.srv.lifetimesOn() {
+ t.Fatalf("the gate is %s, want on", fx.srv.cutover.status().State)
+ }
+}
+
+// ixAlive sends a keepalive and wants one back.
+func ixAlive(t *testing.T, wsAlive func() (byte, error)) {
+ t.Helper()
+ if kind, err := wsAlive(); err != nil || kind != interactive.KindAlive {
+ t.Fatalf("keepalive: %q %v, want one back", kind, err)
+ }
+}
+
+// stepSeen is one write step the hook saw.
+type stepSeen struct {
+ mode cutoverState
+ judged bool
+ own bool // the context carries the step's own unit
+}
+
+func hookSteps(t *testing.T) func() []stepSeen {
+ t.Helper()
+ var mu sync.Mutex
+ var seen []stepSeen
+ old := lifetimesStepHook
+ lifetimesStepHook = func(ctx context.Context, u *admittedUnit) {
+ mu.Lock()
+ defer mu.Unlock()
+ seen = append(seen, stepSeen{mode: u.mode, judged: provision.JudgeFrom(ctx) != nil, own: unitFrom(ctx) == u})
+ }
+ t.Cleanup(func() { lifetimesStepHook = old })
+ return func() []stepSeen {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]stepSeen(nil), seen...)
+ }
+}
+
+func TestAWaitingSessionHoldsNoLifetimesUnit(t *testing.T) {
+ fx, clock := newIxLtFx(t, "code-ix-lt-hold")
+ g := fx.srv.cutover
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ alive := func() (byte, error) {
+ if err := interactive.Send(ws, interactive.KindAlive, nil); err != nil {
+ return 0, err
+ }
+ k, _, err := ixRecv(ws)
+ return k, err
+ }
+ if p := g.status().Pending; p != 0 {
+ t.Fatalf("a waiting 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 waiting session holds a unit")
+ }
+ if st := g.status().State; st != "draining" {
+ t.Fatalf("the gate is %s before the settle, want draining", st)
+ }
+ ixAlive(t, alive)
+ ixActivate(t, fx, clock)
+ ixAlive(t, alive)
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("the session ended across the cutover: %+v", evs)
+ }
+ steps := hookSteps(t)
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 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 TestAdmissionRefusedWhileDrainingEndsWithC37(t *testing.T) {
+ fx, _ := newIxLtFx(t, "code-ix-lt-refused")
+ held, ok, _ := fx.srv.lifetimesAdmit(context.Background(), true)
+ if !ok || held.mode != cutoverBefore {
+ t.Fatal("the test's legacy unit was not admitted")
+ }
+ t.Cleanup(held.done)
+ ixCutover(t, fx)
+ var reservedID atomic.Value
+ fx.srv.interactive.afterReserve = func(id string) { reservedID.Store(id) }
+ snap := ixSnapshot(t, fx, ixHost)
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), fx.alice)
+ if err != nil {
+ t.Fatalf("the door's checks are reads, admitted while draining: %v", err)
+ }
+ ixSendOpen(t, ws, ixOpenArgv())
+ if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused || e.Detail != "could not open the session. try again" {
+ t.Fatalf("end %+v, want refused with RFS-6-C37", e)
+ }
+ ixNothingWritten(t, fx, ixHost, snap)
+ reserved, _ := reservedID.Load().(string)
+ if reserved == "" || hubState(fx.srv.interactive, reserved) != "" || hubCount(fx.srv.interactive) != 0 {
+ t.Fatalf("the hub holds %q as %q", reserved, hubState(fx.srv.interactive, reserved))
+ }
+}
+
+// ixSweep is one pass of the run sweep as its worker runs it: a mutating
+// lifetimes iteration. It reports whether the pass was admitted.
+func ixSweep(fx *interactiveFx) bool {
+ return fx.srv.lifetimesIteration(context.Background(), "run sweep", true, false, func(ctx context.Context) {
+ fx.srv.runSweepPass(ctx, time.Now(), false)
+ })
+}
+
+func TestAWaitingSessionExpiresDuringTheDrain(t *testing.T) {
+ fx, clock := newIxLtFx(t, "code-ix-lt-expire")
+ h := fx.srv.interactive
+ h.pickupWindow = time.Second
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ rec, _ := ixRecord(t, fx, ixHost)
+ id := rec.Interactive.ID
+ ixCutover(t, fx)
+ if e := ixWantEnd(t, ws); e.Reason != interactive.EndExpired {
+ t.Fatalf("end %+v, want expired at PickupBy, with no write needed to say so", e)
+ }
+ deadline := time.Now().Add(10 * time.Second)
+ for hubState(h, id) != "pending" && time.Now().Before(deadline) {
+ time.Sleep(10 * time.Millisecond)
+ }
+ if st := hubState(h, id); st != "pending" {
+ t.Fatalf("hub: %q, want pending (the end step refused while draining)", st)
+ }
+ h.mu.Lock()
+ pendingEnd := h.endPending[id]
+ h.mu.Unlock()
+ if pendingEnd.Reason != interactive.EndExpired {
+ t.Fatalf("endPending %+v", pendingEnd)
+ }
+ grant := 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(), grant); 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")
+
+ 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 g := ixGrants(t, fx); len(g) != 0 {
+ t.Fatalf("grants %v left after the sweep", g)
+ }
+ evs := ixEvents(t, fx, "interactive-end")
+ if len(evs) != 1 || ixEndRow(t, evs[0]).Reason != interactive.EndExpired || ixEndRow(t, evs[0]).ID != id {
+ t.Fatalf("end rows %+v, want one expired", evs)
+ }
+ if st := hubState(h, id); st != "ended" {
+ t.Fatalf("hub: %q, want ended", st)
+ }
+ 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)
+ }
+}
+
+func TestASessionsEndStepIsItsOwnUnit(t *testing.T) {
+ fx, clock := newIxLtFx(t, "code-ix-lt-end")
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ ixCutover(t, fx)
+ ixActivate(t, fx, clock)
+ steps := hookSteps(t)
+ slot := provision.HostIncarnationKey(ixHost)
+ var mu sync.Mutex
+ var slotReads int
+ fx.rel.(*deletableStore).setGetHook(func(_ context.Context, key string) error {
+ if key == slot {
+ mu.Lock()
+ slotReads++
+ mu.Unlock()
+ }
+ return nil
+ })
+ ws.Close()
+ evs := ixWaitEvents(t, fx, "interactive-end", 1)
+ if d := ixEndRow(t, evs[0]); d.Reason != interactive.EndCancelled {
+ t.Fatalf("end row %+v", d)
+ }
+ 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 unit admitted on, judged, its own", s)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if slotReads == 0 {
+ t.Fatal("the end's record write read no incarnation slot: it was not judged")
+ }
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive != nil {
+ t.Fatalf("marker %+v left", rec.Interactive)
+ }
+ if p := fx.srv.cutover.status().Pending; p != 0 {
+ t.Fatalf("%d units still counted", p)
+ }
+}
+
+// ---- the request budget (PF-22) -------------------------------------------
+
+// ixBudgetClass names the object a store request touched.
+func ixBudgetClass(path string) string {
+ switch {
+ case strings.HasSuffix(path, "/"+release.ChangeIndexKey):
+ return "index"
+ case strings.HasSuffix(path, "/"+release.SerialKey):
+ return "serial"
+ case strings.Contains(path, "/control/host-incarnations/"):
+ return "slot"
+ case strings.Contains(path, "/instances/"):
+ return "record"
+ case strings.Contains(path, "/interactive/"):
+ return "grant"
+ case strings.HasSuffix(path, "/config.json"):
+ return "config"
+ case strings.Contains(path, "/channels/"):
+ return "channel"
+ case strings.HasSuffix(path, "/manifest.json"):
+ return "manifest"
+ }
+ return "other " + path
+}
+
+// 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.
+//
+// The box's attach (Task 11) adds no console request: the box door reads
+// the hub, the token and the registry, and writes nothing.
+func TestInteractiveRequestBudget(t *testing.T) {
+ type counts map[string]int
+ legacy := counts{
+ "GET record": 3, "PUT record": 2, "GET config": 1,
+ "PUT grant": 1, "DELETE grant": 1,
+ "GET index": 4, "PUT index": 4,
+ "GET serial": 1, "PUT serial": 1,
+ }
+ plus := func(base counts, more counts) counts {
+ out := counts{}
+ for k, v := range base {
+ out[k] += v
+ }
+ for k, v := range more {
+ out[k] += v
+ }
+ return out
+ }
+ judged := plus(legacy, counts{"GET slot": 3})
+ console := counts{"GET channel": 1, "GET manifest": 1}
+ for _, c := range []struct {
+ name string
+ judged bool
+ console 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},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ clock := useLifetimesClock(t)
+ lat := &perfLatency{}
+ fx := newInteractiveFxWith(t, 7, "code-ix-budget", consoleFixtureOptions{WithKey: true, S3: lat})
+ ixWorld(t, fx)
+ o := ixOpenArgv()
+ if c.console {
+ 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"})
+ o = interactive.Open{Schema: 1, Process: release.ProcessConsole}
+ }
+ if c.judged {
+ turnLifetimesOn(t, fx.srv, clock)
+ } else if st := fx.srv.cutover.status().State; st != "before" {
+ t.Fatalf("the gate is %s, want before", st)
+ }
+ if on, err := appconfig.GetInteractive(context.Background(), fx.rel, fx.acct, "shop"); err != nil || !on {
+ t.Fatalf("setting %v %v", on, err)
+ }
+ var mu sync.Mutex
+ var log []string
+ lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
+ mu.Lock()
+ log = append(log, r.Method+" "+r.URL.Path)
+ mu.Unlock()
+ return 0, nil
+ })
+ ws := ixStart(t, fx, fx.alice, o)
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+ lat.Fake().OnRequest(nil)
+ mu.Lock()
+ defer mu.Unlock()
+ got := counts{}
+ for _, l := range log {
+ method, path, _ := strings.Cut(l, " ")
+ got[method+" "+ixBudgetClass(path)]++
+ }
+ if len(log) != c.total || !equalCounts(got, c.want) {
+ sort.Strings(log)
+ t.Fatalf("%d store requests, want %d:\n got %v\nwant %v\n%s", len(log), c.total, got, c.want, strings.Join(log, "\n"))
+ }
+ })
+ }
+}
+
+func equalCounts(a, b map[string]int) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if b[k] != v {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/console/apiinteractive_test.go b/internal/console/apiinteractive_test.go
new file mode 100644
index 000000000..3b378dff1
--- /dev/null
+++ b/internal/console/apiinteractive_test.go
@@ -0,0 +1,992 @@
+package console
+
+// The console's session door, the CLI leg (rootfs apps Plan 6 Task 10):
+// admission and the refusals before the upgrade, the grant, the record CAS
+// and activation, and the end of a session nobody picked up. Every test
+// goes through the real console (newConsoleFixture's NewServer, its mux,
+// serveAdmitted and the lifetimes gate) and a WebSocket client from
+// interactive.Dial. Account bah, app shop, host shop.example.com.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "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"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+const ixHost = "shop.example.com"
+
+// newIxFx is the session world: bah's shop with interactive sessions on and
+// a hibernating exec instance at shop.example.com on a platform box,
+// channel stable. Every session a test leaves open is closed, and its end
+// written, before the fixture's store closes.
+func newIxFx(t *testing.T, code string) *interactiveFx {
+ t.Helper()
+ fx := newInteractiveFx(t, 7, code)
+ ixWorld(t, fx)
+ return fx
+}
+
+func ixWorld(t *testing.T, fx *interactiveFx) {
+ t.Helper()
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk"})
+ if _, err := appconfig.SetInteractive(context.Background(), fx.rel, fx.acct, "shop", true); err != nil {
+ t.Fatal(err)
+ }
+ // Registered after the fixture, so it runs before the store closes and
+ // after every test connection's own cleanup has closed it.
+ t.Cleanup(func() { fx.srv.interactive.sessions.Wait() })
+}
+
+// ixPutRecord writes (or overwrites) an instance record of bah's shop, as
+// putAcctShopRecord shapes it.
+func ixPutRecord(t *testing.T, fx *interactiveFx, rec provision.Record) {
+ t.Helper()
+ key := provision.RecordKey(fx.acct, "shop", rec.Host)
+ if _, etag, err := fx.rel.Get(context.Background(), key); err == nil {
+ if err := release.DeleteIfMatch(context.Background(), fx.rel, key, etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ putAcctShopRecord(t, fx, rec)
+}
+
+func (fx *interactiveFx) ixURL(host string) string {
+ return fx.ts.URL + "/api/cli/apps/" + fx.acct + "/shop/instances/" + host + "/interactive"
+}
+
+// ixDial opens the session door at u as token. The connection is closed
+// when the test ends.
+func ixDial(t *testing.T, origin, u, token string) (*websocket.Conn, error) {
+ t.Helper()
+ wsURL, err := interactive.WebSocketURL(u)
+ if err != nil {
+ return nil, err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ ws, err := interactive.Dial(ctx, wsURL, origin, http.Header{"Authorization": {"Bearer " + token}})
+ if err == nil {
+ t.Cleanup(func() { ws.Close() })
+ }
+ return ws, err
+}
+
+func ixOpenArgv() interactive.Open {
+ return interactive.Open{Schema: 1, Argv: []string{"bin/rails", "db:migrate:status"}, Term: "xterm-256color", Cols: 80, Rows: 24}
+}
+
+func ixSendOpen(t *testing.T, ws *websocket.Conn, o interactive.Open) {
+ t.Helper()
+ if err := interactive.SendJSON(ws, interactive.KindOpen, o); err != nil {
+ t.Fatalf("send open: %v", err)
+ }
+}
+
+// ixRecv is the next frame, within 10 seconds.
+func ixRecv(ws *websocket.Conn) (byte, []byte, error) {
+ _ = ws.SetReadDeadline(time.Now().Add(10 * time.Second))
+ return interactive.Receive(ws)
+}
+
+// ixNext reads the next frame: a Status's state, or the End.
+func ixNext(ws *websocket.Conn) (state string, end *interactive.End, err error) {
+ kind, payload, err := ixRecv(ws)
+ if err != nil {
+ return "", nil, err
+ }
+ switch kind {
+ case interactive.KindStatus:
+ var st interactive.Status
+ if err := json.Unmarshal(payload, &st); err != nil {
+ return "", nil, err
+ }
+ return st.State, nil, nil
+ case interactive.KindEnd:
+ var e interactive.End
+ if err := json.Unmarshal(payload, &e); err != nil {
+ return "", nil, err
+ }
+ return "", &e, nil
+ }
+ return "", nil, fmt.Errorf("frame kind %q", kind)
+}
+
+func ixWantWaiting(t *testing.T, ws *websocket.Conn) {
+ t.Helper()
+ state, end, err := ixNext(ws)
+ if err != nil || end != nil || state != interactive.StateWaiting {
+ t.Fatalf("first frame: state %q, end %+v, %v; want Status waiting", state, end, err)
+ }
+}
+
+func ixWantEnd(t *testing.T, ws *websocket.Conn) interactive.End {
+ t.Helper()
+ state, end, err := ixNext(ws)
+ if err != nil || end == nil {
+ t.Fatalf("frame: state %q, %v; want an End", state, err)
+ }
+ return *end
+}
+
+// ixStart opens a waiting session as token and returns its connection.
+func ixStart(t *testing.T, fx *interactiveFx, token string, o interactive.Open) *websocket.Conn {
+ t.Helper()
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), token)
+ if err != nil {
+ t.Fatalf("dial: %v", err)
+ }
+ ixSendOpen(t, ws, o)
+ ixWantWaiting(t, ws)
+ return ws
+}
+
+// ixRecord is the stored record of host, read raw.
+func ixRecord(t *testing.T, fx *interactiveFx, host string) (provision.Record, []byte) {
+ t.Helper()
+ raw, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.acct, "shop", host))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rec provision.Record
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ return rec, raw
+}
+
+func ixGrants(t *testing.T, fx *interactiveFx) []string {
+ t.Helper()
+ keys, err := fx.rel.List(context.Background(), interactive.Prefix(fx.acct, "shop"))
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ t.Fatal(err)
+ }
+ return keys
+}
+
+func ixEvents(t *testing.T, fx *interactiveFx, action string) []Event {
+ t.Helper()
+ evs, err := fx.st.Events(fx.acctID, "shop", 200)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []Event
+ for _, e := range evs {
+ if e.Action == action {
+ out = append(out, e)
+ }
+ }
+ return out
+}
+
+// ixWaitEvents waits up to 10 seconds for n rows of action.
+func ixWaitEvents(t *testing.T, fx *interactiveFx, action string, n int) []Event {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ evs := ixEvents(t, fx, action)
+ if len(evs) >= n || time.Now().After(deadline) {
+ if len(evs) != n {
+ t.Fatalf("%d %s rows, want %d: %+v", len(evs), action, n, evs)
+ }
+ return evs
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+type ixEndDetail struct {
+ ID string `json:"id"`
+ Reason string `json:"reason"`
+ Refused string `json:"refused"`
+ Exit int `json:"exit"`
+ Started time.Time `json:"started"`
+ Ended time.Time `json:"ended"`
+ Box string `json:"box"`
+}
+
+func ixEndRow(t *testing.T, e Event) ixEndDetail {
+ t.Helper()
+ var d ixEndDetail
+ if err := json.Unmarshal([]byte(e.Detail), &d); err != nil {
+ t.Fatalf("interactive-end detail %q: %v", e.Detail, err)
+ }
+ return d
+}
+
+// hubState is what the hub holds for id: "" (nothing), "reserved",
+// "active", "ended" or "pending".
+func hubState(h *interactiveHub, id string) string {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if s, ok := h.byID[id]; ok {
+ if s.active {
+ return "active"
+ }
+ return "reserved"
+ }
+ if _, ok := h.endPending[id]; ok {
+ return "pending"
+ }
+ if h.ended[id] {
+ return "ended"
+ }
+ return ""
+}
+
+// hubCount is how many sessions the hub holds reserved or active.
+func hubCount(h *interactiveHub) int {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return len(h.byID)
+}
+
+func hubSessionOf(h *interactiveHub, id string) *hubSession {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ return h.byID[id]
+}
+
+// ixUnchanged is what a refused request must leave as it was.
+type ixUnchanged struct {
+ record []byte
+ serial int64
+}
+
+func ixSnapshot(t *testing.T, fx *interactiveFx, host string) ixUnchanged {
+ t.Helper()
+ snap := ixUnchanged{serial: serial(t, fx.consoleFixture)}
+ if raw, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.acct, "shop", host)); err == nil {
+ snap.record = raw
+ }
+ return snap
+}
+
+func ixNothingWritten(t *testing.T, fx *interactiveFx, host string, snap ixUnchanged) {
+ t.Helper()
+ raw, _, _ := fx.rel.Get(context.Background(), provision.RecordKey(fx.acct, "shop", host))
+ if string(raw) != string(snap.record) {
+ t.Errorf("the record changed:\n%s\nwas\n%s", raw, snap.record)
+ }
+ if g := ixGrants(t, fx); len(g) != 0 {
+ t.Errorf("grant objects %v", g)
+ }
+ if evs := append(ixEvents(t, fx, "interactive-start"), ixEvents(t, fx, "interactive-end")...); len(evs) != 0 {
+ t.Errorf("audit rows %+v", evs)
+ }
+ if got := serial(t, fx.consoleFixture); got != snap.serial {
+ t.Errorf("serial %d, want %d", got, snap.serial)
+ }
+}
+
+func ixGet(t *testing.T, fx *interactiveFx, host, token string) (int, http.Header, string) {
+ t.Helper()
+ return rawReq(t, http.MethodGet, fx.ixURL(host), token, "")
+}
+
+// TestInteractiveRefusalsInOrder walks the door's refusals 1 to 11 with every
+// later one also failing, so each answer proves it comes before the rest;
+// then fixes it and goes on. Nothing is written by any of them.
+func TestInteractiveRefusalsInOrder(t *testing.T) {
+ fx := newInteractiveFx(t, 7, "code-ix-order")
+ t.Cleanup(func() { fx.srv.interactive.sessions.Wait() })
+ ctx := context.Background()
+ s := fx.srv
+ no := false
+ // The record, broken for refusals 7 to 11: pooled (7), moving (8), an
+ // uncommitted import (10) and a live marker (11); the setting is off (9).
+ const liveID = "tty_aaaaaaaaaaaaaaaaaaaaaaaaaa"
+ broken := provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Pool: "shop",
+ Move: &provision.MoveState{ID: "mv_1", To: "ie"},
+ Seed: &provision.SeedSource{Kind: seeds.KindImport, State: seeds.StatePlaced},
+ Interactive: &provision.InteractiveState{ID: liveID, By: "bob@keymail.dev", Console: s.bootID, PickupBy: time.Now().Add(time.Minute)},
+ }
+ s.interactive.reserve(&hubSession{id: liveID, acct: fx.acct, app: "shop", host: ixHost})
+ _ = no
+
+ type step struct {
+ name string
+ token string
+ host string
+ status int
+ msg string
+ fix func()
+ }
+ stranger := cliToken(t, fx.consoleFixture, "mallory@keymail.dev", "code-ix-order-stranger")
+ realRel, realKey := s.cfg.Releases, s.cfg.Key
+
+ // 1. Not a person. The mux's gate refuses a service credential first
+ // (the route's zero role set); the handler's own check answers 404 for
+ // any principal that is not a person.
+ svc := serviceToken(t, fx.st, fx.acctID, "ci-admin", "shop", "admin")
+ if code, _, out := ixGet(t, fx, ixHost, svc); code != http.StatusForbidden || !strings.Contains(out, "closed to service credentials") {
+ t.Fatalf("a service credential: %d %s, want the closed-door 403", code, out)
+ }
+ req := httptest.NewRequest(http.MethodGet, fx.ixURL(ixHost), nil)
+ req.SetPathValue("account", fx.acct)
+ req.SetPathValue("app", "shop")
+ req.SetPathValue("host", ixHost)
+ // The credential's own principal, a member of bah bound to shop: only
+ // the handler's person check stands between it and the door.
+ svcP, ok := fx.st.CLIPrincipal(svc, time.Now())
+ if !ok || svcP.Kind != PrincipalService {
+ t.Fatalf("the service credential resolves to %+v", svcP)
+ }
+ req = req.WithContext(context.WithValue(req.Context(), cliRouteKey{}, svcP))
+ rec := httptest.NewRecorder()
+ s.handleAPIInteractive(rec, req)
+ assertNotFound(t, "1 not a person", canonicalNotFound(t), rec.Code, rec.Header(), rec.Body.String())
+
+ // From here the record exists, broken for 7 to 11, and the bucket and
+ // key are taken away for 5.
+ ixPutRecord(t, fx, broken)
+ snap := ixSnapshot(t, fx, ixHost)
+
+ // 2. Membership: a stranger gets the byte-identical 404.
+ s.cfg.HostClaim = true
+ s.cli.instances = newRateLimiter(1, cliRateWindow)
+ s.cli.instances.allow(hashToken(fx.alice), time.Now())
+ code, h, out := ixGet(t, fx, ixHost, stranger)
+ assertNotFound(t, "2 a stranger", canonicalNotFound(t), code, h, out)
+
+ steps := []step{
+ {"3 host claims", fx.alice, ixHost, http.StatusConflict, claimInteractiveUnsupportedMsg, func() { s.cfg.HostClaim = false }},
+ {"4 rate", fx.alice, ixHost, http.StatusTooManyRequests, runTooManyMsg, func() {
+ s.cli.instances = newRateLimiter(1000, cliRateWindow)
+ s.cfg.Releases = nil
+ }},
+ {"5 no bucket", fx.alice, ixHost, http.StatusServiceUnavailable, "could not open the session. try again", func() {
+ s.cfg.Releases = realRel
+ s.cfg.Key = nil
+ }},
+ {"5 no key", fx.alice, ixHost, http.StatusServiceUnavailable, "interactive sessions need this console to hold the release signing key", func() { s.cfg.Key = realKey }},
+ {"6 host shape", fx.alice, "Not_A_Host", http.StatusNotFound, "Not_A_Host is not an instance of shop", nil},
+ {"6 no record", fx.alice, "other.example.com", http.StatusNotFound, "other.example.com is not an instance of shop", nil},
+ {"7 class", fx.alice, ixHost, http.StatusConflict, ixHost + " is a pooled instance. carlos run works on instances with a process of their own", func() {
+ broken.Pool = ""
+ ixPutRecord(t, fx, broken)
+ }},
+ {"8 moving", fx.alice, ixHost, http.StatusConflict, runMovingMsg(ixHost), func() {
+ broken.Move = nil
+ ixPutRecord(t, fx, broken)
+ }},
+ {"9 setting off", fx.alice, ixHost, http.StatusConflict, "interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on", func() {
+ if _, err := appconfig.SetInteractive(ctx, fx.rel, fx.acct, "shop", true); err != nil {
+ t.Fatal(err)
+ }
+ }},
+ {"10 uncommitted import", fx.alice, ixHost, http.StatusConflict, runImportMsg(ixHost), func() {
+ broken.Seed = nil
+ ixPutRecord(t, fx, broken)
+ }},
+ {"11 a live marker", fx.alice, ixHost, http.StatusConflict, ixHost + " already has an interactive session open, started by bob@keymail.dev", nil},
+ }
+ // The host's shape is checked before the bucket is read at all.
+ var gets atomic.Int64
+ ds := fx.rel.(*deletableStore)
+ for _, st := range steps {
+ snap = ixSnapshot(t, fx, ixHost)
+ gets.Store(0)
+ ds.setGetHook(func(context.Context, string) error { gets.Add(1); return nil })
+ code, _, out := ixGet(t, fx, st.host, st.token)
+ ds.setGetHook(nil)
+ if st.host == "Not_A_Host" && gets.Load() != 0 {
+ t.Errorf("%s: the bucket was read %d times before the refusal", st.name, gets.Load())
+ }
+ if code != st.status || interactiveError(t, out) != st.msg {
+ t.Errorf("%s: %d %s, want %d %q", st.name, code, out, st.status, st.msg)
+ }
+ ixNothingWritten(t, fx, ixHost, snap)
+ if st.fix != nil {
+ st.fix()
+ }
+ }
+ // With the live marker's session gone from the hub, the same request is
+ // admitted: the walk's world was otherwise whole.
+ s.interactive.release(liveID)
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestInteractiveOnAHostClaimConsole(t *testing.T) {
+ fx := newIxFx(t, "code-ix-claim")
+ fx.srv.cfg.HostClaim = true
+ var gets atomic.Int64
+ fx.rel.(*deletableStore).setGetHook(func(context.Context, string) error { gets.Add(1); return nil })
+ code, _, out := ixGet(t, fx, ixHost, fx.alice)
+ if code != http.StatusConflict || interactiveError(t, out) != claimInteractiveUnsupportedMsg {
+ t.Fatalf("%d %s, want 409 %q", code, out, claimInteractiveUnsupportedMsg)
+ }
+ if n := gets.Load(); n != 0 {
+ t.Fatalf("the host-claim refusal read the bucket %d times, want none", n)
+ }
+}
+
+func TestInteractiveAdmitsAndWaits(t *testing.T) {
+ fx := newIxFx(t, "code-ix-admit")
+ before := serial(t, fx.consoleFixture)
+ start := time.Now()
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ rec, _ := ixRecord(t, fx, ixHost)
+ m := rec.Interactive
+ if m == nil || !interactive.ValidID(m.ID) || m.Console != fx.srv.bootID || m.By != "alice@keymail.dev" {
+ t.Fatalf("marker %+v, want this console's boot %q and alice", m, fx.srv.bootID)
+ }
+ if d := m.PickupBy.Sub(start); d < 59*time.Second || d > 61*time.Second+5*time.Second {
+ t.Errorf("PickupBy is %v after the request, want about 60 s", d)
+ }
+ wire, _, err := fx.rel.Get(context.Background(), interactive.GrantKey(fx.acct, "shop", m.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 does not verify under the release key: %v", err)
+ }
+ inc, _ := provision.Incarnation(fx.acct, "shop", ixHost, rec.CreatedAt)
+ if g.ID != m.ID || g.Account != fx.acct || g.App != "shop" || g.Host != ixHost || g.Incarnation != inc ||
+ g.Attach != fx.ts.URL+"/api/box/interactive/"+m.ID || g.By != "alice@keymail.dev" || !g.PickupBy.Equal(m.PickupBy) {
+ t.Fatalf("grant %+v, marker %+v", g, m)
+ }
+ sess := hubSessionOf(fx.srv.interactive, m.ID)
+ if sess == nil || !sess.active || !interactive.TokenMatches(g.Token, sess.tokenHash) || sess.incarnation != inc || sess.fleet != "" {
+ t.Fatalf("hub session %+v", sess)
+ }
+ evs := ixEvents(t, fx, "interactive-start")
+ if len(evs) != 1 || evs[0].Target != ixHost || evs[0].Address != "alice@keymail.dev" {
+ t.Fatalf("interactive-start rows %+v", evs)
+ }
+ var d struct {
+ ID string `json:"id"`
+ Argv []string `json:"argv"`
+ Process string `json:"process"`
+ Version string `json:"version"`
+ }
+ if err := json.Unmarshal([]byte(evs[0].Detail), &d); err != nil || d.ID != m.ID || strings.Join(d.Argv, " ") != "bin/rails db:migrate:status" || d.Process != "" {
+ t.Fatalf("interactive-start detail %q: %v", evs[0].Detail, err)
+ }
+ if got := serial(t, fx.consoleFixture); got != before+1 {
+ t.Fatalf("serial %d, want %d", got, before+1)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestInteractiveAdmitsARootfsResident(t *testing.T) {
+ fx := newIxFx(t, "code-ix-rootfs")
+ no := false
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "uk"})
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestInteractiveAdmitsAFleetInstance(t *testing.T) {
+ fx := newIxFx(t, "code-ix-fleet")
+ no := false
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "fleet/home"})
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ rec, _ := ixRecord(t, fx, ixHost)
+ if sess := hubSessionOf(fx.srv.interactive, rec.Interactive.ID); sess == nil || sess.fleet != "home" {
+ t.Fatalf("hub session %+v, want fleet home", sess)
+ }
+ // A run on the same record is still refused with the fleet sentence.
+ status, body := postRun(t, fx.runsURL(ixHost), fx.alice, okMeta(), nil)
+ if status != http.StatusConflict || errorOf(t, body) != ixHost+" runs on your fleet home. carlos run works on platform boxes only" {
+ t.Fatalf("a run on the fleet record: %d %s", status, body)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestInteractiveRefusedWhenTheAppDisallows(t *testing.T) {
+ fx := newIxFx(t, "code-ix-off")
+ if _, err := appconfig.SetInteractive(context.Background(), fx.rel, fx.acct, "shop", false); err != nil {
+ t.Fatal(err)
+ }
+ snap := ixSnapshot(t, fx, ixHost)
+ code, _, out := ixGet(t, fx, ixHost, fx.alice)
+ if want := "interactive sessions are off for shop. an owner can turn them on with carlos apps set shop --interactive on"; code != http.StatusConflict || interactiveError(t, out) != want {
+ t.Fatalf("%d %s, want 409 %q", code, out, want)
+ }
+ ixNothingWritten(t, fx, ixHost, snap)
+ if code, out := fx.put(t, fx.owner, `{"interactive":true}`); code != http.StatusOK {
+ t.Fatalf("owner on = %d %s", code, out)
+ }
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+// shipShopRootfs ships and promotes to stable a rootfs release of bah's
+// shop, with a console process when console is not nil.
+func shipShopRootfs(t *testing.T, fx *interactiveFx, version string, console []string) {
+ t.Helper()
+ ctx := context.Background()
+ procs := map[string]release.Process{release.ProcessWeb: {Command: []string{"/rails/bin/web"}}}
+ if console != nil {
+ procs[release.ProcessConsole] = release.Process{Command: console, WorkingDir: "/rails"}
+ }
+ m := release.Manifest{Schema: 1, App: "shop", Version: version, Kind: release.KindRootfs, BuiltAt: "2026-10-24T10:00:00Z",
+ Artifacts: map[string]release.Artifact{release.RootfsArtifactKey: {File: release.RootfsArtifactFile}},
+ Processes: procs}
+ if err := release.Ship(ctx, fx.rel, fx.acct, m, map[string][]byte{release.RootfsArtifactKey: []byte("hsqs" + version)}); err != nil {
+ t.Fatal(err)
+ }
+ if err := release.Promote(ctx, fx.rel, fx.priv, fx.acct, "shop", "stable", version); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestConsoleProcessResolvesFromTheManifest(t *testing.T) {
+ fx := newIxFx(t, "code-ix-console")
+ no := false
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Runtime: provision.RuntimeRootfsV1, Hibernate: &no, Region: "uk"})
+ console := interactive.Open{Schema: 1, Process: release.ProcessConsole, Term: "xterm-256color", Cols: 120, Rows: 40}
+
+ // A release with no console process: refused, with nothing left behind.
+ shipShopRootfs(t, fx, "r1", nil)
+ snap := ixSnapshot(t, fx, ixHost)
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), fx.alice)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ixSendOpen(t, ws, console)
+ want := ixHost + " runs a release that declares no console process. add a console entry to processes in the app's manifest, or name the command: carlos run -it --app shop --instance " + ixHost + " -- <command>"
+ if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused || e.Detail != want {
+ t.Fatalf("end %+v, want refused %q", e, want)
+ }
+ ixNothingWritten(t, fx, ixHost, snap)
+ if n := hubCount(fx.srv.interactive); n != 0 {
+ t.Fatalf("the hub holds %d sessions", n)
+ }
+
+ shipShopRootfs(t, fx, "r2", []string{"bin/rails", "console"})
+ ws = ixStart(t, fx, fx.alice, console)
+ rec, _ := ixRecord(t, fx, ixHost)
+ sess := hubSessionOf(fx.srv.interactive, rec.Interactive.ID)
+ if sess == nil || strings.Join(sess.argv, " ") != "bin/rails console" {
+ t.Fatalf("hub session %+v, want argv bin/rails console", sess)
+ }
+ // The Open is kept as the CLI sent it: the box runs the declared
+ // process with its own env and working directory.
+ if sess.open.Process != release.ProcessConsole || sess.open.Argv != nil || sess.open.Cols != 120 || sess.open.Rows != 40 {
+ t.Fatalf("hub session open %+v, want Process console and no argv", sess.open)
+ }
+ var d struct {
+ Argv []string `json:"argv"`
+ Process string `json:"process"`
+ Version string `json:"version"`
+ }
+ evs := ixEvents(t, fx, "interactive-start")
+ if len(evs) != 1 || json.Unmarshal([]byte(evs[0].Detail), &d) != nil || strings.Join(d.Argv, " ") != "bin/rails console" || d.Process != "console" || d.Version != "r2" {
+ t.Fatalf("interactive-start rows %+v", evs)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestInteractiveMalformedOpenEndsRefused(t *testing.T) {
+ fx := newIxFx(t, "code-ix-malformed")
+ for name, o := range map[string]interactive.Open{
+ "schema": {Schema: 2, Argv: []string{"sh"}},
+ "no command": {Schema: 1},
+ "both": {Schema: 1, Argv: []string{"sh"}, Process: release.ProcessConsole},
+ "bad process": {Schema: 1, Process: "web"},
+ "bad terminal": {Schema: 1, Argv: []string{"sh"}, Term: "x y"},
+ "too wide": {Schema: 1, Argv: []string{"sh"}, Cols: 1001, Rows: 24},
+ } {
+ snap := ixSnapshot(t, fx, ixHost)
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), fx.alice)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ixSendOpen(t, ws, o)
+ if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused || e.Detail != "the session request is malformed" {
+ t.Errorf("%s: end %+v, want refused with RFS-6-C36", name, e)
+ }
+ ixNothingWritten(t, fx, ixHost, snap)
+ }
+ // A frame that is not an Open is refused the same way.
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), fx.alice)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := interactive.Send(ws, interactive.KindData, []byte("ls\n")); err != nil {
+ t.Fatal(err)
+ }
+ if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused || e.Detail != "the session request is malformed" {
+ t.Fatalf("data first: end %+v", e)
+ }
+}
+
+func TestPickupWindowExpiresTheSession(t *testing.T) {
+ fx := newIxFx(t, "code-ix-expire")
+ fx.srv.interactive.pickupWindow = 300 * time.Millisecond
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ rec, _ := ixRecord(t, fx, ixHost)
+ id := rec.Interactive.ID
+ e := ixWantEnd(t, ws)
+ if e.Reason != interactive.EndExpired || e.Ended.IsZero() {
+ t.Fatalf("end %+v, want expired", e)
+ }
+ evs := ixWaitEvents(t, fx, "interactive-end", 1)
+ if d := ixEndRow(t, evs[0]); d.ID != id || d.Reason != interactive.EndExpired {
+ t.Fatalf("interactive-end %+v", d)
+ }
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive != nil {
+ t.Fatalf("marker %+v left after expiry", rec.Interactive)
+ }
+ if g := ixGrants(t, fx); len(g) != 0 {
+ t.Fatalf("grants %v left after expiry", g)
+ }
+ if st := hubState(fx.srv.interactive, id); st != "ended" {
+ t.Fatalf("hub: %q, want ended", st)
+ }
+ fx.srv.interactive.pickupWindow = 0
+ ws = ixStart(t, fx, fx.alice, ixOpenArgv())
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 2)
+}
+
+func TestCancelledBeforePickup(t *testing.T) {
+ fx := newIxFx(t, "code-ix-cancel")
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ rec, _ := ixRecord(t, fx, ixHost)
+ id := rec.Interactive.ID
+ ws.Close()
+ evs := ixWaitEvents(t, fx, "interactive-end", 1)
+ if d := ixEndRow(t, evs[0]); d.ID != id || d.Reason != interactive.EndCancelled {
+ t.Fatalf("interactive-end %+v", d)
+ }
+ if rec, _ := ixRecord(t, fx, ixHost); rec.Interactive != nil {
+ t.Fatalf("marker %+v left after the cancel", rec.Interactive)
+ }
+ if g := ixGrants(t, fx); len(g) != 0 {
+ t.Fatalf("grants %v left after the cancel", g)
+ }
+ if st := hubState(fx.srv.interactive, id); st != "ended" {
+ t.Fatalf("hub: %q, want ended", st)
+ }
+}
+
+func TestAdmissionReplacesAMarkerFromAnotherConsoleBoot(t *testing.T) {
+ fx := newIxFx(t, "code-ix-oldboot")
+ const old = "tty_bbbbbbbbbbbbbbbbbbbbbbbbbb"
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk",
+ Interactive: &provision.InteractiveState{ID: old, By: "bob@keymail.dev", Console: "old", PickupBy: time.Now().Add(time.Minute)}})
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ rec, _ := ixRecord(t, fx, ixHost)
+ if rec.Interactive == nil || rec.Interactive.ID == old || rec.Interactive.Console != fx.srv.bootID || rec.Interactive.By != "alice@keymail.dev" {
+ t.Fatalf("marker %+v, want this boot's session replacing %s", rec.Interactive, old)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+// ixAttempt is one client's go at a session, run on its own goroutine.
+type ixAttempt struct {
+ status int // the 409 before the upgrade, 0 once upgraded
+ msg string
+ waiting bool
+ end *interactive.End
+ ws *websocket.Conn
+ err error
+}
+
+func ixTry(t *testing.T, fx *interactiveFx, token string) ixAttempt {
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), token)
+ if err != nil {
+ // Refused before the upgrade: ask again for the body.
+ code, _, out := rawReq(t, http.MethodGet, fx.ixURL(ixHost), token, "")
+ var e struct{ Error string }
+ _ = json.Unmarshal([]byte(out), &e)
+ return ixAttempt{status: code, msg: e.Error}
+ }
+ if err := interactive.SendJSON(ws, interactive.KindOpen, ixOpenArgv()); err != nil {
+ return ixAttempt{err: err}
+ }
+ state, end, err := ixNext(ws)
+ return ixAttempt{waiting: state == interactive.StateWaiting, end: end, ws: ws, err: err}
+}
+
+func TestTwoSessionsRaceOneAdmission(t *testing.T) {
+ busy := func(by string) string { return ixHost + " already has an interactive session open, started by " + by }
+ who := map[int]string{0: "alice@keymail.dev", 1: "paul@keymail.dev"}
+ check := func(t *testing.T, res [2]ixAttempt) {
+ t.Helper()
+ won := -1
+ for i, r := range res {
+ if r.err != nil {
+ t.Fatalf("client %d: %v", i, r.err)
+ }
+ if r.waiting {
+ if won >= 0 {
+ t.Fatalf("both clients are waiting")
+ }
+ won = i
+ }
+ }
+ if won < 0 {
+ t.Fatalf("no client is waiting: %+v", res)
+ }
+ lost := res[1-won]
+ switch {
+ case lost.status == http.StatusConflict && lost.msg == busy(who[won]):
+ case lost.end != nil && lost.end.Reason == interactive.EndRefused && lost.end.Refused == interactive.RefusedBusy && lost.end.Detail == busy(who[won]):
+ default:
+ t.Fatalf("the loser got %+v, want 409 or End refused %q", lost, busy(who[won]))
+ }
+ }
+ run := func(t *testing.T, fx *interactiveFx) [2]ixAttempt {
+ var res [2]ixAttempt
+ var wg sync.WaitGroup
+ for i, tok := range []string{fx.alice, fx.owner} {
+ wg.Add(1)
+ go func() { defer wg.Done(); res[i] = ixTry(t, fx, tok) }()
+ }
+ wg.Wait()
+ return res
+ }
+ t.Run("at once", func(t *testing.T) {
+ fx := newIxFx(t, "code-ix-race")
+ check(t, run(t, fx))
+ if evs := ixEvents(t, fx, "interactive-start"); len(evs) != 1 {
+ t.Fatalf("%d interactive-start rows, want 1", len(evs))
+ }
+ })
+ t.Run("both past the door", func(t *testing.T) {
+ // Both pass the checks before either CAS: the CAS decides.
+ fx := newIxFx(t, "code-ix-race-cas")
+ var arrived sync.WaitGroup
+ arrived.Add(2)
+ fx.srv.interactive.afterChecks = func() { arrived.Done(); arrived.Wait() }
+ res := run(t, fx)
+ check(t, res)
+ if res[0].status != 0 || res[1].status != 0 {
+ t.Fatalf("a client was refused before the upgrade: %+v", res)
+ }
+ if g := ixGrants(t, fx); len(g) != 1 {
+ t.Fatalf("grants %v, want the winner's only", g)
+ }
+ })
+}
+
+// TestAdmissionHoldsItsReservationUntilRegistered is finding 10: A's id is
+// reserved in the hub before its record CAS, so from the moment the CAS
+// lands every other admission on this console finds the marker live.
+func TestAdmissionHoldsItsReservationUntilRegistered(t *testing.T) {
+ fx := newIxFx(t, "code-ix-reserve")
+ h := fx.srv.interactive
+ // B arrives first and is held just past its door checks, which see no
+ // marker.
+ var checks atomic.Int32
+ bChecked, bGo := make(chan struct{}), make(chan struct{})
+ h.afterChecks = func() {
+ if checks.Add(1) == 1 {
+ close(bChecked)
+ <-bGo
+ }
+ }
+ aAdmitted, aGo := make(chan struct{}), make(chan struct{})
+ h.afterAdmit = func(string) {
+ close(aAdmitted)
+ <-aGo
+ }
+ var b ixAttempt
+ bDone := make(chan struct{})
+ go func() { defer close(bDone); b = ixTry(t, fx, fx.owner) }()
+ waitForSignal(t, bChecked, "B's door checks")
+
+ // A passes the door and lands its CAS, then is held before activate.
+ var a ixAttempt
+ aDone := make(chan struct{})
+ go func() { defer close(aDone); a = ixTry(t, fx, fx.alice) }()
+ waitForSignal(t, aAdmitted, "A's record CAS")
+ rec, _ := ixRecord(t, fx, ixHost)
+ if rec.Interactive == nil || hubState(h, rec.Interactive.ID) != "reserved" {
+ t.Fatalf("marker %+v, hub %q: want A's id reserved", rec.Interactive, hubState(h, rec.Interactive.ID))
+ }
+ aID := rec.Interactive.ID
+
+ // (a) C, a fresh request now: refused at the door, naming A's caller.
+ busy := ixHost + " already has an interactive session open, started by alice@keymail.dev"
+ snap := ixSnapshot(t, fx, ixHost)
+ code, _, out := ixGet(t, fx, ixHost, fx.owner)
+ if code != http.StatusConflict || interactiveError(t, out) != busy {
+ t.Fatalf("(a) %d %s, want 409 %q", code, out, busy)
+ }
+ if raw, _, _ := fx.rel.Get(context.Background(), provision.RecordKey(fx.acct, "shop", ixHost)); string(raw) != string(snap.record) {
+ t.Fatal("(a) the refused request changed the record")
+ }
+
+ // (b) B goes on: its own CAS finds A's marker live.
+ close(bGo)
+ <-bDone
+ if b.err != nil || b.end == nil || b.end.Reason != interactive.EndRefused || b.end.Detail != busy {
+ t.Fatalf("(b) B got %+v, want End refused %q", b, busy)
+ }
+
+ close(aGo)
+ <-aDone
+ if a.err != nil || !a.waiting {
+ t.Fatalf("A got %+v, want waiting", a)
+ }
+ rec, _ = ixRecord(t, fx, ixHost)
+ if rec.Interactive == nil || rec.Interactive.ID != aID {
+ t.Fatalf("marker %+v, want A's %s", rec.Interactive, aID)
+ }
+ if evs := ixEvents(t, fx, "interactive-start"); len(evs) != 1 {
+ t.Fatalf("%d interactive-start rows, want 1", len(evs))
+ }
+ if g := ixGrants(t, fx); len(g) != 1 || g[0] != interactive.GrantKey(fx.acct, "shop", aID) {
+ t.Fatalf("grants %v, want A's only", g)
+ }
+ if hubCount(h) != 1 || hubState(h, aID) != "active" {
+ t.Fatalf("hub holds %d, A is %q", hubCount(h), hubState(h, aID))
+ }
+ a.ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestAFailedAdmissionReleasesItsReservation(t *testing.T) {
+ fx := newIxFx(t, "code-ix-failed")
+ ws, err := ixDial(t, fx.ts.URL, fx.ixURL(ixHost), fx.alice)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The door's checks passed; a move begins before the admission.
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk", Move: &provision.MoveState{ID: "mv_1", To: "ie"}})
+ var reservedID atomic.Value
+ fx.srv.interactive.afterReserve = func(id string) { reservedID.Store(id) }
+ snap := ixSnapshot(t, fx, ixHost)
+ ixSendOpen(t, ws, ixOpenArgv())
+ if e := ixWantEnd(t, ws); e.Reason != interactive.EndRefused || e.Detail != runMovingMsg(ixHost) {
+ t.Fatalf("end %+v, want refused %q", e, runMovingMsg(ixHost))
+ }
+ ixNothingWritten(t, fx, ixHost, snap)
+ reserved, _ := reservedID.Load().(string)
+ if reserved == "" || hubState(fx.srv.interactive, reserved) != "" || hubCount(fx.srv.interactive) != 0 {
+ t.Fatalf("the hub still holds %q (%q)", reserved, hubState(fx.srv.interactive, reserved))
+ }
+ ixPutRecord(t, fx, provision.Record{Host: ixHost, Channel: "stable", Region: "uk"})
+ ws = ixStart(t, fx, fx.alice, ixOpenArgv())
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestTheSessionOutlivesTheServersReadTimeout(t *testing.T) {
+ fx := newIxFx(t, "code-ix-readtimeout")
+ // The Open is awaited for 400 ms, and the session then idles past both
+ // that and the server's ReadTimeout.
+ fx.srv.interactive.openWaitFor = 400 * time.Millisecond
+ hs := NewHTTPServer(fx.srv)
+ hs.ReadTimeout = 200 * time.Millisecond
+ ts := httptest.NewUnstartedServer(fx.srv)
+ ts.Config = hs
+ ts.Start()
+ t.Cleanup(ts.Close)
+ u := ts.URL + "/api/cli/apps/" + fx.acct + "/shop/instances/" + ixHost + "/interactive"
+ ws, err := ixDial(t, ts.URL, u, fx.alice)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The Open comes after the server's read deadline would have passed.
+ time.Sleep(300 * time.Millisecond)
+ ixSendOpen(t, ws, ixOpenArgv())
+ ixWantWaiting(t, ws)
+ time.Sleep(600 * time.Millisecond)
+ if err := interactive.Send(ws, interactive.KindAlive, nil); err != nil {
+ t.Fatal(err)
+ }
+ kind, _, err := ixRecv(ws)
+ if err != nil || kind != interactive.KindAlive {
+ t.Fatalf("after 600 ms idle: %q %v, want a keepalive back", kind, err)
+ }
+ if evs := ixEvents(t, fx, "interactive-end"); len(evs) != 0 {
+ t.Fatalf("the session ended: %+v", evs)
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
+
+func TestPerfRingSkipsTheSessionDoor(t *testing.T) {
+ for _, c := range []struct {
+ method, path string
+ skip bool
+ }{
+ {http.MethodGet, "/api/cli/apps/bah/shop/instances/shop.example.com/interactive", true},
+ {http.MethodGet, "/api/box/interactive/tty_aaaaaaaaaaaaaaaaaaaaaaaaaa", true},
+ {http.MethodPut, "/api/cli/apps/bah/shop/interactive", false},
+ {http.MethodPut, "/api/cli/apps/bah/shop/instances/shop.example.com/interactive", false},
+ {http.MethodGet, "/api/cli/apps/bah/shop/instances/shop.example.com/runs", false},
+ {http.MethodGet, "/healthz", true},
+ } {
+ if got := consolePerfSkip(httptest.NewRequest(c.method, c.path, nil)); got != c.skip {
+ t.Errorf("%s %s: skip %v, want %v", c.method, c.path, got, c.skip)
+ }
+ }
+}
+
+// lostRecordPut lands the first conditional Put of a record carrying an
+// interactive marker, then answers it as a lost race: S3's answer to a PUT
+// the SDK retried after its first attempt had landed.
+type lostRecordPut struct {
+ release.Store
+ key string
+ lost atomic.Bool
+}
+
+func (l *lostRecordPut) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := l.Store.Put(ctx, key, body, ifMatch)
+ if err == nil && key == l.key && ifMatch != "" && strings.Contains(string(body), `"interactive"`) && l.lost.CompareAndSwap(false, true) {
+ return "", fmt.Errorf("the response was lost: %w", release.ErrCASConflict)
+ }
+ return etag, err
+}
+
+// TestAdmissionLandsThroughALostResponse: updateRecord's retry reads the
+// marker this admission already wrote. Its id is reserved, so the marker is
+// live, and the refusal names the admission's own id: that is the
+// admission, not a busy instance.
+func TestAdmissionLandsThroughALostResponse(t *testing.T) {
+ var lost *lostRecordPut
+ fx := newInteractiveFxWith(t, 7, "code-ix-lost", consoleFixtureOptions{WithKey: true, WrapReleases: func(s release.Store) release.Store {
+ lost = &lostRecordPut{Store: s, key: provision.RecordKey("bah", "shop", ixHost)}
+ return lost
+ }})
+ ixWorld(t, fx)
+ ws := ixStart(t, fx, fx.alice, ixOpenArgv())
+ if !lost.lost.Load() {
+ t.Fatal("the record write's response was never lost: the test proves nothing")
+ }
+ rec, _ := ixRecord(t, fx, ixHost)
+ if rec.Interactive == nil || hubState(fx.srv.interactive, rec.Interactive.ID) != "active" {
+ t.Fatalf("marker %+v is not the active session", rec.Interactive)
+ }
+ if g := ixGrants(t, fx); len(g) != 1 || g[0] != interactive.GrantKey(fx.acct, "shop", rec.Interactive.ID) {
+ t.Fatalf("grants %v", g)
+ }
+ if evs := ixEvents(t, fx, "interactive-start"); len(evs) != 1 {
+ t.Fatalf("%d interactive-start rows", len(evs))
+ }
+ ws.Close()
+ ixWaitEvents(t, fx, "interactive-end", 1)
+}
diff --git a/internal/console/apiinteractivesetting_test.go b/internal/console/apiinteractivesetting_test.go
index ee6fa043e..d12e11919 100644
--- a/internal/console/apiinteractivesetting_test.go
+++ b/internal/console/apiinteractivesetting_test.go
@@ -27,7 +27,13 @@ type interactiveFx struct {
func newInteractiveFx(t *testing.T, acctID int64, code string) *interactiveFx {
t.Helper()
- fx := newConsoleFixture(t)
+ return newInteractiveFxWith(t, acctID, code, consoleFixtureOptions{WithKey: true})
+}
+
+// newInteractiveFxWith is newInteractiveFx on the console o describes.
+func newInteractiveFxWith(t *testing.T, acctID int64, code string, o consoleFixtureOptions) *interactiveFx {
+ t.Helper()
+ fx := newConsoleFixtureWith(t, o)
now := time.Now()
sqid := domains.Sqid(acctID)
if err := fx.st.CreateAccount(acctID, sqid, "Shop", "paul@keymail.dev", now); err != nil {
diff --git a/internal/console/apiruns.go b/internal/console/apiruns.go
index 2b797609c..6904330cd 100644
--- a/internal/console/apiruns.go
+++ b/internal/console/apiruns.go
@@ -270,6 +270,21 @@ func runMetaRefusalCode(msg string) string {
// on a customer fleet is still refused, as every fleet record is, until
// runs reach fleet boxes through the console's door (Task 16).
func runClassRefusal(rec provision.Record) string {
+ if msg := instanceClassRefusal(rec); msg != "" {
+ return msg
+ }
+ if fleet, ok := registry.FleetPlacement(rec.Region); ok {
+ return fmt.Sprintf("%s runs on your fleet %s. carlos run works on platform boxes only", rec.Host, fleet)
+ }
+ return ""
+}
+
+// instanceClassRefusal is every arm of runClassRefusal but the fleet one
+// (rootfs apps Plan 6 Task 10, D4): whether the platform runs a process of
+// the record's own at all. An interactive session is admitted on a fleet
+// box, so the session door asks only this; a run still asks the fleet arm
+// too, until Task 16.
+func instanceClassRefusal(rec provision.Record) string {
switch {
case rec.Kind != "" && rec.Kind != "instance":
return fmt.Sprintf("%s is a %s route. carlos run works on instances", rec.Host, rec.Kind)
@@ -280,9 +295,6 @@ func runClassRefusal(rec provision.Record) string {
case rec.Pool != "":
return fmt.Sprintf("%s is a pooled instance. carlos run works on instances with a process of their own", rec.Host)
}
- if fleet, ok := registry.FleetPlacement(rec.Region); ok {
- return fmt.Sprintf("%s runs on your fleet %s. carlos run works on platform boxes only", rec.Host, fleet)
- }
return ""
}
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 5dcb8deec..232eae140 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -791,6 +791,12 @@ func (s *Server) registerCLIRoutes() {
s.cliRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}/cancel", svcrole.Exactly(svcrole.Run), s.handleAPIRunCancel)
s.cliRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}/expire", svcrole.Exactly(svcrole.Run), s.handleAPIRunExpire)
s.cliRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/runs/{id}/ack", svcrole.Exactly(svcrole.Run), s.handleAPIRunAck)
+ // The interactive session door (rootfs apps spec §5.10, apiinteractive.go):
+ // a WebSocket for `carlos run -it` and `carlos console`. The ZERO Set: a
+ // session is a live shell into production data, so no credential reaches
+ // it, the run role included; the handler answers anything but a person
+ // with the byte-identical 404.
+ s.cliRoute("GET /api/cli/apps/{account}/{app}/instances/{host}/interactive", svcrole.Set{}, s.handleAPIInteractive)
// `carlos instances retry <host>` (apiretry.go): the operate family's, as
// restart is. The {host} wildcard and the 404 are the instance family's.
s.cliScopedRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/retry", svcrole.Allow(svcrole.Operate), scopeHost, s.handleAPIInstanceRetry)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index c38d66586..40ebee291 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1648,6 +1648,20 @@ var claimFixtures = map[string]claimFixture{
status: http.StatusConflict,
msg: claimRunUnsupportedMsg,
}},
+ // The interactive session door (apiinteractive.go): refused on a
+ // host-claim console after its caller gates and before it reads
+ // anything. The world enrolls only kass and titogo, so the setup
+ // enrolls shop.
+ "route GET /api/cli/apps/{account}/{app}/instances/{host}/interactive": {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/cli/apps/bab/shop/instances/shop.example.com/interactive", ""),
+ 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/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index cb7beb8a6..fa3407ae6 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -101,6 +101,8 @@ const claimOfflineMoveUnsupportedMsg = "offline moves are not available while ho
var claimUnsupported = map[string]string{
claimRunUnsupportedMsg: "carlos run launches a cmd unit that the claim's isolated root protocol has no reservation for (#250); " +
"every run route refuses before it reads or writes anything",
+ claimInteractiveUnsupportedMsg: "a session launches a tty unit the claim's isolated root protocol has no reservation for (#250); " +
+ "every session route refuses before it reads anything",
claimHostResolveUnsupportedMsg: "host-loss declaration/readmission changes claim roots; the existing service has no scoped lifecycle grant in this slice",
claimMoveUnsupportedMsg: "instance move request, cut and abort rewrite the record's move journal, " +
"which only the unbuilt host-claim Moves protocol may do under its own operation",
diff --git a/internal/console/interactivehub.go b/internal/console/interactivehub.go
new file mode 100644
index 000000000..c8f745bac
--- /dev/null
+++ b/internal/console/interactivehub.go
@@ -0,0 +1,216 @@
+package console
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "sync"
+ "time"
+
+ "golang.org/x/net/websocket"
+
+ "github.com/carlosframework/platform/internal/interactive"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// The console's interactive sessions (rootfs apps spec §5.10, Plan 6 Tasks
+// 10 and 11): what this console process holds of each session it admitted.
+// Nothing here is persisted. A session lives on its CLI's WebSocket and, once
+// a box attaches, on the box's (Task 11); the record's marker names the
+// console process that admitted it (InteractiveState.Console, this process's
+// bootID), so a marker of another boot is dead by that field alone, and a
+// marker of this boot is live only while the hub holds its id.
+
+// interactiveHub is the hub. Its id lifecycle:
+//
+// reserve -> (record CAS) -> activate -> end
+// \-> release (the admission failed: no session started)
+//
+// end moves an id to ended, or to endPending when the gate refused its end
+// step (the sweep finishes it, then it is ended). An id is live, for
+// another admission's CAS, while it is reserved or active; never once
+// ended or pending.
+type interactiveHub struct {
+ mu sync.Mutex
+ byID map[string]*hubSession // reserved or active
+ byHost map[string]string // host -> its active session's id
+ ended map[string]bool
+ // endPending is every ended session whose end step the gate refused
+ // (draining): the sweep makes its writes with this End, then ends it.
+ endPending map[string]interactive.End
+ // pendingSess is the session of each endPending id, for those writes.
+ pendingSess map[string]*hubSession
+
+ // sessions counts the session goroutines running, so a test (or a
+ // shutdown) can wait for every end's writes.
+ sessions sync.WaitGroup
+
+ // Test seams, nil or zero in production.
+ //
+ // afterChecks runs once a request has passed every refusal before the
+ // upgrade, just before it upgrades. afterReserve runs once an id is
+ // reserved. afterAdmit runs after the record CAS lands, just before
+ // activate. pickupWindow and openWait, when not 0, replace
+ // interactive.PickupWindow and interactive.OpenWait.
+ afterChecks func()
+ afterReserve func(id string)
+ afterAdmit func(id string)
+ pickupWindow time.Duration
+ openWaitFor time.Duration
+}
+
+// hubSession is one session this console admitted.
+type hubSession struct {
+ id, acct, app, host, incarnation, fleet, by string
+ // account is the session's account, for its audit rows.
+ account *Account
+ tokenHash [32]byte
+ // open is the Open exactly as the CLI sent it (rev 2: never rewritten,
+ // Process kept), which is what the box gets.
+ open interactive.Open
+ // argv is the resolved command, for the audit row only: open.Argv, or
+ // for the console process the command its manifest declares.
+ argv []string
+ 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
+ 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
+}
+
+// boxConn is a box's attached connection (Task 11's door builds it).
+type boxConn struct {
+ ws *websocket.Conn
+ box string
+}
+
+func newInteractiveHub() *interactiveHub {
+ return &interactiveHub{
+ byID: map[string]*hubSession{},
+ byHost: map[string]string{},
+ ended: map[string]bool{},
+ endPending: map[string]interactive.End{},
+ pendingSess: map[string]*hubSession{},
+ }
+}
+
+// newConsoleBootID mints this process's boot id: 16 random bytes, hex.
+func newConsoleBootID() string {
+ var b [16]byte
+ if _, err := rand.Read(b[:]); err != nil {
+ panic("console: no random source for the boot id: " + err.Error())
+ }
+ return hex.EncodeToString(b[:])
+}
+
+// window is the pickup window this hub gives a session.
+func (h *interactiveHub) window() time.Duration {
+ if h.pickupWindow > 0 {
+ return h.pickupWindow
+ }
+ return interactive.PickupWindow
+}
+
+// openWait is how long this hub waits for a CLI's Open frame.
+func (h *interactiveHub) openWait() time.Duration {
+ if h.openWaitFor > 0 {
+ return h.openWaitFor
+ }
+ return interactive.OpenWait
+}
+
+// live reports whether st is a session this console process still holds:
+// admitted by this boot, and its id reserved or active here (finding 10).
+// An id the hub has ended, or holds in endPending, is not live.
+func (h *interactiveHub) live(st provision.InteractiveState, boot string) bool {
+ if st.Console != boot {
+ return false
+ }
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ _, ok := h.byID[st.ID]
+ return ok
+}
+
+// reserve holds sess's id, not yet active: before the grant and the
+// admission, so the marker is live from the moment its CAS lands.
+func (h *interactiveHub) reserve(sess *hubSession) {
+ h.mu.Lock()
+ sess.active = false
+ h.byID[sess.id] = sess
+ h.mu.Unlock()
+ if h.afterReserve != nil {
+ h.afterReserve(sess.id)
+ }
+}
+
+// activate makes a reserved id active. It is false for an id that was never
+// reserved (or was released or ended since).
+func (h *interactiveHub) activate(id string) bool {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ sess, ok := h.byID[id]
+ if !ok {
+ return false
+ }
+ sess.active = true
+ h.byHost[sess.host] = id
+ return true
+}
+
+// release drops a reserved id that never became active. No session
+// started, so nothing is marked ended.
+func (h *interactiveHub) release(id string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if sess, ok := h.byID[id]; ok && !sess.active {
+ delete(h.byID, id)
+ }
+}
+
+// end takes id out of the live set and marks it ended. 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.
+func (h *interactiveHub) end(id string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if sess, ok := h.byID[id]; ok {
+ if h.byHost[sess.host] == id {
+ delete(h.byHost, sess.host)
+ }
+ delete(h.byID, id)
+ }
+ h.ended[id] = true
+}
+
+// pend records that the gate refused sess's end step: the sweep finishes it
+// with e.
+func (h *interactiveHub) pend(sess *hubSession, e interactive.End) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ delete(h.ended, sess.id)
+ h.endPending[sess.id] = e
+ h.pendingSess[sess.id] = sess
+}
+
+// pending is a snapshot of the endPending sessions and their Ends.
+func (h *interactiveHub) pending() map[*hubSession]interactive.End {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ out := make(map[*hubSession]interactive.End, len(h.endPending))
+ for id, e := range h.endPending {
+ out[h.pendingSess[id]] = e
+ }
+ return out
+}
+
+// finished marks an endPending id ended once the sweep made its writes.
+func (h *interactiveHub) finished(id string) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ delete(h.endPending, id)
+ delete(h.pendingSess, id)
+ h.ended[id] = true
+}
diff --git a/internal/console/lifetimes_cutover.go b/internal/console/lifetimes_cutover.go
index a815d9cf0..f4f345a3b 100644
--- a/internal/console/lifetimes_cutover.go
+++ b/internal/console/lifetimes_cutover.go
@@ -328,6 +328,43 @@ func detachUnit(ctx context.Context) *admittedUnit {
return u
}
+// endRequestUnit ends the unit serveAdmitted admitted for this request
+// (once-only, nil-safe): a long connection holds no unit past its upgrade,
+// so a session open for hours never holds a cutover's drain. The request's
+// context still carries the unit's judge, so nothing may read or write a
+// record under it afterwards; each later write is a lifetimesStep.
+func endRequestUnit(ctx context.Context) {
+ unitFrom(ctx).done()
+}
+
+// errLifetimesRefused is lifetimesStep's refusal: the gate would not admit
+// the step (it is draining, or the console is starting).
+var errLifetimesRefused = errors.New("console: the lifetimes gate refused this step")
+
+// lifetimesStepHook, when set, sees every admitted step before it runs,
+// with the context it runs under. A TEST SEAM.
+var lifetimesStepHook func(ctx context.Context, u *admittedUnit)
+
+// lifetimesStep runs one record step of a long connection as its own unit:
+// admitted with mutating, run under s.recordCtx(ctx, u) with the unit in
+// the context as a request's is, and ended when f returns. A refused
+// admission returns an error wrapping errLifetimesRefused (with the gate's
+// sentence) and does not call f. On a console the gate does not govern, f
+// runs as today. ctx must carry no unit or judge of its own: the step's
+// unit alone decides how its records are read.
+func (s *Server) lifetimesStep(ctx context.Context, mutating bool, f func(context.Context) error) error {
+ u, ok, why := s.lifetimesAdmit(ctx, mutating)
+ if !ok {
+ return fmt.Errorf("%w: %s", errLifetimesRefused, why)
+ }
+ defer u.done()
+ sctx := context.WithValue(s.recordCtx(ctx, u), admittedUnitKey{}, u)
+ if lifetimesStepHook != nil {
+ lifetimesStepHook(sctx, u)
+ }
+ return f(sctx)
+}
+
// 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.
diff --git a/internal/console/runsweep.go b/internal/console/runsweep.go
index 9bd9bde9b..a6fa0b7a1 100644
--- a/internal/console/runsweep.go
+++ b/internal/console/runsweep.go
@@ -83,6 +83,9 @@ func (s *Server) runSweepPass(ctx context.Context, now time.Time, housekeeping b
}
ctx, cancel := context.WithTimeout(ctx, runSweepTimeout)
defer cancel()
+ // Interactive sessions whose end the draining gate refused (rootfs
+ // apps Plan 6, PF-4): their writes, under this pass's unit.
+ s.finishPendingInteractiveEnds(ctx)
src, viewed := s.recordWalkStore(ctx, s.cfg.Releases)
recs, complete, err := provision.ListAllRecordsTolerantJudged(ctx, src, provision.JudgeFrom(ctx))
if err != nil {
diff --git a/internal/console/server.go b/internal/console/server.go
index 016db3b57..39c6b6567 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -48,6 +48,7 @@ import (
"github.com/carlosframework/platform/internal/hostclaim"
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/infraview"
+ "github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/mail"
"github.com/carlosframework/platform/internal/metrics"
@@ -1005,6 +1006,12 @@ type Server struct {
judge *provision.LifetimeJudge
cutover *cutoverGate
appsMaterialized atomic.Bool
+ // bootID names this console process in every interactive-session marker
+ // it admits (InteractiveState.Console): 16 random bytes, minted by
+ // NewServer, so a marker of an earlier process is dead by that field.
+ // interactive is the process's session hub (interactivehub.go).
+ bootID string
+ interactive *interactiveHub
// The console's move pass (movesrecovery.go): its clock (nil is
// time.Now; a TEST SEAM) and when each close was first seen due.
movesClock func() time.Time
@@ -1698,6 +1705,10 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
// deploy overlap are two writers, and they must be able to tell
// each other apart (relayops.go).
relayHolder: relayHolderID(),
+ // This process's interactive sessions (interactivehub.go), and the
+ // boot id their record markers carry.
+ bootID: newConsoleBootID(),
+ interactive: newInteractiveHub(),
scanQueue: objstore.NewQueueIndex(),
perf: cfg.Perf,
billing: newBillingRuntime(cfg.Billing),
@@ -2142,9 +2153,23 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// consolePerfSkip leaves /healthz and the /static/ files unmeasured: a probe
// every few seconds, or a page's worth of stylesheets on every view, would
-// crowd the console's real pages out of the ring.
+// crowd the console's real pages out of the ring. The session doors are
+// skipped too (PF-23): each request is a WebSocket open for up to 6 hours,
+// not a page. The CLI's is a GET of …/instances/{host}/interactive (the
+// setting door, PUT …/{app}/interactive, is still measured); the box's are
+// under interactive.AttachPathPrefix.
func consolePerfSkip(r *http.Request) bool {
- return r.URL.Path == "/healthz" || strings.HasPrefix(r.URL.Path, "/static/")
+ p := r.URL.Path
+ switch {
+ case p == "/healthz", strings.HasPrefix(p, "/static/"):
+ return true
+ case strings.HasPrefix(p, interactive.AttachPathPrefix):
+ return true
+ case r.Method == http.MethodGet && strings.HasPrefix(p, "/api/cli/apps/") &&
+ strings.HasSuffix(p, "/interactive") && strings.Contains(p, "/instances/"):
+ return true
+ }
+ return false
}
// PerfGroups summarises the requests the console has measured, by route
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 6b39bda5c..1b8ee50ab 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -263,6 +263,11 @@ var closedDoors = []string{
// instances. A credential the app holds must not open that for itself;
// turning it on is an account owner's act, in the handler.
"PUT /api/cli/apps/{account}/{app}/interactive",
+ // The interactive session door (rootfs apps spec §5.10): a live shell
+ // into production data on one instance. People only, the run role
+ // included in the refusal: a credential the app holds must never open a
+ // terminal on its own instances.
+ "GET /api/cli/apps/{account}/{app}/instances/{host}/interactive",
// The app policy (instance sizes and egress spec §6): operator-only, both
// the read and the write. Its egress allow opens private addresses to an
// app's instances, so a credential the app holds must never widen it, and
@@ -1142,8 +1147,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
}
seen++
}
- if seen != len(closedDoors) || seen != 74 {
- t.Errorf("walked %d closed doors, want all %d (and 74 today: three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
+ if seen != len(closedDoors) || seen != 75 {
+ t.Errorf("walked %d closed doors, want all %d (and 75 today: three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, six fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 60e241907..ff8ce89d1 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -65,6 +65,7 @@ route GET /api/cli/apps/{account}/{app}/features
route GET /api/cli/apps/{account}/{app}/geo
route GET /api/cli/apps/{account}/{app}/instances
route GET /api/cli/apps/{account}/{app}/instances/{host}
+route GET /api/cli/apps/{account}/{app}/instances/{host}/interactive
route GET /api/cli/apps/{account}/{app}/instances/{host}/move
route GET /api/cli/apps/{account}/{app}/instances/{host}/move/offline
route GET /api/cli/apps/{account}/{app}/instances/{host}/rate-limit
diff --git a/internal/provision/rootfs_apps_6_census_test.go b/internal/provision/rootfs_apps_6_census_test.go
index 8ea25cdb8..988a4c38d 100644
--- a/internal/provision/rootfs_apps_6_census_test.go
+++ b/internal/provision/rootfs_apps_6_census_test.go
@@ -26,11 +26,23 @@ package provision
// cleanUp (true only for the incarnation refusal before RunCmd: the run
// directory otherwise waits for CmdSpec.AfterSettled, INV-2); the
// result write and the one SetRecordRun (runFinishOurs) are unchanged.
+// - Task 10: the console's session door (internal/console/apiinteractive.go).
+// Server.admitSession is a record-writer: its one record write is
+// SetRecordInteractive(InteractiveAdmit), under the step's unit (judged
+// when lifetimes are on). Server.endWrites is a record-writer: one
+// SetRecordInteractive(InteractiveClear). Server.putGrant is the grant's
+// Put to apps/<acct>/<app>/interactive/<id>.json, not a record:
+// nonrecord. Server.registerCLIRoutes registers GET
+// …/instances/{host}/interactive beside the run doors (the same record
+// literals, no record touched); NewServer mints bootID and the hub (no
+// record touched); consolePerfSkip names the session door's path
+// ("/instances/" is a URL segment, not a record key).
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", "93f090dcda4e5364f3cff993cebfc1385550039316a59aacaba72ba933ba14b3"},
+ {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "ede525ff628efe3f32e655448c3b1633975fd7312205e7418c60c8ed5be2894e"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "4ef5168b1506ffcc8e0a7769ac3b188925bc1b79603d632575972e7f1548f17d"},
{"internal/instanceexec/exit.go", "parseExitArgs", "key-site", "lit:instances", "be3a7828e292b4977c42f21d8283fc9d185505ced9ffdf2543267a88bc8033a9"},
{"internal/host/runexec.go", "runsWorker.finish", "record-writer", "key:SetRecordRun", "f586bc77d175652d19bed1e7cceb7ecad523f7a1125bc798c19109e0a4f55ee2"},
}
@@ -51,6 +63,10 @@ func rootfsApps6WriteCensusInventory() []censusEntry {
added := []censusEntry{
{"internal/provision/interactive.go", "SetRecordInteractive", "record-writer", "key:SetRecordInteractive,key:updateRecord", "f2f8c0ad8647cc048a0be0fa3edc051ddd8e3157eba038123f9e5bab79f4530e"},
{"internal/appconfig/interactive.go", "claimRawSetInteractive", "nonrecord", "sel:Put", "d4c768601d1b9bdb44c0fd0c2c6f058c18c1434856e357f00628d2f600ce039b"},
+ {"internal/console/apiinteractive.go", "Server.admitSession", "record-writer", "key:SetRecordInteractive", "232eea1eddee8d6abc87ed9462c148ee70cb1ed64e7c123106c27678abc7d8ca"},
+ {"internal/console/apiinteractive.go", "Server.endWrites", "record-writer", "key:SetRecordInteractive", "fd4136620a996f3aff3beb0dab03a84056d80694c123cdc839c5ecab7a4e1731"},
+ {"internal/console/apiinteractive.go", "Server.putGrant", "nonrecord", "sel:Put", "22a18ef45051da8cfb8a6a62ad8891afd28e3bf71cc26a541639cd2a1dc0a1ff"},
+ {"internal/console/server.go", "consolePerfSkip", "key-site", "lit:instances", "d4b65473d3702b49d79a799d46f078e4491b6e86a59a101dd4c1ce4d50f698e7"},
}
for _, a := range added {
for _, e := range entries {