fix: demo publish review round 1
Retry transient publication failures at durable stages and close demo mutation and hostname reservation gaps. Add restart, cancellation, placement, status and door regressions, and repair the affected guard inventories. P2 remains incomplete for post-promotion terminal errors and deadline settlement. First-publication rollback has no history target; the controller must define withdrawal or nonterminal settlement before this task can land. Details are in the local Task 7 Fix round 1 report.
internal/console/apidemo.go+14 −3internal/console/apiinstances.go+1 −1internal/console/apitemporary.go+1 −1internal/console/appregionset.go+3 −0internal/console/claim_invariant_test.go+4 −1internal/console/demo_domains.go+21 −0internal/console/demo_policy.go+2 −3internal/console/demo_publish.go+17 −4internal/console/demo_publish_test.go+1 −1internal/console/demo_review_test.go+434 −0internal/console/domainattach.go+3 −0internal/console/hostsused.go+3 −0internal/console/lifetimes_create.go+3 −0internal/console/server.go+1 −1internal/provision/demo_census_test.go+11 −2
Intent
<task-notification> <task-id>b2g06mf0f</task-id> <tool-use-id>toolu_01TVqYfNA3RgeHewF9wodnGJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/b2g06mf0f.output</output-file> <status>completed</status> <summary>Background command "Wait for gate repair run" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>br380hf6p</task-id> <tool-use-id>toolu_015C1aeo5xdwDnJ9HfcxoRRo</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/br380hf6p.output</output-file> <status>completed</status> <summary>Background command "Wait for gate repair" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 11.7 g CO₂e (1,439,155 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on agent-start-demo-1, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index cc2b359fe..c57b1e851 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -38,6 +38,7 @@ var demoCopy = map[string]string{ |
| "DEMO-BUILD-STARTING": "The demo is starting.", |
| "DEMO-BUILD-LIVE": "The demo is live.", |
| "DEMO-BUILD-FAILED": "The demo could not start. Submit another update with the same token.", |
| + "DEMO-COMPILE-FAILED": "The demo build failed. Submit another update with the same token.", |
| "DEMO-BUILD-TIMEOUT": "The demo did not become ready within 60 seconds. Submit another update with the same token.", |
| "DEMO-SOURCE": "Send a gzip tarball no larger than 5,000,000 bytes within 30 seconds.", |
| "DEMO-CLAIM-LATER": "Claiming is not available yet.", |
| @@ -509,7 +510,14 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Content-Type", "application/json") |
| diagnostics, truncated := demoResultDiagnosticStatus(row.Result) |
| response := map[string]any{"jobID": id, "status": state, "diagnostics": diagnostics, "diagnosticsTruncated": truncated} |
| - if row.State == "ready" || row.State == "published" || len(row.Result) > 0 { |
| + var stage string |
| + if err := s.store.db.QueryRowContext(r.Context(), `SELECT publish_stage FROM demo_jobs WHERE id=?`, id).Scan(&stage); err != nil { |
| + jsonError(w, http.StatusServiceUnavailable, demoCopy["DEMO-BUILD"]) |
| + return |
| + } |
| + publishedStage := strings.TrimPrefix(stage, "timeout:") |
| + shipped := publishedStage == "shipped" || publishedStage == "promoted" || publishedStage == "starting" |
| + if shipped { |
| response["version"] = demoVersion(row.Job) |
| } |
| switch state { |
| @@ -519,8 +527,11 @@ func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) { |
| response["message"] = demoCopy["DEMO-BUILD-LIVE"] |
| case "failed": |
| response["message"] = demoCopy["DEMO-BUILD-FAILED"] |
| - var stage string |
| - if err := s.store.db.QueryRowContext(r.Context(), `SELECT publish_stage FROM demo_jobs WHERE id=?`, id).Scan(&stage); err == nil && stage == "timeout" { |
| + var result demobuild.Result |
| + if json.Unmarshal(row.Result, &result) == nil && result.BinarySize == 0 { |
| + response["message"] = demoCopy["DEMO-COMPILE-FAILED"] |
| + } |
| + if stage == "timeout" || strings.HasPrefix(stage, "timeout:") { |
| response["message"] = demoCopy["DEMO-BUILD-TIMEOUT"] |
| } |
| } |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 10e2068de..8b2910860 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1664,7 +1664,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| "invalid host โ an instance host is one DNS label followed by ."+m.Domain) |
| return |
| } |
| - if s.demoDomainReserved(host) { |
| + if err := s.demoRecordReservation(r.Context(), provision.Record{Host: host}); err != nil { |
| jsonError(w, http.StatusConflict, demoCopy["DEMO-POLICY"]) |
| return |
| } |
diff --git a/internal/console/apitemporary.go b/internal/console/apitemporary.go| index 98c24aac7..2ffc05bb8 100644 |
| --- a/internal/console/apitemporary.go |
| +++ b/internal/console/apitemporary.go |
| @@ -5,7 +5,6 @@ import ( |
| "crypto/subtle" |
| "errors" |
| "fmt" |
| - "github.com/carlosframework/platform/internal/demo" |
| "log" |
| "net/http" |
| "net/url" |
| @@ -13,6 +12,7 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/apppolicy" |
| + "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
diff --git a/internal/console/appregionset.go b/internal/console/appregionset.go| index 7a82647a5..795291501 100644 |
| --- a/internal/console/appregionset.go |
| +++ b/internal/console/appregionset.go |
| @@ -259,6 +259,9 @@ func (s *Server) handleAPIAppRegionSet(w http.ResponseWriter, r *http.Request) { |
| // region it read, or not at all. via is appended to the audit line ("cli" |
| // or "" for the browser). |
| func (s *Server) setAppRegion(ctx context.Context, acct *Account, app string, found AppIncarnation, raw, addr, via string) (appRegionView, *doorRefusal) { |
| + if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| + return appRegionView{}, ref |
| + } |
| // A host-claim console gates every app-row write through a claim |
| // operation, and this one has none: refused before anything is read |
| // (host claims are shelved; claimRenameUnsupportedMsg is the precedent). |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 378f4f5b1..f6655379a 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -182,7 +182,10 @@ type claimWindow struct { |
| // every writer is reached. A new boundary method or gated table fails the |
| // coverage step until a door reaches it or a reason is written here. |
| var claimWriterReasons = map[string]string{ |
| - "bucket/PutFrom": "the only console streaming caller is geoippublish.go, which writes deployment GeoIP blobs, not app state; app-prefixed fallback writes are checked by Put and the streaming new-door witness", |
| + "sql/demo_apps": "anonymous demo admission refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "sql/demo_jobs": "anonymous demo build work refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "sql/demo_job_outbox": "anonymous demo dispatch refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| + "bucket/PutFrom": "the only console streaming caller is geoippublish.go, which writes deployment GeoIP blobs, not app state; app-prefixed fallback writes are checked by Put and the streaming new-door witness", |
| "bucket/Delete": "the data boundary never sends an unconditional delete: Delete reads the exact revision, " + |
| "authorizes it and issues DeleteIfMatch, which bucket/DeleteIfMatch counts", |
diff --git a/internal/console/demo_domains.go b/internal/console/demo_domains.go| index b99267fc1..a8a406f66 100644 |
| --- a/internal/console/demo_domains.go |
| +++ b/internal/console/demo_domains.go |
| @@ -1,8 +1,12 @@ |
| package console |
| import ( |
| + "context" |
| + "log" |
| "net/http" |
| "strings" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| ) |
| // The zone stays reserved while admission is disabled; that switch is not a |
| @@ -16,6 +20,7 @@ func (s *Server) demoDomainReserved(host string) bool { |
| func (s *Server) demoMutationRefusal(acct *Account, app string) *doorRefusal { |
| life, err := s.store.AppLife(acct.ID, app) |
| if err != nil { |
| + log.Printf("console: demo mutation %s/%s: app life: %v", acct.Sqid, app, err) |
| return &doorRefusal{http.StatusServiceUnavailable, demoCopy["DEMO-POLICY"]} |
| } |
| if life != nil && life.DemoID != "" { |
| @@ -23,3 +28,19 @@ func (s *Server) demoMutationRefusal(acct *Account, app string) *doorRefusal { |
| } |
| return nil |
| } |
| + |
| +// Only the private publisher carries this authority through the create cores. |
| +// A descriptor supplied to an ordinary create does not grant it. |
| +type demoRecordCreateKey struct{} |
| + |
| +func (s *Server) demoRecordReservation(ctx context.Context, rec provision.Record) error { |
| + if !s.demoDomainReserved(rec.Host) { |
| + return nil |
| + } |
| + if rec.Demo != nil && ctx.Value(demoRecordCreateKey{}) == rec.Demo.ID && |
| + s.cfg.Demo.ValidateBinding(*rec.Demo, rec.Account, rec.App, rec.Host, rec.Demo.Lifetime, strings.TrimPrefix(rec.Region, "fleet/")) == nil && |
| + rec.Region == "fleet/"+s.cfg.Demo.Fleet { |
| + return nil |
| + } |
| + return &hostsUsedError{doorRefusal{http.StatusConflict, demoCopy["DEMO-POLICY"]}} |
| +} |
diff --git a/internal/console/demo_policy.go b/internal/console/demo_policy.go| index 883a89ad5..76ea4f18d 100644 |
| --- a/internal/console/demo_policy.go |
| +++ b/internal/console/demo_policy.go |
| @@ -2,7 +2,6 @@ package console |
| import ( |
| "context" |
| - "fmt" |
| "time" |
| "github.com/carlosframework/platform/internal/demo" |
| @@ -38,7 +37,7 @@ func (s *Server) writeDemoPolicy(ctx context.Context, d DemoRow, life AppLife) e |
| defer mu.Unlock() |
| hold, ref := s.policyWriter(ctx) |
| if ref != nil { |
| - return fmt.Errorf("%w: writer lease: %s", demo.ErrPolicy, ref.Msg) |
| + return demoPublishRefusal(ref) |
| } |
| base, etag, next, _, err := s.policyBase(ctx, acct, d.App, hold, true) |
| if err != nil { |
| @@ -54,7 +53,7 @@ func (s *Server) writeDemoPolicy(ctx context.Context, d DemoRow, life AppLife) e |
| base.Sizes = nil |
| _, ref = s.writePolicy(ctx, acct, d.App, "demo", hold, base, next, etag, "demo deny-all small policy") |
| if ref != nil { |
| - return fmt.Errorf("%w: policy write: %s", demo.ErrPolicy, ref.Msg) |
| + return demoPublishRefusal(ref) |
| } |
| return nil |
| } |
diff --git a/internal/console/demo_publish.go b/internal/console/demo_publish.go| index c453be4ce..26ccbfaf5 100644 |
| --- a/internal/console/demo_publish.go |
| +++ b/internal/console/demo_publish.go |
| @@ -24,6 +24,15 @@ const demoStartWindow = 60 * time.Second |
| var errDemoWorkerUnavailable = errors.New("demo-build: assigned worker is unavailable") |
| var errDemoStartTimeout = errors.New("demo-build: starting timed out") |
| +// A busy or lost writer lease and an unpublished policy are retryable. Keep |
| +// policy identity refusals distinct from those service failures. |
| +func demoPublishRefusal(ref *doorRefusal) error { |
| + if ref.Status >= 500 { |
| + return fmt.Errorf("demo-build: %s", ref.Msg) |
| + } |
| + return fmt.Errorf("%w: %s", demo.ErrPolicy, ref.Msg) |
| +} |
| + |
| func demoVersion(j demobuild.Job) string { return fmt.Sprintf("v0.0.0-demo.%d", j.Generation) } |
| // publishDemo consumes only the durable accepted result. Each boundary acquires |
| @@ -87,12 +96,12 @@ func (s *Server) publishDemo(ctx context.Context, d DemoRow, j demobuild.Job, ou |
| } |
| hold, ref := s.policyWriter(ctx) |
| if ref != nil { |
| - return fmt.Errorf("%w: writer lease: %s", demo.ErrPolicy, ref.Msg) |
| + return demoPublishRefusal(ref) |
| } |
| ctx, releaseAttempt, ref := s.policyAttempt(ctx, hold) |
| defer releaseAttempt() |
| if ref != nil { |
| - return fmt.Errorf("%w: writer lease: %s", demo.ErrPolicy, ref.Msg) |
| + return demoPublishRefusal(ref) |
| } |
| next := "" |
| switch stage { |
| @@ -177,7 +186,7 @@ func (s *Server) placeDemoLocked(ctx context.Context, d DemoRow, life AppLife, c |
| yes := true |
| rec := provision.Record{Schema: 1, Host: d.Host, Slug: d.Name, App: d.App, Account: d.AccountSqid, Region: "fleet/" + d.Fleet, FleetBox: d.AssignedBox, FleetBoxAt: time.Unix(d.CreatedAt, 0).UTC().Format(time.RFC3339Nano), Channel: "edge", CreatedAt: time.Unix(d.CreatedAt, 0).UTC(), CreatedBy: "demo", Hibernate: &yes, Demo: &demo.Descriptor{ID: d.ID, Host: d.Host, Lifetime: life.Lifetime, ExpiresAt: life.ExpiresAt}} |
| if err := provision.ValidateShape(rec); err != nil { |
| - return err |
| + return fmt.Errorf("%w: %v", demo.ErrPolicy, err) |
| } |
| if !provision.ValidRecordHost(rec, m.Domain) { |
| return demo.ErrPolicy |
| @@ -198,6 +207,7 @@ func (s *Server) placeDemoLocked(ctx context.Context, d DemoRow, life AppLife, c |
| if !create { |
| return nil |
| } |
| + ctx = context.WithValue(ctx, demoRecordCreateKey{}, d.ID) |
| if lifetimesUnit(ctx) { |
| _, err = s.createRecordWithLifetimeLocked(ctx, rec, life.Lifetime) |
| return err |
| @@ -280,6 +290,9 @@ func (s *Server) publishReadyDemos(ctx context.Context) error { |
| } |
| if err != nil { |
| log.Printf("console: demo publication %s: %v", row.Job.ID, err) |
| + if !errors.Is(err, errDemoJob) && !errors.Is(err, ErrDemoToken) && !errors.Is(err, demo.ErrPolicy) && !errors.Is(err, errDemoStartTimeout) { |
| + continue |
| + } |
| if e := s.finishDemoPublish(ctx, row.Job, false); e != nil && !errors.Is(e, ErrDemoToken) && !errors.Is(e, errDemoJob) { |
| return e |
| } |
| @@ -318,7 +331,7 @@ func (s *Server) finishDemoPublish(ctx context.Context, j demobuild.Job, live bo |
| if live { |
| state = "published" |
| } |
| - if _, err = tx.ExecContext(ctx, `UPDATE demo_jobs SET state=?,publish_stage=CASE WHEN ?='failed' AND starting_until>0 AND starting_until<=? THEN 'timeout' ELSE publish_stage END WHERE id=? AND state='ready'`, state, state, time.Now().UnixNano(), j.ID); err != nil { |
| + if _, err = tx.ExecContext(ctx, `UPDATE demo_jobs SET state=?,publish_stage=CASE WHEN ?='failed' AND starting_until>0 AND starting_until<=? THEN 'timeout:' || publish_stage ELSE publish_stage END WHERE id=? AND state='ready'`, state, state, time.Now().UnixNano(), j.ID); err != nil { |
| return err |
| } |
| if _, err = tx.ExecContext(ctx, `UPDATE demo_apps SET active_job_id='' WHERE demo_id=? AND active_job_id=?`, d.ID, j.ID); err != nil { |
diff --git a/internal/console/demo_publish_test.go b/internal/console/demo_publish_test.go| index 5408e2e8d..96f31772c 100644 |
| --- a/internal/console/demo_publish_test.go |
| +++ b/internal/console/demo_publish_test.go |
| @@ -3,6 +3,7 @@ package console |
| import ( |
| "context" |
| "crypto/sha256" |
| + "database/sql" |
| "encoding/hex" |
| "errors" |
| "net/http" |
| @@ -12,7 +13,6 @@ import ( |
| "testing" |
| "time" |
| - "database/sql" |
| "github.com/carlosframework/platform/internal/demobuild" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/provision" |
diff --git a/internal/console/demo_review_test.go b/internal/console/demo_review_test.go| new file mode 100644 |
| index 000000000..c7937a4f1 |
| --- /dev/null |
| +++ b/internal/console/demo_review_test.go |
| @@ -0,0 +1,434 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "net/http/httptest" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestDemoStatusOnlyShippedVersion(t *testing.T) { |
| + for _, tc := range []struct { |
| + state, stage, message string |
| + version bool |
| + }{ |
| + {"failed", "", "The demo build failed. Submit another update with the same token.", false}, |
| + {"ready", "", "The demo is starting.", false}, |
| + {"ready", "policy", "The demo is starting.", false}, |
| + {"ready", "shipped", "The demo is starting.", true}, |
| + {"failed", "shipped", "The demo could not start. Submit another update with the same token.", true}, |
| + {"published", "starting", "The demo is live.", true}, |
| + } { |
| + t.Run(tc.state+"/"+tc.stage, func(t *testing.T) { |
| + s, _, j, _ := demoPublishFixture(t) |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET state=?,publish_stage=? WHERE id=?`, tc.state, tc.stage, j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if tc.state == "failed" && tc.stage == "" { |
| + raw, err := json.Marshal(demobuild.Result{Diagnostics: []demobuild.Diagnostic{{File: "main.go", Line: 1, Message: "syntax error"}}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET result=? WHERE id=?`, raw, j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + r := httptest.NewRequest("GET", "/api/demo/jobs/"+j.ID, nil) |
| + r.SetPathValue("jobID", j.ID) |
| + w := httptest.NewRecorder() |
| + s.handleDemoStatus(w, r) |
| + var out map[string]any |
| + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, has := out["version"] |
| + if has != tc.version || out["message"] != tc.message { |
| + t.Fatalf("status=%s", w.Body.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoRegionSetOperatorDoor(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + s.cli = newCLILimits() |
| + if err := s.store.AddMember(OpsAccountID, "operator@example.com", RoleOwner, time.Unix(d.CreatedAt, 0)); err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest(http.MethodPut, "/api/cli/apps/"+d.AccountSqid+"/"+d.App+"/region?exact=sqid", strings.NewReader(`{"region":"ie"}`)) |
| + r.Header.Set("Content-Type", "application/json") |
| + r.SetPathValue("account", d.AccountSqid) |
| + r.SetPathValue("app", d.App) |
| + r = r.WithContext(context.WithValue(r.Context(), cliRouteKey{}, Principal{Kind: PrincipalUser, Address: "operator@example.com"})) |
| + w := httptest.NewRecorder() |
| + s.handleAPIAppRegionSet(w, r) |
| + if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), demoCopy["DEMO-POLICY"]) { |
| + t.Fatalf("region: %d %s", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +func TestDemoZoneRecordCreators(t *testing.T) { |
| + for _, lifetime := range []bool{false, true} { |
| + for _, host := range []string{"demos.example.com", "shop.demos.example.com", "deep.shop.demos.example.com"} { |
| + t.Run(host+map[bool]string{false: "/marked", true: "/lifetime"}[lifetime], func(t *testing.T) { |
| + s, _, _, _ := demoPublishFixture(t) |
| + s.cfg.Demo.Domain = "demos.example.com" |
| + s.cfg.Demo.Enabled = false |
| + rec := provision.Record{Schema: 1, Account: "other", App: "shop", Host: host, Channel: "edge", Kind: "static"} |
| + var err error |
| + if lifetime { |
| + _, err = s.createRecordWithLifetime(t.Context(), rec, "life") |
| + } else { |
| + err = s.createRecordMarked(t.Context(), rec) |
| + } |
| + var refusal *hostsUsedError |
| + if !errors.As(err, &refusal) || refusal.ref.Msg != demoCopy["DEMO-POLICY"] { |
| + t.Fatalf("reservation: %v", err) |
| + } |
| + if _, _, err = s.cfg.Releases.Get(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host)); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("record created: %v", err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// Fail the next matching remote operation at a durable publication boundary. |
| +type demoPublishFaultStore struct { |
| + release.Store |
| + stage func() string |
| + want, operation string |
| + fault error |
| + hit bool |
| +} |
| + |
| +func (s *demoPublishFaultStore) fail(op string) error { |
| + if !s.hit && op == s.operation && s.stage() == s.want { |
| + s.hit = true |
| + return s.fault |
| + } |
| + return nil |
| +} |
| +func (s *demoPublishFaultStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if err := s.fail("get"); err != nil { |
| + return nil, "", err |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| +func (s *demoPublishFaultStore) Put(ctx context.Context, key string, b []byte, etag string) (string, error) { |
| + if err := s.fail("put"); err != nil { |
| + return "", err |
| + } |
| + return s.Store.Put(ctx, key, b, etag) |
| +} |
| + |
| +type demoReadyTransport func(*http.Request) (*http.Response, error) |
| + |
| +func (f demoReadyTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| +func demoAcceptReadiness(s *Server, version string) { |
| + s.demoTransport = demoReadyTransport(func(r *http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: 200, Header: http.Header{"X-Carlos-Version": []string{version}}, Body: io.NopCloser(strings.NewReader("ok"))}, nil |
| + }) |
| +} |
| +func TestDemoPublishTransientStageRetry(t *testing.T) { |
| + for _, stage := range []string{"", "policy", "shipped", "promoted"} { |
| + for _, operation := range []string{"get", "put"} { |
| + for _, fault := range []error{errors.New("store: 503 unavailable"), context.Canceled} { |
| + t.Run(stage+"/"+operation+"/"+fault.Error(), func(t *testing.T) { |
| + s, d, j, _ := demoPublishFixture(t) |
| + until := int64(0) |
| + if err := s.store.db.QueryRow(`SELECT starting_until FROM demo_jobs WHERE id=?`, j.ID).Scan(&until); err != nil { |
| + t.Fatal(err) |
| + } |
| + base := s.cfg.Releases |
| + fs := &demoPublishFaultStore{Store: base, want: stage, operation: operation, fault: fault, stage: func() string { |
| + var got string |
| + if err := s.store.db.QueryRow(`SELECT publish_stage FROM demo_jobs WHERE id=?`, j.ID).Scan(&got); err != nil { |
| + t.Fatal(err) |
| + } |
| + return got |
| + }} |
| + s.cfg.Releases = fs |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), j.ID) |
| + if !fs.hit || err != nil || row.State != "ready" || fs.stage() != stage { |
| + t.Fatalf("transient failure lost progress: hit=%v state=%s stage=%s err=%v", fs.hit, row.State, fs.stage(), err) |
| + } |
| + // A fresh console reopens the SQL/spool after the failed attempt. |
| + s.cfg.Releases = base |
| + s = reopenDemoJobs(t, s) |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err = s.readDemoJob(t.Context(), j.ID) |
| + if err != nil || row.State != "published" { |
| + t.Fatalf("retry: %s %v", row.State, err) |
| + } |
| + current, err := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil || current.Generation != d.Generation || current.UpdateAttempts != d.UpdateAttempts || current.ActiveJobID != "" { |
| + t.Fatalf("retry spent budget or retained slot: %+v %v", current, err) |
| + } |
| + var after int64 |
| + if err := s.store.db.QueryRow(`SELECT starting_until FROM demo_jobs WHERE id=?`, j.ID).Scan(&after); err != nil || after != until { |
| + t.Fatalf("deadline changed: %d %d %v", until, after, err) |
| + } |
| + ptr, err := release.Channel(t.Context(), base, s.cfg.ReleasePub, j.Account, j.App, "edge") |
| + if err != nil || ptr.Version != demoVersion(j) { |
| + t.Fatalf("live/channel disagree: %+v %v", ptr, err) |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestDemoPublishLeaseHeldRetry(t *testing.T) { |
| + s, d, j, _ := demoPublishFixture(t) |
| + s.cfg.Bucket = "test-bucket" |
| + leaser := &fakePolicyLeaser{err: &lease.HeldError{Owner: "outgoing-console", ExpiresAt: time.Now().Add(time.Minute)}} |
| + s.cfg.PolicyLease = leaser.leaser |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), j.ID) |
| + if err != nil || row.State != "ready" { |
| + t.Fatalf("lease contention failed job: %s %v", row.State, err) |
| + } |
| + leaser.err = nil |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + t.Cleanup(func() { s.ReleasePolicyWriter(context.Background()) }) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err = s.readDemoJob(t.Context(), j.ID) |
| + current, _ := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil || row.State != "published" || current.UpdateAttempts != d.UpdateAttempts { |
| + t.Fatalf("lease retry: %s %+v %v", row.State, current, err) |
| + } |
| +} |
| + |
| +func TestDemoCapabilitiesBrowserDoors(t *testing.T) { |
| + s, d, _, _ := demoPublishFixture(t) |
| + if err := s.store.AddMember(d.AccountID, "owner@example.com", RoleOwner, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + token, err := s.store.CreateSession("owner@example.com", "test", time.Now()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, handler := range map[string]http.HandlerFunc{"rename": s.handleAppRename, "controlPlane": s.handleAppControlPlaneSet} { |
| + t.Run(name, func(t *testing.T) { |
| + r := httptest.NewRequest(http.MethodPost, "/a/"+d.AccountSqid+"/apps/"+d.App+"/"+name, strings.NewReader("csrf="+token)) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.AddCookie(&http.Cookie{Name: sessionCookie, Value: token}) |
| + r.SetPathValue("sqid", d.AccountSqid) |
| + r.SetPathValue("app", d.App) |
| + w := httptest.NewRecorder() |
| + handler(w, r) |
| + if w.Code != 409 || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") || !strings.Contains(w.Body.String(), demoCopy["DEMO-POLICY"]) { |
| + t.Fatalf("browser refusal: %d %s", w.Code, w.Body.String()) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoZoneSeedImportDoors(t *testing.T) { |
| + lifetimesFor(t, func(t *testing.T, on func(*testing.T, markCase)) { |
| + for _, door := range markDoors { |
| + if door.name != "seed" && door.name != "import" { |
| + continue |
| + } |
| + t.Run(door.name, func(t *testing.T) { |
| + c := door.build(t) |
| + on(t, c) |
| + c.fx.srv.cfg.Demo.Domain = fromDomain |
| + code, body := c.create(t) |
| + if code != 409 || !strings.Contains(body, demoCopy["DEMO-POLICY"]) { |
| + t.Fatalf("reserved host: %d %s", code, body) |
| + } |
| + if recordPresent(t, c, c.recordKey) { |
| + t.Fatal("reserved host record created") |
| + } |
| + }) |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoZoneDescriptorDoesNotAuthorizeCreate(t *testing.T) { |
| + s, d, j, out := demoPublishFixture(t) |
| + if err := s.publishDemo(t.Context(), d, j, out); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, err := provision.GetRecord(t.Context(), s.cfg.Releases, j.Account, j.App, j.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Even the exact signed identity cannot grant an ordinary caller access. |
| + for _, create := range []func() error{ |
| + func() error { return s.createRecordMarked(t.Context(), *rec) }, |
| + func() error { _, err := s.createRecordWithLifetime(t.Context(), *rec, j.Lifetime); return err }, |
| + func() error { return s.createSeedRecord(t.Context(), seedCreate{}, *rec) }, |
| + } { |
| + err := create() |
| + var ref *hostsUsedError |
| + if !errors.As(err, &ref) || ref.ref.Msg != demoCopy["DEMO-POLICY"] { |
| + t.Fatalf("descriptor authorized an ordinary create: %v", err) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoPublishPrePromotionTerminalAndDeadline(t *testing.T) { |
| + for _, which := range []string{"policy", "timeout"} { |
| + t.Run(which, func(t *testing.T) { |
| + s, d, j, _ := demoPublishFixture(t) |
| + if which == "policy" { |
| + if err := provision.PutManifest(t.Context(), s.cfg.Releases, j.Account, j.App, provision.Manifest{Schema: 1, App: j.App, Domain: "other.example.com", Channel: "edge"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } else { |
| + if _, err := s.store.db.Exec(`UPDATE demo_jobs SET starting_until=? WHERE id=?`, time.Now().Add(-time.Second).UnixNano(), j.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), j.ID) |
| + current, _ := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil || row.State != "failed" || current.ActiveJobID != "" { |
| + t.Fatalf("terminal: %s %+v %v", row.State, current, err) |
| + } |
| + if _, _, err := s.cfg.Releases.Get(t.Context(), release.ChannelKey(j.Account, j.App, "edge")); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("terminal published channel: %v", err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoZoneFirstDeployAndAttach(t *testing.T) { |
| + f := newFromFixture(t, 0) |
| + s := f.fx.srv |
| + s.cfg.Demo.Domain = fromDomain |
| + // createDeployInstance and mintPlatformHost both use instanceCreate. |
| + for _, kind := range []string{"instance", "static"} { |
| + code, out := f.create(t, `{"host":"shop.`+fromDomain+`","kind":"`+kind+`"}`) |
| + if code != 409 || out["error"] != demoCopy["DEMO-POLICY"] { |
| + t.Fatalf("first deploy %s: %d %v", kind, code, out) |
| + } |
| + } |
| + acct, err := s.store.AccountBySqid("bab") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, ref := s.attachDomain(t.Context(), acct, fromApp, "alias."+fromDomain, "static", "stable", "operator@example.com") |
| + if ref == nil || ref.Status != 409 || ref.Msg != demoCopy["DEMO-POLICY"] { |
| + t.Fatalf("attach: %+v", ref) |
| + } |
| +} |
| + |
| +func TestDemoPublishCancellationAfterChannelWrite(t *testing.T) { |
| + s, _, j, _ := demoPublishFixture(t) |
| + ctx, cancel := context.WithCancel(t.Context()) |
| + defer cancel() |
| + base := s.cfg.Releases |
| + s.cfg.Releases = demoBoundaryStore{Store: base, after: func(key string) { |
| + if key == release.ChannelKey(j.Account, j.App, "edge") { |
| + cancel() |
| + } |
| + }} |
| + if err := s.publishReadyDemos(ctx); !errors.Is(err, context.Canceled) { |
| + t.Fatalf("cancel: %v", err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), j.ID) |
| + if err != nil || row.State != "ready" { |
| + t.Fatalf("uncertain promotion failed: %s %v", row.State, err) |
| + } |
| + before, err := release.Channel(t.Context(), base, s.cfg.ReleasePub, j.Account, j.App, "edge") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.Releases = base |
| + s = reopenDemoJobs(t, s) |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + after, err := release.Channel(t.Context(), base, s.cfg.ReleasePub, j.Account, j.App, "edge") |
| + if err != nil || after.Version != before.Version || len(after.History) != len(before.History) { |
| + t.Fatalf("promotion replay: %+v %+v %v", before, after, err) |
| + } |
| + row, err = s.readDemoJob(t.Context(), j.ID) |
| + if err != nil || row.State != "published" { |
| + t.Fatalf("replay: %s %v", row.State, err) |
| + } |
| +} |
| + |
| +func TestDemoPublishUpdatePlacementRetry(t *testing.T) { |
| + s, d, j, out := demoPublishFixture(t) |
| + demoAcceptReadiness(s, demoVersion(j)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + current, err := s.store.demoByID(t.Context(), d.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + next, err := s.enqueueDemo(t.Context(), current, demoJobSource()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.pickupDemo(t.Context(), next.ID, next.Attempt, next.Fleet, next.Box); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err := s.readDemoJob(t.Context(), next.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + next = row.Job |
| + out.JobID, out.Attempt, out.BinaryPath = next.ID, next.Attempt, "" |
| + if err := s.storeDemoResult(t.Context(), next, out, []byte("demo executable bytes")); err != nil { |
| + t.Fatal(err) |
| + } |
| + fs := &demoPublishFaultStore{Store: s.cfg.Releases, want: "promoted", operation: "get", fault: errors.New("store: 503 unavailable"), stage: func() string { |
| + var stage string |
| + if err := s.store.db.QueryRow(`SELECT publish_stage FROM demo_jobs WHERE id=?`, next.ID).Scan(&stage); err != nil { |
| + t.Fatal(err) |
| + } |
| + return stage |
| + }} |
| + s.cfg.Releases = fs |
| + demoAcceptReadiness(s, demoVersion(next)) |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + ptr, err := release.Channel(t.Context(), fs, s.cfg.ReleasePub, next.Account, next.App, "edge") |
| + if err != nil || ptr.Version != demoVersion(next) || next.Generation != 2 { |
| + t.Fatalf("update not promoted: %+v %v", ptr, err) |
| + } |
| + row, err = s.readDemoJob(t.Context(), next.ID) |
| + if err != nil || row.State != "ready" || !fs.hit { |
| + t.Fatalf("promoted update failed: %s %v", row.State, err) |
| + } |
| + if err := s.publishReadyDemos(t.Context()); err != nil { |
| + t.Fatal(err) |
| + } |
| + row, err = s.readDemoJob(t.Context(), next.ID) |
| + if err != nil || row.State != "published" { |
| + t.Fatalf("next pass: %s %v", row.State, err) |
| + } |
| +} |
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go| index 2f715e7b2..c436a149f 100644 |
| --- a/internal/console/domainattach.go |
| +++ b/internal/console/domainattach.go |
| @@ -133,6 +133,9 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k |
| return attachResult{}, &doorRefusal{http.StatusUnprocessableEntity, |
| "not a valid hostname โ attach a full hostname like tickets.example.com"} |
| } |
| + if err := s.demoRecordReservation(ctx, provision.Record{Host: host}); err != nil { |
| + return attachResult{}, &doorRefusal{http.StatusConflict, demoCopy["DEMO-POLICY"]} |
| + } |
| if policy := s.domainHostPolicy(host, acct.Sqid); policy == hostReserved || (policy == hostPlatform && !platform) { |
| return attachResult{}, &doorRefusal{http.StatusUnprocessableEntity, |
| "that hostname is platform-managed"} |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index 2c7b6747e..c8f41e648 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -567,6 +567,9 @@ func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) e |
| // createRecordMarkedLocked shares the ordinary create checks under both locks. |
| func (s *Server) createRecordMarkedLocked(ctx context.Context, rec provision.Record) error { |
| + if err := s.demoRecordReservation(ctx, rec); err != nil { |
| + return err |
| + } |
| // The regional recheck (spec ยง6.3): a regional claim written since the |
| // door's first check refuses the create before anything is marked. |
| if err := s.regionalRecheck(ctx, rec); err != nil { |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index 5fadcf249..1b3c5a58a 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -61,6 +61,9 @@ func (s *Server) createRecordWithLifetime(ctx context.Context, rec provision.Rec |
| // errLifetimeSettling, errLifetimePending, or a read error with nothing |
| // persisted. |
| func (s *Server) createRecordWithLifetimeLocked(ctx context.Context, rec provision.Record, lifetime string) (*provision.Record, error) { |
| + if err := s.demoRecordReservation(ctx, rec); err != nil { |
| + return nil, err |
| + } |
| if len(rec.Maintenance) != 0 { |
| return nil, provision.ErrMaintenanceProjection |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 9c411536c..563965de6 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -4270,7 +4270,7 @@ func (s *Server) accountApp(w http.ResponseWriter, r *http.Request) (addr, raw s |
| } |
| if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| if ref := s.demoMutationRefusal(acct, app); ref != nil { |
| - jsonError(w, ref.Status, ref.Msg) |
| + s.renderMessage(w, r, ref.Status, "Demo", ref.Msg) |
| return "", "", nil, "", "", false |
| } |
| } |
diff --git a/internal/provision/demo_census_test.go b/internal/provision/demo_census_test.go| index 2a8e3dc88..b0d61927c 100644 |
| --- a/internal/provision/demo_census_test.go |
| +++ b/internal/provision/demo_census_test.go |
| @@ -30,8 +30,17 @@ func demoWriteCensusInventory() []censusEntry { |
| {"internal/activator/demo_durability.go", "ExecBackend.restoreDemoLocal", "nonrecord", "sel:Put", "783f1f9b46972a7156c2663ee1d463e6ea0b075bf35f09f2f9488cd9e78bb3e0"}, |
| // Both callers supply demo source/job keys, under the app lock and SQL recheck. |
| {"internal/console/demo_jobs.go", "Server.putDemoObject", "nonrecord", "sel:Put", "41da9bc04403d0c94f191d5a34562415d81fdbddcacf219ec80174f0044c2573"}, |
| - // Both callers hold app and hostname locks; retains rechecks and typed CreateRecord. |
| - {"internal/console/hostsused.go", "Server.createRecordMarkedLocked", "record-writer", "key:CreateRecord,key:RecordKey", "7133825222a1a780ec93049d7f8c42eceded6fb3d3cefd6ad271210dec791273"}, |
| + // Round 1: adds demoRecordReservation before any mark/write. Both callers |
| + // still hold app and hostname locks; only placeDemoLocked supplies the |
| + // private context authority. TestDemoZoneRecordCreators and |
| + // TestDemoZoneDescriptorDoesNotAuthorizeCreate cover the refusal. |
| + {"internal/console/hostsused.go", "Server.createRecordMarkedLocked", "record-writer", "key:CreateRecord,key:RecordKey", "b4cbb54c137e354b69fd81efe096d9ce6bf17598c15f7d2cda2f74eafc2fb468"}, |
| + // Same reservation before BeginAllocation; no change to the slot, |
| + // sequence or recovery protocol. Seed/import witnesses run with lifetimes on. |
| + {"internal/console/lifetimes_create.go", "Server.createRecordWithLifetimeLocked", "key-site", "key:RecordKey", "53402d617ed4f9616cba944027774a45b10df09f81bd5a7e3941f28915bf0c72"}, |
| + // Shared reservation after normalization, before any claim/record write. |
| + // Existing proof, ownership and static CreateRecord behavior is retained. |
| + {"internal/console/domainattach.go", "Server.attachDomainAs", "record-writer", "key:CreateRecord", "abd913b9788cdc7d8bbb409d57f5b1a70128c9b60a9b40d71a5be8b98ec8ade5"}, |
| } { |
| found := false |
| for i, old := range entries { |