console: tests that a gone client leaves the connection queue
Two tests over the signed-in doors this branch threads (the landing, the app list, an app page, its instances list and GET /api/cli/apps): - TestCancelledRequestLeavesTheConnectionQueue holds the store's one connection, sends a door, waits until the pool counts it queued (Stats().WaitCount), and cancels the request. The request must return while the connection is still held, signed out and with nothing of the page served. On the code before this branch every door kept its place until the connection came free. - TestSignedInPagesQueryUnderTheRequestContext wraps the store's handle and fails any query a door makes with no context, or under a context that is not the request's. Plans are on and the fixture account is not exempt, so the plan banner's reads are checked too. The second test found handleAPIApps listing accounts and apps through the context-free wrappers; it now uses AccountsForContext and AppsInContext.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+253
−2
internal/console/apicli.go+2 −2internal/console/requestctx_test.go+251 −0
CI failed — run details
diff --git a/internal/console/apicli.go b/internal/console/apicli.go| index 9e730a0a5..f42fcbb1a 100644 |
| --- a/internal/console/apicli.go |
| +++ b/internal/console/apicli.go |
| @@ -767,7 +767,7 @@ func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) { |
| } |
| case PrincipalUser: |
| var err error |
| - accts, err = s.store.AccountsFor(p.Address) |
| + accts, err = s.store.AccountsForContext(r.Context(), p.Address) |
| if err != nil { |
| log.Printf("console: api apps for %s: %v", p.Address, err) |
| jsonError(w, http.StatusInternalServerError, "could not load accounts") |
| @@ -779,7 +779,7 @@ func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) { |
| } |
| out := make([]map[string]any, 0, len(accts)) |
| for _, a := range accts { |
| - apps, err := s.store.AppsIn(a.ID) |
| + apps, err := s.store.AppsInContext(r.Context(), a.ID) |
| if err != nil { |
| log.Printf("console: api apps in %s: %v", a.Sqid, err) |
| jsonError(w, http.StatusInternalServerError, "could not load apps") |
diff --git a/internal/console/requestctx_test.go b/internal/console/requestctx_test.go| new file mode 100644 |
| index 000000000..5cd344a37 |
| --- /dev/null |
| +++ b/internal/console/requestctx_test.go |
| @@ -0,0 +1,251 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "net/http" |
| + "net/http/httptest" |
| + "runtime" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// TestCancelledRequestLeavesTheConnectionQueue: the console store has one |
| +// SQLite connection, so a query with no context waits for it however long |
| +// the client that asked has been gone. Each signed-in door below is sent |
| +// while something else holds that connection; once the request is queued |
| +// for it, the client goes away. The request must give up its place and |
| +// return while the connection is still held, without the page's queries |
| +// running. |
| +// |
| +// The wait is on the pool's own counter (the request is queued once |
| +// WaitCount moves) and on the handler returning; the timer only bounds a |
| +// failure. |
| +func TestCancelledRequestLeavesTheConnectionQueue(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + const person = "paul@keymail.dev" |
| + session, err := fx.st.CreateSession(person, "", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token := mintHostClaimToken(t, fx.st, person) |
| + cookie := func(r *http.Request) { r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session}) } |
| + bearer := func(r *http.Request) { r.Header.Set("Authorization", "Bearer "+token) } |
| + for _, c := range []struct { |
| + name, path string |
| + auth func(*http.Request) |
| + }{ |
| + {"app list", fx.path("/"), cookie}, |
| + {"app page", fx.path("/apps/kass"), cookie}, |
| + {"instances", fx.path("/apps/kass/instances"), cookie}, |
| + {"cli door", "/api/cli/apps", bearer}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + // The door answers this caller when nothing is in its way. |
| + req := httptest.NewRequest(http.MethodGet, c.path, nil) |
| + c.auth(req) |
| + rec := httptest.NewRecorder() |
| + fx.srv.ServeHTTP(rec, req) |
| + if rec.Code != http.StatusOK { |
| + t.Fatalf("GET %s = %d with the connection free, want 200:\n%s", c.path, rec.Code, rec.Body) |
| + } |
| + |
| + held, err := fx.st.rawPool.Conn(context.Background()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + released := false |
| + release := func() { |
| + if !released { |
| + released = true |
| + held.Close() |
| + } |
| + } |
| + defer release() |
| + |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + req = httptest.NewRequest(http.MethodGet, c.path, nil).WithContext(ctx) |
| + c.auth(req) |
| + rec = httptest.NewRecorder() |
| + waits := fx.st.rawPool.Stats().WaitCount |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + fx.srv.ServeHTTP(rec, req) |
| + }() |
| + bound := time.After(10 * time.Second) |
| + for fx.st.rawPool.Stats().WaitCount == waits { |
| + select { |
| + case <-done: |
| + t.Fatalf("GET %s returned %d before it queued for the connection", c.path, rec.Code) |
| + case <-bound: |
| + t.Fatalf("GET %s never queued for the connection", c.path) |
| + default: |
| + runtime.Gosched() |
| + } |
| + } |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-bound: |
| + release() |
| + <-done |
| + t.Fatalf("GET %s kept its place behind the held connection after the client went away", c.path) |
| + } |
| + if released { |
| + t.Fatal("the held connection was let go before the request returned") |
| + } |
| + // It gave up at the first query, the session or bearer |
| + // lookup: the caller reads as signed out, and nothing of the |
| + // page was served. |
| + if rec.Code == http.StatusOK { |
| + t.Fatalf("GET %s = 200 after the client went away, want the signed-out answer", c.path) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestSignedInPagesQueryUnderTheRequestContext runs the doors above with |
| +// the store's handle wrapped, and fails any query a door makes with no |
| +// context, or under one that is not the request's (context.Background() |
| +// where the request's was in reach). Plans are on and the fixture account |
| +// is not exempt, so the plan banner's reads run too. |
| +func TestSignedInPagesQueryUnderTheRequestContext(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.PlanCatalog = examplePlanCatalog(t) |
| + fx.st.planExemptID = 0 |
| + const person = "paul@keymail.dev" |
| + session, err := fx.st.CreateSession(person, "", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token := mintHostClaimToken(t, fx.st, person) |
| + check := &requestCtxDB{sqlHandle: fx.st.db} |
| + fx.st.db = check |
| + t.Cleanup(func() { fx.st.db = check.sqlHandle }) |
| + for _, c := range []struct { |
| + name, path, auth string |
| + }{ |
| + {"landing", "/", session}, |
| + {"app list", fx.path("/"), session}, |
| + {"app page", fx.path("/apps/kass"), session}, |
| + {"instances", fx.path("/apps/kass/instances"), session}, |
| + {"cli door", "/api/cli/apps", "Bearer " + token}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + ctx := context.WithValue(context.Background(), requestCtxMark{}, c.path) |
| + req := httptest.NewRequest(http.MethodGet, c.path, nil).WithContext(ctx) |
| + if strings.HasPrefix(c.auth, "Bearer ") { |
| + req.Header.Set("Authorization", c.auth) |
| + } else { |
| + req.AddCookie(&http.Cookie{Name: sessionCookie, Value: c.auth}) |
| + } |
| + check.reset() |
| + rec := httptest.NewRecorder() |
| + fx.srv.ServeHTTP(rec, req) |
| + if rec.Code != http.StatusOK && rec.Code != http.StatusFound { |
| + t.Fatalf("GET %s = %d:\n%s", c.path, rec.Code, rec.Body) |
| + } |
| + queries, bad := check.result() |
| + if queries == 0 { |
| + t.Fatalf("GET %s made no queries through the store; the check saw nothing", c.path) |
| + } |
| + for _, b := range bad { |
| + t.Errorf("GET %s: %s", c.path, b) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// requestCtxMark marks a test request's context. |
| +type requestCtxMark struct{} |
| + |
| +// requestCtxDB is the store's handle with every call checked: a method |
| +// with no context, or a context without requestCtxMark, is recorded. |
| +type requestCtxDB struct { |
| + sqlHandle |
| + mu sync.Mutex |
| + queries int |
| + bad []string |
| +} |
| + |
| +func (d *requestCtxDB) reset() { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.queries, d.bad = 0, nil |
| +} |
| + |
| +func (d *requestCtxDB) result() (int, []string) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + return d.queries, append([]string(nil), d.bad...) |
| +} |
| + |
| +func (d *requestCtxDB) note(ctx context.Context, method, query string) { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + d.queries++ |
| + q := strings.Join(strings.Fields(query), " ") |
| + if len(q) > 90 { |
| + q = q[:90] + "..." |
| + } |
| + switch { |
| + case ctx == nil: |
| + d.bad = append(d.bad, method+" with no context: "+q) |
| + case ctx.Value(requestCtxMark{}) == nil: |
| + d.bad = append(d.bad, method+" under a context that is not the request's: "+q) |
| + } |
| +} |
| + |
| +func (d *requestCtxDB) Exec(query string, args ...any) (sql.Result, error) { |
| + d.note(nil, "Exec", query) |
| + return d.sqlHandle.Exec(query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { |
| + d.note(ctx, "ExecContext", query) |
| + return d.sqlHandle.ExecContext(ctx, query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) Query(query string, args ...any) (*sql.Rows, error) { |
| + d.note(nil, "Query", query) |
| + return d.sqlHandle.Query(query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { |
| + d.note(ctx, "QueryContext", query) |
| + return d.sqlHandle.QueryContext(ctx, query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) QueryRow(query string, args ...any) *sql.Row { |
| + d.note(nil, "QueryRow", query) |
| + return d.sqlHandle.QueryRow(query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { |
| + d.note(ctx, "QueryRowContext", query) |
| + return d.sqlHandle.QueryRowContext(ctx, query, args...) |
| +} |
| + |
| +func (d *requestCtxDB) Begin() (*sql.Tx, error) { |
| + d.note(nil, "Begin", "") |
| + return d.sqlHandle.Begin() |
| +} |
| + |
| +func (d *requestCtxDB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) { |
| + d.note(ctx, "BeginTx", "") |
| + return d.sqlHandle.BeginTx(ctx, opts) |
| +} |
| + |
| +func (d *requestCtxDB) Prepare(query string) (*sql.Stmt, error) { |
| + d.note(nil, "Prepare", query) |
| + return d.sqlHandle.Prepare(query) |
| +} |
| + |
| +func (d *requestCtxDB) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { |
| + d.note(ctx, "PrepareContext", query) |
| + return d.sqlHandle.PrepareContext(ctx, query) |
| +} |