feat: seed claimed apps behind the existing traffic gate
Add fresh claim seed transitions, atomic gated provisioning, snapshot restore, claim-bound verification, and lease-aware abort cleanup. Publish destination and ingress capability evidence with the existing seeds floor. Targeted claim and seed/import regressions, gofmt and go vet pass. The cumulative census overlay and independent review remain controller-owned.
instances_demo_claim_test.go+21 −0instances_seed.go+12 −8internal/activator/activator.go+5 −0internal/activator/backend_exec.go+3 −0internal/activator/demo_claim_seed_test.go+161 −0internal/activator/seedplace.go+13 −2internal/console/demo_claim_seed.go+358 −0internal/console/demo_claim_seed_test.go+266 −0internal/console/seedfinish.go+31 −2internal/console/seedfloor.go+1 −1internal/console/seedfloor_test.go+1 −1internal/console/seedsweep.go+4 −0internal/edge/demo_claim_seed_test.go+64 −0internal/edge/importgate.go+5 −1internal/host/demo_claim_seed_test.go+40 −0internal/host/edgesfile.go+3 −2internal/host/edgesfile_test.go+5 −5internal/host/seedwiring.go+21 −0internal/provision/demo_claim_seed.go+188 −0internal/provision/demo_claim_seed_test.go+323 −0internal/provision/forward.go+2 −0internal/provision/provision.go+3 −0internal/provision/reconcile.go+22 −1internal/provision/seed.go+26 −17internal/provision/seedreconcile.go+30 −0internal/registry/demo_claim_seed.go+49 −0internal/seeds/floor.go+2 −1internal/seeds/row.go+18 −5internal/seeds/seeds.go+5 −2internal/status/snapshot.go+3 −0internal/status/snapshot_test.go+1 −1
CI failed — run details
Intent
<task-notification> <task-id>bkvv53jg3</task-id> <tool-use-id>toolu_01TuN7Qw5wpTRDWJaSYAeKbL</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/22215d20-2b53-4378-8426-ae55e2362d13/tasks/bkvv53jg3.output</output-file> <status>completed</status> <summary>Background command "S=/home/paulca/.cache/tmp/claude-1001/agent-start-demo-3; until [ -f $S/t3fix3.done ]; do sleep 30; done; tail -1 $S/t3fix3.log" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 13.3 g CO₂e (1,560,617 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-3, 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/instances_demo_claim_test.go b/instances_demo_claim_test.go| new file mode 100644 |
| index 000000000..8b1a8c5ba |
| --- /dev/null |
| +++ b/instances_demo_claim_test.go |
| @@ -0,0 +1,21 @@ |
| +package main |
| + |
| +import ( |
| + "encoding/json" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestDemoClaimSeedRendering(t *testing.T) { |
| + var rec apiInstanceRecord |
| + if err := json.Unmarshal([]byte(`{"seed":{"id":"sd_aaaaaaaaaaaaaaaaaaaaaaaaaa","kind":"demo-claim","claim_id":"operation","state":"committed"}}`), &rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rec.Seed.ClaimID != "operation" || seedCell(rec) != "demo-claim committed" { |
| + t.Fatalf("%+v %s", rec.Seed, seedCell(rec)) |
| + } |
| + body, err := json.Marshal(apiSeed{Kind: "replica", State: "placed"}) |
| + if err != nil || strings.Contains(string(body), "claim_id") { |
| + t.Fatal(string(body), err) |
| + } |
| +} |
diff --git a/instances_seed.go b/instances_seed.go| index 3d3b0ff1b..bd15aefdf 100644 |
| --- a/instances_seed.go |
| +++ b/instances_seed.go |
| @@ -14,14 +14,15 @@ import ( |
| // apiSeed is the record's seed as the CLI renders it |
| // (provision.SeedSource's wire shape). |
| type apiSeed struct { |
| - ID string `json:"id"` |
| - Kind string `json:"kind"` |
| - From string `json:"from,omitempty"` |
| - TXID string `json:"txid,omitempty"` |
| - SHA256 string `json:"sha256"` |
| - Bytes int64 `json:"bytes"` |
| - State string `json:"state"` |
| - Reason string `json:"reason,omitempty"` |
| + ID string `json:"id"` |
| + ClaimID string `json:"claim_id,omitempty"` |
| + Kind string `json:"kind"` |
| + From string `json:"from,omitempty"` |
| + TXID string `json:"txid,omitempty"` |
| + SHA256 string `json:"sha256"` |
| + Bytes int64 `json:"bytes"` |
| + State string `json:"state"` |
| + Reason string `json:"reason,omitempty"` |
| } |
| // seedCell is the list's SEED column (seeded-instances spec §7). |
| @@ -30,6 +31,9 @@ func seedCell(r apiInstanceRecord) string { |
| if s == nil { |
| return "-" |
| } |
| + if s.Kind == "demo-claim" { |
| + return s.Kind + " " + s.State |
| + } |
| switch s.State { |
| case "reserving": |
| return fmt.Sprintf("copying from %s", s.From) |
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 046a94d10..853422e4f 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -80,6 +80,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/seeds" |
| ) |
| // SidecarHeader marks every request a co-spawned sidecar makes to its own |
| @@ -3273,6 +3274,10 @@ func (a *Service) doWakeOnce(ctx context.Context, e *actEntry) (*wokenInstance, |
| // the placed file, and the next wake records it (finishPlacement). |
| if p, ok := a.backend.(seedPlacer); ok && !rt.IsDemo() { |
| if err := p.SeedPlaced(ctx, rt, rep); err != nil { |
| + if src, parseErr := seeds.ParseRowSeed(rt.SeedSource); parseErr != nil || (src != nil && src.Kind == seeds.KindDemoClaim) { |
| + a.cleanupFailedWake(ctx, e, rt, w, lease) |
| + return w, err |
| + } |
| log.Printf("activator: %s: seed placement not recorded yet: %v", host, err) |
| } |
| } |
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 69c1ad312..0601bab70 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -257,6 +257,9 @@ type ExecBackend struct { |
| // OnSeedPlaced records a seed placed (Task 4): the record's CAS to |
| // placed, then the snapshot's delete. Nil: not recorded here. |
| OnSeedPlaced func(ctx context.Context, account, app, host, id string) error |
| + // OnDemoClaimSeedWake rechecks the durable claim after taking the lease, |
| + // before restore or exec. A stale row cannot restart an aborted target. |
| + OnDemoClaimSeedWake func(context.Context, registry.Route, *seeds.RowSeed) error |
| // ConfigGate answers whether this box can provide rt's config (amadan |
| // #213): nil means yes, an error means refuse. Acquire asks it BEFORE |
| // lease.Acquire, so a box that would start the instance without its |
diff --git a/internal/activator/demo_claim_seed_test.go b/internal/activator/demo_claim_seed_test.go| new file mode 100644 |
| index 000000000..187934d3c |
| --- /dev/null |
| +++ b/internal/activator/demo_claim_seed_test.go |
| @@ -0,0 +1,161 @@ |
| +//go:build linux |
| + |
| +package activator |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDemoClaimFreshSeed(t *testing.T) { |
| + noOwnReplica(t) |
| + for _, missing := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "snapshotThenApp", true: "missingSnapshot"}[missing], func(t *testing.T) { |
| + b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{}) |
| + b.OnDemoClaimSeedWake = func(context.Context, registry.Route, *seeds.RowSeed) error { return nil } |
| + rt, objects, id := seededRoute(t, b, rt, seeds.StateReady) |
| + src, _ := seeds.ParseRowSeed(rt.SeedSource) |
| + src.Kind = seeds.KindDemoClaim |
| + src.ClaimID, _ = demobuild.NewJobID() |
| + rt.SeedSource = src.Encode() |
| + if missing { |
| + delete(objects.body, id) |
| + } |
| + fresh, err := b.Restore(context.Background(), rt) |
| + if fresh || (err != nil) != missing { |
| + t.Fatalf("fresh=%v err=%v", fresh, err) |
| + } |
| + if !missing { |
| + if err := checkSeedDB(context.Background(), rt.DBPath); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestDemoClaimSeedGate(t *testing.T) { |
| + b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{}) |
| + b.OnDemoClaimSeedWake = func(context.Context, registry.Route, *seeds.RowSeed) error { return nil } |
| + rt, _, _ = seededRoute(t, b, rt, seeds.StateReady) |
| + src, _ := seeds.ParseRowSeed(rt.SeedSource) |
| + src.Kind = seeds.KindDemoClaim |
| + src.ClaimID, _ = demobuild.NewJobID() |
| + rt.SeedSource = src.Encode() |
| + called := 0 |
| + b.OnSeedPlaced = func(context.Context, string, string, string, string) error { called++; return nil } |
| + if err := b.SeedPlaced(context.Background(), rt, plainRep{}); err == nil || called != 0 { |
| + t.Fatal("placed without replica confirmation") |
| + } |
| + rep := &syncRep{} |
| + if err := b.SeedPlaced(context.Background(), rt, rep); err != nil || rep.synced != 1 || called != 1 { |
| + t.Fatalf("sync: %v %d %d", err, rep.synced, called) |
| + } |
| + src.State = seeds.StateAborted |
| + rt.SeedSource = src.Encode() |
| + if fresh, err := b.Restore(context.Background(), rt); err == nil || fresh { |
| + t.Fatal("aborted seed fell through to empty restore") |
| + } |
| +} |
| + |
| +func TestDemoClaimFreshSeedConcurrentWake(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + b.startGate = make(chan struct{}) |
| + rt := testRoute("shop.example.com") |
| + id, _ := seeds.NewID() |
| + claim, _ := demobuild.NewJobID() |
| + rt.SeedSource = seeds.RowSeed{ID: id, Kind: seeds.KindDemoClaim, ClaimID: claim, State: seeds.StateReady}.Encode() |
| + var wg sync.WaitGroup |
| + for range 12 { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + release, err := a.beginRequest(context.Background(), rt) |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + release() |
| + }() |
| + } |
| + waitFor(t, "wake", func() bool { _, _, started := b.counts(); return started == 1 }) |
| + close(b.startGate) |
| + wg.Wait() |
| + acquires, restores, starts := b.counts() |
| + if acquires != 1 || restores != 1 || starts != 1 { |
| + t.Fatalf("%d leases, %d restores, %d starts", acquires, restores, starts) |
| + } |
| +} |
| +func TestDemoClaimSeedCommit(t *testing.T) { |
| + b, rt := nestedBackend(t, &fakeControl{}, &fakeUnit{}) |
| + b.OnDemoClaimSeedWake = func(context.Context, registry.Route, *seeds.RowSeed) error { return nil } |
| + rt, objects, _ := seededRoute(t, b, rt, seeds.StateCommitted) |
| + src, _ := seeds.ParseRowSeed(rt.SeedSource) |
| + src.Kind = seeds.KindDemoClaim |
| + src.ClaimID, _ = demobuild.NewJobID() |
| + rt.SeedSource = src.Encode() |
| + if err := os.MkdirAll(filepath.Dir(rt.DBPath), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := writeMinimalSQLite(rt.DBPath); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A committed destination keeps its own warm lineage without fetching seed data. |
| + if fresh, err := b.Restore(context.Background(), rt); err != nil || fresh { |
| + t.Fatalf("%v %v", fresh, err) |
| + } |
| + if objects.opens != 0 { |
| + t.Fatal("committed wake fetched temporary snapshot") |
| + } |
| +} |
| + |
| +type failedClaimPlacement struct { |
| + *fakeBackend |
| + stuck bool |
| +} |
| + |
| +func (b *failedClaimPlacement) SeedPlaced(context.Context, registry.Route, Rep) error { |
| + p := b.lastProc() |
| + p.mu.Lock() |
| + p.stuck = b.stuck |
| + p.mu.Unlock() |
| + return errors.New("first replica not confirmed") |
| +} |
| +func TestDemoClaimSeedGateFailedReplicaKeepsLeaseUntilStopped(t *testing.T) { |
| + for _, stuck := range []bool{false, true} { |
| + t.Run(fmt.Sprint(stuck), func(t *testing.T) { |
| + a, b, _, _ := testActivator(t, time.Minute) |
| + a.backend = &failedClaimPlacement{b, stuck} |
| + rt := testRoute("shop.example.com") |
| + id, _ := seeds.NewID() |
| + claim, _ := demobuild.NewJobID() |
| + rt.SeedSource = seeds.RowSeed{ID: id, Kind: seeds.KindDemoClaim, ClaimID: claim, State: seeds.StateReady}.Encode() |
| + if release, err := a.beginRequest(context.Background(), rt); err == nil { |
| + release() |
| + t.Fatal("served unconfirmed replica") |
| + } |
| + rep := b.lastRep() |
| + if rep == nil { |
| + t.Fatal("no replica") |
| + } |
| + want := 1 |
| + if stuck { |
| + want = 0 |
| + } |
| + if rep.closeCount() != want { |
| + t.Fatalf("replica closed %d times, want %d", rep.closeCount(), want) |
| + } |
| + b.lastProc().mu.Lock() |
| + b.lastProc().stuck = false |
| + b.lastProc().mu.Unlock() |
| + }) |
| + } |
| +} |
diff --git a/internal/activator/seedplace.go b/internal/activator/seedplace.go| index 84ccfed34..7237d40fb 100644 |
| --- a/internal/activator/seedplace.go |
| +++ b/internal/activator/seedplace.go |
| @@ -88,7 +88,7 @@ func ownsReplica(src *seeds.RowSeed) bool { |
| // seedRestores reports a row Restore sends through seededRestore: a seed |
| // still to place, or one whose own replica exists. |
| func seedRestores(src *seeds.RowSeed) bool { |
| - return src != nil && (src.Placeable() || ownsReplica(src)) |
| + return src != nil && (src.Kind == seeds.KindDemoClaim || src.Placeable() || ownsReplica(src)) |
| } |
| // seededRestore is the plain-path seed fallback (spec §3.4). It never |
| @@ -107,9 +107,20 @@ func (b *ExecBackend) seededRestore(ctx context.Context, rt registry.Route, src |
| } |
| return false, err |
| } |
| + if src.Kind == seeds.KindDemoClaim && (!src.Placeable() && !ownsReplica(src)) { |
| + return fail(fmt.Errorf("claim seed %s is not ready", src.ID)) |
| + } |
| if err := seeds.Check(host, src.ID); err != nil { |
| return fail(fmt.Errorf("seed fallback for %s: %w", host, err)) |
| } |
| + if src.Kind == seeds.KindDemoClaim && src.State != seeds.StateCommitted { |
| + if b.OnDemoClaimSeedWake == nil { |
| + return fail(fmt.Errorf("claim seed %s has no admission check", src.ID)) |
| + } |
| + if err := b.OnDemoClaimSeedWake(ctx, rt, src); err != nil { |
| + return fail(err) |
| + } |
| + } |
| // restoreOwn restores the host's own lineage, the staging fallback |
| // included, and never reports fresh: a host that has (or was listed as |
| // having) a replica of its own and finds none must not boot empty. The |
| @@ -530,7 +541,7 @@ func (e *readErrs) Read(p []byte) (int, error) { |
| // cannot be asked for its first upload records nothing. |
| func (b *ExecBackend) SeedPlaced(ctx context.Context, rt registry.Route, rep Rep) error { |
| src, err := seeds.ParseRowSeed(rt.SeedSource) |
| - if err != nil || src == nil || !src.Placeable() || src.State == seeds.StatePlaced { |
| + if err != nil || src == nil || !src.Placeable() || (src.State == seeds.StatePlaced && src.Kind != seeds.KindDemoClaim) { |
| return err |
| } |
| s, ok := rep.(interface{ SyncAndWait(context.Context) error }) |
diff --git a/internal/console/demo_claim_seed.go b/internal/console/demo_claim_seed.go| new file mode 100644 |
| index 000000000..37de9a1f7 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_seed.go |
| @@ -0,0 +1,358 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "errors" |
| + "io" |
| + "os" |
| + "reflect" |
| + "slices" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// The token is reproducible after a console restart but never persisted. |
| +func (s *Server) demoClaimVerifyToken(id string) (string, error) { |
| + if !s.demoClaimEnabled() || len(s.cfg.Key) != ed25519.PrivateKeySize || !demobuild.ValidJobID(id) { |
| + return "", errors.New(demoClaimUnavailable) |
| + } |
| + mac := hmac.New(sha256.New, s.cfg.Key.Seed()) |
| + _, _ = mac.Write([]byte("carlos demo claim verify v1\n" + id)) |
| + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil |
| +} |
| + |
| +// Admission requires every ingress reader as well as every destination. |
| +// Protocol 2's existing seeds floor excludes an older rollback binary. |
| +func (s *Server) demoClaimSeedReady(ctx context.Context, region string) error { |
| + refuse := func() error { return errors.New(demoClaimUnavailable) } |
| + if !s.demoClaimEnabled() || s.cfg.Releases == nil || region != s.cfg.Region || s.haRegion(region) { |
| + return refuse() |
| + } |
| + if ref := s.seedRegionReady(ctx, region, false); ref != nil { |
| + return refuse() |
| + } |
| + floor, err := seeds.ReadFloor(ctx, s.cfg.Releases) |
| + if err != nil || floor == nil || floor.Min < seeds.DemoClaimProtocol { |
| + return refuse() |
| + } |
| + snap, err := s.liveEdges(ctx) |
| + if err != nil || !snap.EvidenceComplete() || len(snap.Files) == 0 { |
| + return refuse() |
| + } |
| + for _, f := range snap.Files { |
| + if !slices.Contains(f.Capabilities, seeds.DemoClaimCapability) || f.SeedsProtocol < seeds.DemoClaimProtocol || |
| + f.SeedsFloorMinRelease != floor.MinRelease || (f.PrevRelease != "none" && f.PrevSeedsAllowedFor != floor.MinRelease) || |
| + ((f.SeedsFloorState != "" || f.SeedsFloorGeneration != 0) && (f.SeedsFloorState != "accepted" || f.SeedsFloorGeneration == 0)) { |
| + return refuse() |
| + } |
| + } |
| + boxes, err := status.LoadBoxes(ctx, s.cfg.Releases) |
| + if err != nil { |
| + return refuse() |
| + } |
| + byLabel := map[string]status.Box{} |
| + dup := map[string]bool{} |
| + for _, b := range boxes { |
| + if _, ok := byLabel[b.Label]; ok { |
| + dup[b.Label] = true |
| + } |
| + byLabel[b.Label] = b |
| + } |
| + for _, f := range snap.Files { |
| + b, ok := byLabel[f.Box] |
| + if !ok || dup[f.Box] || status.BoxStale(b, time.Now(), status.SnapshotPeriod) || b.Metrics == nil || !slices.Contains(b.Metrics.Capabilities, seeds.DemoClaimCapability) { |
| + return refuse() |
| + } |
| + if s.homeRegionIn(f.Placement) == s.homeRegionIn(region) && b.Metrics.Platform != "linux-arm64" { |
| + return refuse() |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// Call while holding the app lock. Stored identity, not a caller's target, |
| +// authorizes all operation-owned record and snapshot writes. |
| +func (s *Server) demoClaimSeedOperation(ctx context.Context, op claimOp) (claimOp, error) { |
| + if !s.demoClaimEnabled() { |
| + return claimOp{}, errors.New(demoClaimUnavailable) |
| + } |
| + fresh, err := scanDemoClaimOp(s.store.db.QueryRowContext(ctx, `SELECT `+demoClaimOpColumns+` FROM demo_claim_ops WHERE id=?`, op.ID)) |
| + if err != nil { |
| + return claimOp{}, err |
| + } |
| + if fresh.Target != op.Target || fresh.DemoID != op.DemoID || !demobuild.ValidJobID(fresh.ID) || !seeds.ValidID(fresh.Target.SeedID) { |
| + return claimOp{}, ErrDemoToken |
| + } |
| + life, err := s.store.AppLife(fresh.Target.AccountID, fresh.Target.App) |
| + if err != nil || life == nil || life.Lifetime != fresh.Target.Lifetime || life.Trashed() || life.Temporary() || life.DemoID != "" { |
| + return claimOp{}, ErrDemoToken |
| + } |
| + var marker string |
| + if err = s.store.db.QueryRowContext(ctx, `SELECT demo_claim_op FROM apps WHERE account_id=? AND app=?`, fresh.Target.AccountID, fresh.Target.App).Scan(&marker); err != nil || marker != fresh.ID { |
| + return claimOp{}, ErrDemoToken |
| + } |
| + return fresh, nil |
| +} |
| + |
| +func demoClaimRecordMatches(rec *provision.Record, op claimOp) bool { |
| + return rec != nil && rec.Account == op.Target.Sqid && rec.App == op.Target.App && rec.Host == op.Target.Host && |
| + rec.Seed.DemoClaim() && rec.Seed.ID == op.Target.SeedID && rec.Seed.ClaimID == op.ID |
| +} |
| + |
| +// createDemoClaimSeed reserves exactly the instance counted by Task 2. |
| +// The reserving record mints no route. Its ready transition supplies the |
| +// hash before the reconciler creates a route and traffic gate together. |
| +func (s *Server) createDemoClaimSeed(ctx context.Context, op claimOp) (*provision.Record, error) { |
| + if err := s.demoClaimSeedReady(ctx, op.Target.Region); err != nil { |
| + return nil, err |
| + } |
| + ctx = withDemoClaimOperation(ctx, op.ID) |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + defer s.lockHostname(op.Target.Host)() |
| + fresh, err := s.demoClaimSeedOperation(ctx, op) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !slices.Contains([]string{"reserved", "freezing", "copying", "verifying"}, fresh.Phase) || !time.Now().Before(fresh.Deadline) { |
| + return nil, ErrDemoToken |
| + } |
| + old, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err == nil { |
| + if !demoClaimRecordMatches(old, op) { |
| + return nil, ErrDemoToken |
| + } |
| + return old, nil |
| + } |
| + if !errors.Is(err, os.ErrNotExist) { |
| + return nil, err |
| + } |
| + if s.cfg.SeedData == nil || !s.leftoverCheckApplies(op.Target.Region, "") { |
| + return nil, errors.New(demoClaimUnavailable) |
| + } |
| + held, err := s.hostHoldsReplicaData(ctx, op.Target.Host) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if held { |
| + return nil, errors.New(demoClaimReserveFailed) |
| + } |
| + manifest := provision.Manifest{Schema: 1, App: op.Target.App, Domain: op.Target.Sqid + "." + s.cfg.AppsDomain, Channel: "edge"} |
| + previous, err := provision.GetManifest(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App) |
| + if errors.Is(err, os.ErrNotExist) { |
| + if err = provision.PutManifestIfMatch(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App, manifest, ""); err != nil { |
| + return nil, err |
| + } |
| + } else if err != nil { |
| + return nil, err |
| + } else if !reflect.DeepEqual(*previous, manifest) { |
| + return nil, ErrDemoToken |
| + } |
| + rec := provision.Record{Schema: 1, Host: op.Target.Host, Slug: op.Target.App, App: op.Target.App, Account: op.Target.Sqid, |
| + Channel: "edge", CreatedBy: op.Person, Region: op.Target.Region, CreatedAt: time.Now(), |
| + Seed: &provision.SeedSource{ID: op.Target.SeedID, ClaimID: op.ID, Kind: seeds.KindDemoClaim, State: seeds.StateReserving, By: op.Person, At: time.Now()}} |
| + if lifetimesUnit(ctx) { |
| + return s.createRecordWithLifetimeLocked(ctx, rec, op.Target.Lifetime) |
| + } |
| + return s.createRecordMarkedLocked(ctx, rec) |
| +} |
| + |
| +// publishDemoClaimSeed streams the already checked private snapshot, verifies |
| +// the stored bytes on retries, and publishes only their hash and length. |
| +func (s *Server) publishDemoClaimSeed(ctx context.Context, op claimOp, path, sha string, size int64) error { |
| + if size <= 0 || size > 268435456 || !demobuild.ValidDigest(sha) { |
| + return ErrDemoToken |
| + } |
| + token, err := s.demoClaimVerifyToken(op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + hash := seeds.HashToken(token) |
| + ready, err := func() (bool, error) { |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + return s.demoClaimSeedPublishState(ctx, op, sha, size, hash) |
| + }() |
| + if err != nil || ready { |
| + return err |
| + } |
| + deadline := time.Now().Add(120 * time.Second) |
| + if op.Deadline.Before(deadline) { |
| + deadline = op.Deadline |
| + } |
| + ctx, cancel := context.WithDeadline(ctx, deadline) |
| + defer cancel() |
| + if s.cfg.SeedData == nil { |
| + return errors.New(demoClaimUnavailable) |
| + } |
| + file, err := os.Open(path) |
| + if err != nil { |
| + return err |
| + } |
| + defer file.Close() |
| + st, err := file.Stat() |
| + if err != nil { |
| + return err |
| + } |
| + if !st.Mode().IsRegular() || st.Size() != size { |
| + return ErrDemoToken |
| + } |
| + check := func(r io.Reader) error { |
| + h := sha256.New() |
| + n, e := io.Copy(h, io.LimitReader(r, size+1)) |
| + if e != nil { |
| + return e |
| + } |
| + if n != size || hex.EncodeToString(h.Sum(nil)) != sha { |
| + return ErrDemoToken |
| + } |
| + return nil |
| + } |
| + if err = check(file); err != nil { |
| + return err |
| + } |
| + if _, err = file.Seek(0, io.SeekStart); err != nil { |
| + return err |
| + } |
| + key := seeds.SnapshotKey(op.Target.Host, op.Target.SeedID) |
| + _, err = release.PutObjectFrom(ctx, s.cfg.SeedData, key, file, size, "") |
| + if err != nil && !errors.Is(err, release.ErrCASConflict) { |
| + return err |
| + } |
| + // Verify what was persisted, including a create whose reply was lost. |
| + stored, _, err := release.OpenObjectStreaming(ctx, s.cfg.SeedData, key) |
| + if err != nil { |
| + return err |
| + } |
| + err = check(stored) |
| + closeErr := stored.Close() |
| + if err != nil { |
| + return err |
| + } |
| + if closeErr != nil { |
| + return closeErr |
| + } |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + ready, err = s.demoClaimSeedPublishState(ctx, op, sha, size, hash) |
| + if err != nil || ready { |
| + return err |
| + } |
| + currentToken, err := s.demoClaimVerifyToken(op.ID) |
| + if err != nil { |
| + return err |
| + } |
| + if !seeds.TokenMatches(hash, currentToken) { |
| + return ErrDemoToken |
| + } |
| + _, err = provision.SetRecordSeed(withDemoClaimOperation(ctx, op.ID), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host, |
| + provision.SeedPublishDemoClaim(op.Target.SeedID, op.ID, sha, size, hash)) |
| + if err == nil { |
| + s.bumpSerial(ctx) |
| + } |
| + return err |
| +} |
| + |
| +// demoClaimSeedPublishState is checked before transfer and again under the |
| +// app lock at publication, so network waits hold no lifecycle lock. |
| +func (s *Server) demoClaimSeedPublishState(ctx context.Context, op claimOp, sha string, size int64, hash string) (bool, error) { |
| + fresh, err := s.demoClaimSeedOperation(ctx, op) |
| + if err != nil { |
| + return false, err |
| + } |
| + if !slices.Contains([]string{"copying", "verifying"}, fresh.Phase) || !time.Now().Before(fresh.Deadline) { |
| + return false, ErrDemoToken |
| + } |
| + rec, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + return false, err |
| + } |
| + if !demoClaimRecordMatches(rec, op) { |
| + return false, ErrDemoToken |
| + } |
| + if rec.Seed.State == seeds.StateReserving { |
| + return false, nil |
| + } |
| + if slices.Contains([]string{seeds.StateReady, seeds.StatePlaced}, rec.Seed.State) && rec.Seed.SHA256 == sha && rec.Seed.Bytes == size && rec.Seed.VerifyHash == hash { |
| + return true, nil |
| + } |
| + return false, ErrDemoToken |
| +} |
| + |
| +// demoClaimSeedVerifyToken refuses a changed signing key. The coordinator |
| +// must abort and obtain new proof before attempting another claim. |
| +func (s *Server) demoClaimSeedVerifyToken(ctx context.Context, op claimOp) (string, error) { |
| + token, err := s.demoClaimVerifyToken(op.ID) |
| + if err != nil { |
| + return "", err |
| + } |
| + rec, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + return "", err |
| + } |
| + if !demoClaimRecordMatches(rec, op) || !slices.Contains([]string{seeds.StateReady, seeds.StatePlaced}, rec.Seed.State) || !seeds.TokenMatches(rec.Seed.VerifyHash, token) { |
| + return "", ErrDemoToken |
| + } |
| + return token, nil |
| +} |
| + |
| +// abortDemoClaimSeed requests a stop. false means the box has not yet |
| +// acknowledged cleanup. The coordinator retains the source hold until true. |
| +func (s *Server) abortDemoClaimSeed(ctx context.Context, op claimOp) (bool, error) { |
| + ctx = withDemoClaimOperation(ctx, op.ID) |
| + ready, err := func() (bool, error) { |
| + defer s.lockApp(op.Target.Sqid, op.Target.App)() |
| + return s.requestDemoClaimSeedAbort(ctx, op) |
| + }() |
| + if err != nil || !ready { |
| + return false, err |
| + } |
| + if err = s.finishSeed(ctx, op.Target.Sqid, op.Target.App, op.Target.Host, op.Target.SeedID); err != nil { |
| + return false, err |
| + } |
| + return true, nil |
| +} |
| + |
| +func (s *Server) requestDemoClaimSeedAbort(ctx context.Context, op claimOp) (bool, error) { |
| + ctx = withDemoClaimOperation(ctx, op.ID) |
| + fresh, err := s.demoClaimSeedOperation(ctx, op) |
| + if err != nil { |
| + return false, err |
| + } |
| + if !slices.Contains([]string{"reserved", "freezing", "copying", "verifying", "aborting"}, fresh.Phase) { |
| + return false, ErrDemoToken |
| + } |
| + rec, _, err := s.readRecord(ctx, op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return true, nil |
| + } |
| + if err != nil { |
| + return false, err |
| + } |
| + if !demoClaimRecordMatches(rec, op) { |
| + return false, ErrDemoToken |
| + } |
| + if rec.Seed.State == seeds.StateRolledBack { |
| + return true, nil |
| + } |
| + if rec.Seed.State == seeds.StateAborted { |
| + return false, nil |
| + } |
| + _, err = provision.SetRecordSeed(ctx, s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Target.Host, func(r *provision.Record) error { |
| + if !demoClaimRecordMatches(r, op) { |
| + return provision.ErrSeedConflict |
| + } |
| + return provision.SeedAbort(op.Target.SeedID)(r) |
| + }) |
| + if err == nil { |
| + s.bumpSerial(ctx) |
| + } |
| + return false, err |
| +} |
diff --git a/internal/console/demo_claim_seed_test.go b/internal/console/demo_claim_seed_test.go| new file mode 100644 |
| index 000000000..e02c9b819 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_seed_test.go |
| @@ -0,0 +1,266 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "github.com/carlosframework/platform/internal/status" |
| + "net/http/httptest" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDemoClaimSeedCommit(t *testing.T) { |
| + t.Run("verifyToken", func(t *testing.T) { |
| + s, _, _ := claimTestServer(t) |
| + id, _ := demobuild.NewJobID() |
| + token, err := s.demoClaimVerifyToken(id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mac := hmac.New(sha256.New, s.cfg.Key.Seed()) |
| + mac.Write([]byte("carlos demo claim verify v1\n" + id)) |
| + want := base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) |
| + if token != want { |
| + t.Fatal("wrong derivation") |
| + } |
| + again, err := s.demoClaimVerifyToken(id) |
| + if err != nil || again != token { |
| + t.Fatal("retry changed token") |
| + } |
| + old := seeds.HashToken(token) |
| + s.cfg.Key = ed25519.NewKeyFromSeed(make([]byte, 32)) |
| + changed, err := s.demoClaimVerifyToken(id) |
| + if err != nil || seeds.TokenMatches(old, changed) { |
| + t.Fatal("key rotation bypassed gate") |
| + } |
| + }) |
| + t.Run("oldReaders", func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.demoClaimTestEnabled = true |
| + publishSeedsFloorFx(t, fx, "v0.27.0") |
| + seedReadyBox(t, fx, "box-a", "", 1, "v0.27.0", "v0.27.0", "nested", false) |
| + if err := fx.srv.demoClaimSeedReady(t.Context(), ""); err == nil { |
| + t.Fatal("old reader admitted") |
| + } |
| + }) |
| +} |
| + |
| +func claimSeedReadyFixture(t *testing.T, s *Server, protocol int, capable bool, prev string) { |
| + t.Helper() |
| + st := s.cfg.Releases |
| + if err := seeds.PublishFloor(t.Context(), st, seeds.Floor{Min: 2, MinRelease: "v1.0.0"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + caps := []string{"lifetimes-1"} |
| + if capable { |
| + caps = append(caps, seeds.DemoClaimCapability) |
| + } |
| + raw, _ := json.Marshal(map[string]any{"v": 1, "box": "box-a", "eip": "192.0.2.10", "placement": s.cfg.Region, "hibernation_configured": true, "capabilities": caps, "hosts": map[string]any{}, "seeds_protocol": protocol, "seeds_floor_min_release": "v1.0.0", "prev_release": "v1.0.0", "prev_seeds_allowed_for": prev}) |
| + key := "control/edges/box-a.json" |
| + _, etag, _ := st.Get(t.Context(), key) |
| + if _, err := st.Put(t.Context(), key, raw, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := status.CollectBox(nil, status.Probes{Release: "v1.0.0", Platform: "linux-arm64", Layout: &status.LayoutReport{Mode: "nested"}}, time.Now()) |
| + b.Label = "box-a" |
| + if err := status.WriteBox(t.Context(), st, b); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func claimSeedConsole(t *testing.T) (*Server, claimOp) { |
| + t.Helper() |
| + s, _, token := claimTestServer(t) |
| + f, _ := claimProved(t, s, token, "shop@example.com") |
| + a := claimAccount(t, s, 501, f.Person, RoleOwner) |
| + op, err := s.reserveDemoClaim(t.Context(), f, a, regionReq{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + claimSeedReadyFixture(t, s, 2, true, "v1.0.0") |
| + root := t.TempDir() |
| + s.cfg.SeedData = release.NewDirStore(root) |
| + s.cfg.HibernateBucket = "data-test" |
| + s.cfg.HibernatePrefix = "instances" |
| + s.dbReplica = func(_ context.Context, prefix string) (replicaReader, error) { |
| + return lsfile.NewReplicaClient(filepath.Join(root, prefix)), nil |
| + } |
| + return s, op |
| +} |
| +func TestDemoClaimFreshSeed(t *testing.T) { |
| + s, op := claimSeedConsole(t) |
| + rec, err := s.createDemoClaimSeed(t.Context(), op) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + acct, err := s.store.AccountByID(op.Target.AccountID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if count, err := s.runningThings(t.Context(), acct); err != nil || count != 2 { |
| + t.Fatalf("count after reserved record: %d %v", count, err) |
| + } |
| + if rec.Host != op.Target.Host || rec.Demo != nil || rec.DemoClaim != nil || rec.Region != op.Target.Region || rec.Seed.ClaimID != op.ID { |
| + t.Fatalf("record: %+v", rec) |
| + } |
| + again, err := s.createDemoClaimSeed(t.Context(), op) |
| + if err != nil || again.Seed.ID != rec.Seed.ID { |
| + t.Fatalf("retry %v %v", again, err) |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='copying' WHERE id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + snapshot := []byte("checked private snapshot bytes") |
| + sum := sha256.Sum256(snapshot) |
| + sha := hex.EncodeToString(sum[:]) |
| + path := filepath.Join(t.TempDir(), "snapshot.db") |
| + if err := os.WriteFile(path, snapshot, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + for range 2 { |
| + if err := s.publishDemoClaimSeed(t.Context(), op, path, sha, int64(len(snapshot))); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + rec, _, err = s.readRecord(t.Context(), op.Target.Sqid, op.Target.App, op.Target.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + token, err := s.demoClaimSeedVerifyToken(t.Context(), op) |
| + if err != nil || !seeds.TokenMatches(rec.Seed.VerifyHash, token) { |
| + t.Fatalf("verify %v", err) |
| + } |
| + s.cfg.Key = ed25519.NewKeyFromSeed(make([]byte, 32)) |
| + if _, err := s.demoClaimSeedVerifyToken(t.Context(), op); err == nil { |
| + t.Fatal("key rotation bypassed proof") |
| + } |
| + if err := s.publishDemoClaimSeed(t.Context(), op, path, sha, int64(len(snapshot))); err == nil { |
| + t.Fatal("rotated key republished hash") |
| + } |
| + if rec.Seed.State != seeds.StateReady { |
| + t.Fatalf("state %s", rec.Seed.State) |
| + } |
| +} |
| +func TestDemoClaimSeedCommitReadiness(t *testing.T) { |
| + s, _, _ := claimTestServer(t) |
| + for _, c := range []struct { |
| + name string |
| + protocol int |
| + capable bool |
| + prev string |
| + ok bool |
| + }{ |
| + {"ready", 2, true, "v1.0.0", true}, {"oldCurrent", 1, true, "v1.0.0", false}, {"oldIngress", 2, false, "v1.0.0", false}, {"oldRollback", 2, true, "", false}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + claimSeedReadyFixture(t, s, c.protocol, c.capable, c.prev) |
| + err := s.demoClaimSeedReady(t.Context(), s.cfg.Region) |
| + if (err == nil) != c.ok { |
| + t.Fatalf("readiness: %v", err) |
| + } |
| + }) |
| + } |
| +} |
| +func TestDemoClaimSeedCommitCleanup(t *testing.T) { |
| + for _, mode := range []string{"matching", "heldLease", "otherLifetime", "committed", "lifetimeOn"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, op := claimSeedConsole(t) |
| + ctx := t.Context() |
| + if mode == "lifetimeOn" { |
| + s.cutover = newCutoverGate(time.Now) |
| + s.cutover.state = cutoverOn |
| + s.judge = provision.NewLifetimeJudge() |
| + ctx = onCtx(t, s) |
| + } |
| + rec, err := s.createDemoClaimSeed(ctx, op) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='aborting' WHERE id=?`, op.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, step := range []func(*provision.Record) error{provision.SeedAbort(rec.Seed.ID), provision.SeedRolledBack(rec.Seed.ID)} { |
| + if _, err := provision.SetRecordSeed(t.Context(), s.cfg.Releases, rec.Account, rec.App, rec.Host, step); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + key := "instances/" + rec.Host + "/0000/0000000000000001-0000000000000001.ltx" |
| + other := "instances/other.example.com/0000/file.ltx" |
| + for _, k := range []string{key, other} { |
| + if _, err := s.cfg.SeedData.Put(t.Context(), k, []byte("replica"), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + bucket := leasetest.NewVersionedBucket() |
| + bucket.AddBucket(s.cfg.HibernateBucket) |
| + handler, _ := leasetest.NewS3Server(bucket) |
| + server := httptest.NewServer(handler) |
| + t.Cleanup(server.Close) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("CARLOS_S3_ENDPOINT", server.URL) |
| + s.cfg.HibernateRegion = "test-region" |
| + if mode == "lifetimeOn" && rec.Incarnation == 0 { |
| + t.Fatal("lifetime not allocated") |
| + } |
| + if mode == "heldLease" { |
| + bucket.Put(s.cfg.HibernateBucket, "instances/"+rec.Host+"/lock.json", []byte(fmt.Sprintf(`{"generation":1,"expires_at":%q,"owner":"box-a"}`, time.Now().Add(time.Hour).UTC().Format(time.RFC3339Nano)))) |
| + } |
| + if mode == "otherLifetime" { |
| + _, err = s.store.db.Exec(`UPDATE apps SET lifetime='other' WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if mode == "committed" { |
| + _, err = s.store.db.Exec(`UPDATE demo_claim_ops SET phase='committed' WHERE id=?`, op.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + done, err := s.abortDemoClaimSeed(ctx, op) |
| + if mode == "matching" || mode == "lifetimeOn" { |
| + if err != nil || !done { |
| + t.Fatalf("cleanup: %v %v", done, err) |
| + } |
| + if _, _, err := s.cfg.SeedData.Get(t.Context(), key); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("replica retained") |
| + } |
| + if _, _, err := s.readRecord(t.Context(), rec.Account, rec.App, rec.Host); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal("record retained") |
| + } |
| + if done, err := s.abortDemoClaimSeed(ctx, op); !done || err != nil { |
| + t.Fatalf("retry: %v %v", done, err) |
| + } |
| + } else { |
| + if err == nil || done { |
| + t.Fatalf("unsafe finish: %v %v", done, err) |
| + } |
| + if _, _, err := s.cfg.SeedData.Get(t.Context(), key); err != nil { |
| + t.Fatal("foreign or live data deleted") |
| + } |
| + } |
| + if _, _, err := s.cfg.SeedData.Get(t.Context(), other); err != nil { |
| + t.Fatal("unrelated replica deleted") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/seedfinish.go b/internal/console/seedfinish.go| index bffc7ae1b..cf6491ee2 100644 |
| --- a/internal/console/seedfinish.go |
| +++ b/internal/console/seedfinish.go |
| @@ -84,6 +84,31 @@ func (s *Server) finishSeedOnce(ctx context.Context, sqid, app, host, seedID str |
| if rec.Seed == nil || rec.Seed.ID != seedID || rec.Seed.State != seeds.StateRolledBack { |
| return nil |
| } |
| + if rec.Seed.DemoClaim() { |
| + defer s.lockApp(sqid, app)() |
| + defer s.lockHostname(host)() |
| + rec, etag, err = s.readRecord(ctx, sqid, app, host) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if rec.Seed == nil || rec.Seed.ID != seedID || rec.Seed.State != seeds.StateRolledBack || !rec.Seed.DemoClaim() { |
| + return ErrDemoToken |
| + } |
| + op, err := scanDemoClaimOp(s.store.db.QueryRowContext(ctx, `SELECT `+demoClaimOpColumns+` FROM demo_claim_ops WHERE id=?`, rec.Seed.ClaimID)) |
| + if err != nil { |
| + return err |
| + } |
| + if !demoClaimRecordMatches(rec, op) || op.Phase != "aborting" { |
| + return ErrDemoToken |
| + } |
| + if _, err = s.demoClaimSeedOperation(ctx, op); err != nil { |
| + return err |
| + } |
| + ctx = withDemoClaimOperation(ctx, op.ID) |
| + } |
| // Checked before anything is destroyed: without it the store would be |
| // torn down and every later finish fail with the record holding the |
| // host. |
| @@ -96,7 +121,7 @@ func (s *Server) finishSeedOnce(ctx context.Context, sqid, app, host, seedID str |
| if err := s.cfg.SeedData.Delete(ctx, seeds.SnapshotKey(host, seedID)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| return fmt.Errorf("delete the snapshot of seed %s of %s: %w", seedID, host, err) |
| } |
| - if rec.Seed.Kind == seeds.KindReplica { |
| + if rec.Seed.Kind == seeds.KindReplica || rec.Seed.DemoClaim() { |
| var gone bool |
| if etag, gone, err = s.deleteSeedReplica(ctx, rec, etag); err != nil { |
| return err |
| @@ -110,7 +135,11 @@ func (s *Server) finishSeedOnce(ctx context.Context, sqid, app, host, seedID str |
| // Admitted on: the record retires through its tombstone, bound to |
| // the last read that saw this seed (lifetimes_retire.go). A CAS |
| // conflict is finishSeed's one re-read. |
| - if err := s.retireRecordWithLifetime(ctx, sqid, app, host, retireExpectETag(etag)); err != nil { |
| + retire := s.retireRecordWithLifetime |
| + if rec.Seed.DemoClaim() { |
| + retire = s.retireRecordWithLifetimeLocked |
| + } |
| + if err := retire(ctx, sqid, app, host, retireExpectETag(etag)); err != nil { |
| return fmt.Errorf("retire the record of %s: %w", host, err) |
| } |
| } else if err := release.DeleteIfMatch(ctx, s.cfg.Releases, provision.RecordKey(sqid, app, host), etag); err != nil && !errors.Is(err, os.ErrNotExist) { |
diff --git a/internal/console/seedfloor.go b/internal/console/seedfloor.go| index 7e0c5cc00..80a6b1668 100644 |
| --- a/internal/console/seedfloor.go |
| +++ b/internal/console/seedfloor.go |
| @@ -189,7 +189,7 @@ func (s *Server) handleAPISystemSeedsFloor(w http.ResponseWriter, r *http.Reques |
| jsonError(w, http.StatusBadRequest, "min_release must be a release such as v0.27.0") |
| return |
| } |
| - err := seeds.PublishFloor(r.Context(), s.cfg.Releases, seeds.Floor{Min: seeds.RequiredProtocol, MinRelease: req.MinRelease}) |
| + err := seeds.PublishFloor(r.Context(), s.cfg.Releases, seeds.Floor{Min: seeds.ProtocolVersion, MinRelease: req.MinRelease}) |
| var lower *seeds.FloorLowerError |
| switch { |
| case errors.As(err, &lower): |
diff --git a/internal/console/seedfloor_test.go b/internal/console/seedfloor_test.go| index c11f72c42..abdbedd06 100644 |
| --- a/internal/console/seedfloor_test.go |
| +++ b/internal/console/seedfloor_test.go |
| @@ -348,7 +348,7 @@ func TestSeedsFloorDoorIsForSystemOperators(t *testing.T) { |
| t.Fatalf("a lower floor = %d %v, want 409 naming v0.27.0", st, out) |
| } |
| f, err := seeds.ReadFloor(context.Background(), fx.rel) |
| - if err != nil || f == nil || f.MinRelease != "v0.27.0" || f.Min != seeds.RequiredProtocol { |
| + if err != nil || f == nil || f.MinRelease != "v0.27.0" || f.Min != seeds.ProtocolVersion { |
| t.Fatalf("floor = %+v, %v", f, err) |
| } |
| } |
diff --git a/internal/console/seedsweep.go b/internal/console/seedsweep.go| index 61fa26107..da91b89c4 100644 |
| --- a/internal/console/seedsweep.go |
| +++ b/internal/console/seedsweep.go |
| @@ -95,6 +95,10 @@ func (s *Server) seedsIteration(ctx context.Context) { |
| // about 8 minutes, and an overrun costs a copy, never data. |
| func seedStale(seed *provision.SeedSource, now time.Time) bool { |
| switch { |
| + // Claim expiry belongs to the operation coordinator: it records aborting |
| + // before the seed changes, and never resumes a source after commit. |
| + case seed != nil && seed.DemoClaim(): |
| + return false |
| case seed == nil: |
| return false |
| case seed.Kind == seeds.KindReplica && seed.State == seeds.StateReserving: |
diff --git a/internal/edge/demo_claim_seed_test.go b/internal/edge/demo_claim_seed_test.go| new file mode 100644 |
| index 000000000..70b026700 |
| --- /dev/null |
| +++ b/internal/edge/demo_claim_seed_test.go |
| @@ -0,0 +1,64 @@ |
| +package edge |
| + |
| +import ( |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "net/http" |
| + "testing" |
| +) |
| + |
| +func TestDemoClaimSeedGate(t *testing.T) { |
| + srv, back := newGateBackend(t, "snapshot app", "public, max-age=60") |
| + reg := openReg(t) |
| + token, hash, _ := seeds.NewVerifyToken() |
| + id, _ := seeds.NewID() |
| + claim, _ := demobuild.NewJobID() |
| + rt := registry.Route{Host: gateHost, Kind: "instance", Addr: srv.Listener.Addr().String(), App: "shop", Account: "bbw", Status: "ready", ImportGate: hash, SeedSource: seeds.RowSeed{ID: id, Kind: seeds.KindDemoClaim, ClaimID: claim, State: seeds.StatePlaced}.Encode()} |
| + if err := reg.Upsert(rt); err != nil { |
| + t.Fatal(err) |
| + } |
| + upsertAlias(t, reg, gateAliasHost, gateHost) |
| + e, err := New(reg, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + e.EnableCache(NewCache(DefaultCacheMaxEntries, DefaultCacheMaxBodyBytes)) |
| + targetSrv, _ := newGateBackend(t, "other app", "") |
| + if err := reg.Upsert(registry.Route{Host: "target.example.com", Kind: "service", Addr: targetSrv.Listener.Addr().String(), App: "shop", Account: "bbw", Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + upsertPath(t, reg, gateHost, "other", "target.example.com") |
| + upsertPath(t, reg, "target.example.com", "claim", gateHost) |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []struct{ host, path string }{{gateHost, "/other"}, {"target.example.com", "/claim"}} { |
| + if r := gateDo(e, http.MethodGet, p.host, p.path, token); r.Code != 503 { |
| + t.Fatalf("path escaped gate: %d", r.Code) |
| + } |
| + } |
| + |
| + for _, c := range []struct{ name, host, method, token string }{ |
| + {"GETWithoutToken", gateHost, http.MethodGet, ""}, {"POST", gateHost, http.MethodPost, token}, {"alias", gateAliasHost, http.MethodGet, token}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + r := gateDo(e, c.method, c.host, "/up", c.token) |
| + if r.Code != 503 { |
| + t.Fatalf("code %d", r.Code) |
| + } |
| + }) |
| + } |
| + if n, _ := back.seen(); n != 0 { |
| + t.Fatal("gate reached app") |
| + } |
| + for range 2 { |
| + if r := gateDo(e, http.MethodGet, gateHost, "/up", token); r.Code != 200 || r.Body.String() != "snapshot app" { |
| + t.Fatalf("verify: %d %s", r.Code, r.Body) |
| + } |
| + } |
| + if n, h := back.seen(); n != 2 || len(h) != 0 { |
| + t.Fatalf("cache or token leak: %d %v", n, h) |
| + } |
| +} |
diff --git a/internal/edge/importgate.go b/internal/edge/importgate.go| index eaa8956b7..4f27b00be 100644 |
| --- a/internal/edge/importgate.go |
| +++ b/internal/edge/importgate.go |
| @@ -42,7 +42,11 @@ func (e *Edge) importGateAdmit(w http.ResponseWriter, r *http.Request, host stri |
| if rt.ImportGate == "" && front.ImportGate == "" { |
| return true |
| } |
| - if front.Host == rt.Host && r.Method == http.MethodGet && seeds.TokenMatches(rt.ImportGate, token) { |
| + claimExact := true |
| + if src, err := seeds.ParseRowSeed(rt.SeedSource); err != nil || (src != nil && src.Kind == seeds.KindDemoClaim && host != rt.Host) { |
| + claimExact = false |
| + } |
| + if claimExact && front.Host == rt.Host && r.Method == http.MethodGet && seeds.TokenMatches(rt.ImportGate, token) { |
| return true |
| } |
| w.Header().Set("Retry-After", "5") |
diff --git a/internal/host/demo_claim_seed_test.go b/internal/host/demo_claim_seed_test.go| new file mode 100644 |
| index 000000000..f6a4197c3 |
| --- /dev/null |
| +++ b/internal/host/demo_claim_seed_test.go |
| @@ -0,0 +1,40 @@ |
| +package host |
| + |
| +import ( |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDemoClaimSeedGateStaleWake(t *testing.T) { |
| + store := release.NewDirStore(t.TempDir()) |
| + id, _ := seeds.NewID() |
| + claim, _ := demobuild.NewJobID() |
| + rec := provision.Record{Schema: 1, Host: "shop.example.com", App: "shop", Account: "bae", Channel: "edge", CreatedAt: time.Now(), Seed: &provision.SeedSource{ID: id, Kind: seeds.KindDemoClaim, ClaimID: claim, State: seeds.StateReady, SHA256: strings.Repeat("a", 64), Bytes: 4096, VerifyHash: strings.Repeat("b", 64)}} |
| + if err := provision.CreateRecord(t.Context(), store, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + row := registry.Route{Host: rec.Host, App: rec.App, Account: rec.Account, SeedSource: provision.SeedColumn(rec)} |
| + src, _ := seeds.ParseRowSeed(row.SeedSource) |
| + check := claimSeedWakeHook(store, nil) |
| + if err := check(t.Context(), row, src); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := provision.SetRecordSeed(t.Context(), store, rec.Account, rec.App, rec.Host, provision.SeedAbort(id)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := check(t.Context(), row, src); err == nil { |
| + t.Fatal("stale route started after durable abort") |
| + } |
| + if err := store.Delete(t.Context(), provision.RecordKey(rec.Account, rec.App, rec.Host)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := check(t.Context(), row, src); err == nil { |
| + t.Fatal("stale route started after cleanup") |
| + } |
| +} |
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go| index 07b75e09f..62d493b77 100644 |
| --- a/internal/host/edgesfile.go |
| +++ b/internal/host/edgesfile.go |
| @@ -23,6 +23,7 @@ import ( |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| "github.com/carlosframework/platform/internal/domains" |
| ) |
| @@ -199,9 +200,9 @@ const capLifetimes1 = "lifetimes-1" |
| // offline-move-1 is added per pass by withOfflineCapability. |
| func edgesFileCapabilities(getenv func(string) string) []string { |
| if !regionHAEnabled(getenv) { |
| - return []string{capLifetimes1, edgesfile.NamesCapability} |
| + return []string{capLifetimes1, edgesfile.NamesCapability, seeds.DemoClaimCapability} |
| } |
| - return []string{capLifetimes1, capRegionHA1, edgesfile.NamesCapability} |
| + return []string{capLifetimes1, capRegionHA1, edgesfile.NamesCapability, seeds.DemoClaimCapability} |
| } |
| // withOfflineCapability is caps with offline-move-1 and offline-stage-1 when |
diff --git a/internal/host/edgesfile_test.go b/internal/host/edgesfile_test.go| index 9d60b04bd..631809823 100644 |
| --- a/internal/host/edgesfile_test.go |
| +++ b/internal/host/edgesfile_test.go |
| @@ -1356,13 +1356,13 @@ func TestEdgesFileCapabilityFollowsTheFlag(t *testing.T) { |
| } |
| } |
| // lifetimes-1 is the lifetimes cutover's box floor, published always. |
| - if got := edgesFileCapabilities(env("")); !slices.Equal(got, []string{"lifetimes-1", "names-2"}) { |
| + if got := edgesFileCapabilities(env("")); !slices.Equal(got, []string{"lifetimes-1", "names-2", "demo-claim-seed-v1"}) { |
| t.Fatalf("unset: %v", got) |
| } |
| - if got := edgesFileCapabilities(env("1")); !slices.Equal(got, []string{"lifetimes-1", "region-ha-1", "names-2"}) { |
| + if got := edgesFileCapabilities(env("1")); !slices.Equal(got, []string{"lifetimes-1", "region-ha-1", "names-2", "demo-claim-seed-v1"}) { |
| t.Fatalf("set: %v", got) |
| } |
| - if got := edgesFileCapabilities(env("0")); !slices.Equal(got, []string{"lifetimes-1", "names-2"}) { |
| + if got := edgesFileCapabilities(env("0")); !slices.Equal(got, []string{"lifetimes-1", "names-2", "demo-claim-seed-v1"}) { |
| t.Fatalf("\"0\" is off: %v", got) |
| } |
| } |
| @@ -1386,8 +1386,8 @@ func TestEdgesFilePublishesTheLifetimesFloor(t *testing.T) { |
| t.Fatal(err) |
| } |
| var f edgesfile.PlacementView |
| - if err := json.Unmarshal(b1, &f); err != nil || !slices.Equal(f.Capabilities, []string{capLifetimes1, edgesfile.NamesCapability}) { |
| - t.Fatalf("capabilities = %v (%v), want [lifetimes-1 names-2]", f.Capabilities, err) |
| + if err := json.Unmarshal(b1, &f); err != nil || !slices.Equal(f.Capabilities, []string{capLifetimes1, edgesfile.NamesCapability, "demo-claim-seed-v1"}) { |
| + t.Fatalf("capabilities = %v (%v), want [lifetimes-1 names-2 demo-claim-seed-v1]", f.Capabilities, err) |
| } |
| if err := edgesFileWrite(context.Background(), s, reg, ident, "203.0.113.10", &last, false); err != nil { |
| t.Fatal(err) |
diff --git a/internal/host/seedwiring.go b/internal/host/seedwiring.go| index 760f8413a..a96ea3f81 100644 |
| --- a/internal/host/seedwiring.go |
| +++ b/internal/host/seedwiring.go |
| @@ -160,6 +160,7 @@ func wireSeedPlacement(eb *activator.ExecBackend, claimArmed bool, openData, ope |
| } |
| eb.Seeds = storeSeedObjects{data} |
| eb.OnSeedPlaced = seedPlacedHook(deploy, data, box.Judge) |
| + eb.OnDemoClaimSeedWake = claimSeedWakeHook(deploy, box.Judge) |
| h := &provision.SeedHooks{Data: data} |
| if !claimArmed { |
| h.NestedOK = eb.NestedOK |
| @@ -256,3 +257,23 @@ func deleteReplica(data release.Store, prefix string) func(ctx context.Context, |
| return nil |
| } |
| } |
| + |
| +// The caller holds the destination lease before this read. Abort cleanup |
| +// cannot delete its replica while that lease is held, and a wake that takes |
| +// the lease after an abort observes the terminal record before any exec. |
| +func claimSeedWakeHook(deploy release.Store, judge *provision.LifetimeJudge) func(context.Context, registry.Route, *seeds.RowSeed) error { |
| + return func(ctx context.Context, rt registry.Route, src *seeds.RowSeed) error { |
| + rec, err := judgedRecord(ctx, deploy, judge, rt.Account, rt.App, rt.Host) |
| + if err != nil { |
| + return err |
| + } |
| + if rec == nil || rec.Seed == nil || !rec.Seed.DemoClaim() || rec.Seed.ID != src.ID || rec.Seed.ClaimID != src.ClaimID || rec.Incarnation != rt.Incarnation || rec.MoveSeq != rt.ServingSeq { |
| + return provision.ErrSeedConflict |
| + } |
| + switch rec.Seed.State { |
| + case seeds.StateReady, seeds.StatePlaced, seeds.StateCommitted: |
| + return nil |
| + } |
| + return provision.ErrSeedConflict |
| + } |
| +} |
diff --git a/internal/provision/demo_claim_seed.go b/internal/provision/demo_claim_seed.go| new file mode 100644 |
| index 000000000..a14a5f88b |
| --- /dev/null |
| +++ b/internal/provision/demo_claim_seed.go |
| @@ -0,0 +1,188 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "os" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +func (s *SeedSource) DemoClaim() bool { return s != nil && s.Kind == seeds.KindDemoClaim } |
| + |
| +func validateDemoClaimSeed(rec Record) error { |
| + s := rec.Seed |
| + if s == nil { |
| + return nil |
| + } |
| + if !s.DemoClaim() { |
| + if s.ClaimID != "" { |
| + return fmt.Errorf("%w: claim id on another seed kind", ErrSeedConflict) |
| + } |
| + return nil |
| + } |
| + if !seeds.ValidID(s.ID) || !demobuild.ValidJobID(s.ClaimID) || s.From != "" || s.TXID != "" || s.Replaces != "" || |
| + rec.Demo != nil || rec.DemoClaim != nil || rec.HA || rec.Runtime != "" || rec.KindOrDefault() != "instance" || !rec.DerivesPaths() { |
| + return fmt.Errorf("%w: invalid fresh claim seed", ErrSeedConflict) |
| + } |
| + if s.State != seeds.StateCommitted { |
| + _, fleet := registry.FleetPlacement(rec.Region) |
| + if fleet || !rec.HibernateOrDefault() || rec.Unit != "" || rec.Role != "" || len(rec.Replicas) != 0 || rec.Pool != "" || rec.FleetBox != "" || rec.ReplicaAssignment != nil || rec.Move != nil || rec.ActiveRun.Open() || rec.Interactive != nil { |
| + return fmt.Errorf("%w: unsupported claim placement", ErrSeedConflict) |
| + } |
| + } |
| + switch s.State { |
| + case seeds.StateReserving: |
| + if s.SHA256 != "" || s.Bytes != 0 || s.VerifyHash != "" { |
| + return fmt.Errorf("%w: reserving claim has snapshot", ErrSeedConflict) |
| + } |
| + case seeds.StateReady, seeds.StatePlaced, seeds.StateCommitted: |
| + if !demobuild.ValidDigest(s.SHA256) || s.Bytes <= 0 || s.Bytes > 268435456 || !demobuild.ValidDigest(s.VerifyHash) { |
| + return fmt.Errorf("%w: invalid claim snapshot", ErrSeedConflict) |
| + } |
| + case seeds.StateAborted, seeds.StateRolledBack: |
| + default: |
| + return fmt.Errorf("%w: invalid claim state", ErrSeedConflict) |
| + } |
| + return nil |
| +} |
| + |
| +func SeedPublishDemoClaim(id, claimID, sha string, bytes int64, verifyHash string) func(*Record) error { |
| + return func(rec *Record) error { |
| + if err := seedIn(rec, id, seeds.KindDemoClaim, seeds.StateReserving); err != nil { |
| + return err |
| + } |
| + if rec.Seed.ClaimID != claimID { |
| + return ErrSeedConflict |
| + } |
| + next := *rec |
| + next.Seed = cloneSeed(rec.Seed) |
| + next.Seed.State, next.Seed.SHA256, next.Seed.Bytes, next.Seed.VerifyHash = seeds.StateReady, sha, bytes, verifyHash |
| + if err := validateDemoClaimSeed(next); err != nil { |
| + return err |
| + } |
| + rec.Seed = next.Seed |
| + return nil |
| + } |
| +} |
| +func SeedCommitDemoClaim(id, claimID string) func(*Record) error { |
| + return func(rec *Record) error { |
| + if err := seedIn(rec, id, seeds.KindDemoClaim, seeds.StatePlaced); err != nil { |
| + return err |
| + } |
| + if rec.Seed.ClaimID != claimID { |
| + return ErrSeedConflict |
| + } |
| + if err := validateDemoClaimSeed(*rec); err != nil { |
| + return err |
| + } |
| + rec.Seed.State = seeds.StateCommitted |
| + return nil |
| + } |
| +} |
| + |
| +func demoClaimSeedRow(rec Record, row registry.Route) bool { |
| + src, err := seeds.ParseRowSeed(row.SeedSource) |
| + return err == nil && src != nil && src.Kind == seeds.KindDemoClaim && src.ID == rec.Seed.ID && src.ClaimID == rec.Seed.ClaimID && |
| + row.Host == rec.Host && row.Account == rec.Account && row.App == rec.App && row.Kind == "instance" && row.Provisioned && |
| + row.Incarnation == rec.Incarnation && row.ServingSeq == rec.MoveSeq && row.Runtime == "" && !row.IsDemo() && !row.HA && row.Unit == "" && row.Backing == "" && row.Tunnel == "" && row.Addr == "" && row.Addrs == "" |
| +} |
| + |
| +func demoClaimSeedGate(rec Record) string { |
| + if rec.Seed.State == seeds.StateCommitted { |
| + return "" |
| + } |
| + if rec.Seed.State == seeds.StateReady || rec.Seed.State == seeds.StatePlaced { |
| + return rec.Seed.VerifyHash |
| + } |
| + return registry.ImportGateClosed |
| +} |
| + |
| +// abortDemoClaimSeed closes the durable row before fencing it. No legacy |
| +// route or swap journal participates. A missing marker never authorizes data |
| +// removal; even that case requires a proven stop before acknowledging cleanup. |
| +func abortDemoClaimSeed(ctx context.Context, store release.Store, reg *registry.Registry, cfg ReconcileConfig, rec Record, row *registry.Route) { |
| + if cfg.DryRun || !rollbackArmed(cfg.Seeds) || cfg.ClaimEnabled { |
| + return |
| + } |
| + fail := func(err error) { log.Printf("provision: claim seed %s abort deferred: %v", rec.Seed.ID, err) } |
| + if row != nil { |
| + if !NestedPaths(cfg.DataDir, *row) { |
| + return |
| + } |
| + if !demoClaimSeedRow(rec, *row) { |
| + return |
| + } |
| + if err := reg.CompareSeedGate(*row, SeedColumn(rec), registry.ImportGateClosed); err != nil { |
| + fail(err) |
| + return |
| + } |
| + } |
| + h := cfg.Seeds |
| + gen, err := h.NextFenceGen() |
| + if err != nil || gen == 0 { |
| + return |
| + } |
| + proceed, err := h.FenceForRollback(ctx, rec.Host, gen) |
| + defer h.LiftFence(rec.Host, gen) |
| + if err != nil || !proceed { |
| + return |
| + } |
| + current, err := reg.Get(rec.Host) |
| + if err != nil { |
| + fail(err) |
| + return |
| + } |
| + if current != nil && (!demoClaimSeedRow(rec, *current) || current.ImportGate != registry.ImportGateClosed) { |
| + return |
| + } |
| + // Re-read authority after stop. A retry never acts on a changed lifetime, |
| + // operation or seed, even if a former pass had already closed its row. |
| + fresh, err := GetRecord(ctx, store, rec.Account, rec.App, rec.Host) |
| + if err != nil || fresh.Incarnation != rec.Incarnation || fresh.Seed == nil || fresh.Seed.ClaimID != rec.Seed.ClaimID || fresh.Seed.ID != rec.Seed.ID || (fresh.Seed.State != seeds.StateAborted && fresh.Seed.State != seeds.StateRolledBack) { |
| + return |
| + } |
| + db := NestedDBPath(cfg.DataDir, rec.Host) |
| + marker, err := h.LocalSeedID(db) |
| + if err != nil { |
| + fail(err) |
| + return |
| + } |
| + if marker == rec.Seed.ID { |
| + if err = h.RemoveLocal(registry.Route{Host: rec.Host, Kind: "instance", DBPath: db}); err != nil { |
| + fail(err) |
| + return |
| + } |
| + } |
| + if err = cfg.Seeds.Data.Delete(ctx, seeds.SnapshotKey(rec.Host, rec.Seed.ID)); err != nil && !errors.Is(err, os.ErrNotExist) { |
| + fail(err) |
| + return |
| + } |
| + if fresh.Seed.State == seeds.StateRolledBack { |
| + if current != nil { |
| + _, _ = reg.DeleteSeedRoute(*current) |
| + } |
| + return |
| + } |
| + _, err = SetRecordSeed(ctx, store, rec.Account, rec.App, rec.Host, func(r *Record) error { |
| + if r.Incarnation != rec.Incarnation || r.Seed == nil || r.Seed.ClaimID != rec.Seed.ClaimID { |
| + return ErrSeedConflict |
| + } |
| + return SeedRolledBack(rec.Seed.ID)(r) |
| + }) |
| + if err != nil { |
| + fail(err) |
| + return |
| + } |
| + if current != nil { |
| + _, err = reg.DeleteSeedRoute(*current) |
| + if err != nil { |
| + fail(err) |
| + } |
| + } |
| +} |
diff --git a/internal/provision/demo_claim_seed_test.go b/internal/provision/demo_claim_seed_test.go| new file mode 100644 |
| index 000000000..c2a34fad7 |
| --- /dev/null |
| +++ b/internal/provision/demo_claim_seed_test.go |
| @@ -0,0 +1,323 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "github.com/carlosframework/platform/internal/demo" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +func claimSeedRecord(t *testing.T, account string) Record { |
| + t.Helper() |
| + id, _ := seeds.NewID() |
| + claim, _ := demobuild.NewJobID() |
| + return Record{Schema: 1, Host: "shop.example.com", Slug: "shop", App: "shop", Account: account, Channel: "stable", Region: "ie", CreatedAt: time.Now(), Seed: &SeedSource{ID: id, ClaimID: claim, Kind: seeds.KindDemoClaim, State: seeds.StateReserving, By: "shop@example.com", At: time.Now()}} |
| +} |
| +func TestDemoClaimFreshSeed(t *testing.T) { |
| + t.Run("noExistingRoute", func(t *testing.T) { |
| + s := dirStore(t) |
| + account := writeAccountManifest(t, s, acctID, "Shop") |
| + if err := PutManifest(ctx, s, account, "shop", Manifest{Schema: 1, App: "shop", Domain: "example.com", Channel: "stable"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + rec := claimSeedRecord(t, account) |
| + if err := CreateRecord(ctx, s, rec); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := regWith(t) |
| + cfg := nestedSeedCfg(dirStore(t)) |
| + cfg.Pools = nil |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rt, _ := reg.Get(rec.Host); rt != nil { |
| + t.Fatal("reserving minted a route") |
| + } |
| + recp, err := SetRecordSeed(ctx, s, account, rec.App, rec.Host, SeedPublishDemoClaim(rec.Seed.ID, rec.Seed.ClaimID, strings.Repeat("a", 64), 4096, strings.Repeat("b", 64))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec = *recp |
| + if err := Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + rt := mustGet(t, reg, rec.Host) |
| + if rt.Kind != "instance" || rt.DBPath != NestedDBPath("/data", rec.Host) || rt.ImportGate != rec.Seed.VerifyHash || rt.Seed != "" || rt.SeedSource != SeedColumn(rec) { |
| + t.Fatalf("ungated or non-normal route: %+v", rt) |
| + } |
| + js, err := reg.ImportJournals() |
| + if err != nil || len(js) != 0 { |
| + t.Fatalf("claim entered import journal: %v %v", js, err) |
| + } |
| + if _, err = SetRecordSeed(ctx, s, account, rec.App, rec.Host, SeedCommitDemoClaim(rec.Seed.ID, rec.Seed.ClaimID)); !errors.Is(err, ErrSeedConflict) { |
| + t.Fatalf("commit before placement: %v", err) |
| + } |
| + if _, err = SetRecordSeed(ctx, s, account, rec.App, rec.Host, SeedPlace(rec.Seed.ID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if mustGet(t, reg, rec.Host).ImportGate == "" { |
| + t.Fatal("placement opened gate") |
| + } |
| + if _, err = SetRecordSeed(ctx, s, account, rec.App, rec.Host, SeedCommitDemoClaim(rec.Seed.ID, rec.Seed.ClaimID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = Reconcile(ctx, s, reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if mustGet(t, reg, rec.Host).ImportGate != "" { |
| + t.Fatal("commit kept gate") |
| + } |
| + }) |
| + for name, mutate := range map[string]func(*Record){ |
| + "demoDescriptor": func(r *Record) { |
| + r.Demo = &demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: r.Host, Lifetime: "life", ExpiresAt: time.Now().Add(time.Hour).Unix()} |
| + }, |
| + "fleet": func(r *Record) { r.Region = "fleet/example" }, |
| + "replaces": func(r *Record) { r.Seed.Replaces = "127.0.0.1:8080" }, |
| + "fakeTXID": func(r *Record) { r.Seed.TXID = "1" }, |
| + "replicaFrom": func(r *Record) { r.Seed.From = "source.example.com" }, |
| + "HA": func(r *Record) { r.HA = true }, |
| + "pool": func(r *Record) { r.Pool = "example" }, |
| + "nonhibernating": func(r *Record) { v := false; r.Hibernate = &v }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + r := claimSeedRecord(t, "bae") |
| + mutate(&r) |
| + if err := ValidateShape(r); err == nil { |
| + t.Fatal("unsupported shape admitted") |
| + } |
| + }) |
| + } |
| + t.Run("existingRoute", func(t *testing.T) { |
| + r := claimSeedRecord(t, "bae") |
| + r.Seed.State = seeds.StateReady |
| + r.Seed.SHA256 = strings.Repeat("a", 64) |
| + r.Seed.Bytes = 4096 |
| + r.Seed.VerifyHash = strings.Repeat("b", 64) |
| + row := registry.Route{Host: r.Host, Kind: "instance", Account: r.Account, App: r.App, Provisioned: true} |
| + if seedAction(r, &row, nestedSeedCfg(dirStore(t)), func() (bool, error) { return true, nil }, true) != seedSkip { |
| + t.Fatal("adopted unrelated row") |
| + } |
| + }) |
| +} |
| +func TestDemoClaimSeedCommit(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + r := claimSeedRecord(t, "bae") |
| + if err := CreateRecord(context.Background(), s, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + publish := SeedPublishDemoClaim(r.Seed.ID, r.Seed.ClaimID, strings.Repeat("a", 64), 4096, strings.Repeat("b", 64)) |
| + if _, err := SetRecordSeed(ctx, s, r.Account, r.App, r.Host, publish); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := SetRecordSeed(ctx, s, r.Account, r.App, r.Host, SeedCommitDemoClaim(r.Seed.ID, "wrong")); !errors.Is(err, ErrSeedConflict) { |
| + t.Fatal(err) |
| + } |
| + if !r.Seed.BlocksRun() { |
| + t.Fatal("run/schedule not blocked") |
| + } |
| + if _, err := SetRecordSeed(ctx, s, r.Account, r.App, r.Host, SeedPlace(r.Seed.ID)); err != nil { |
| + t.Fatal(err) |
| + } |
| + got, err := SetRecordSeed(ctx, s, r.Account, r.App, r.Host, SeedCommitDemoClaim(r.Seed.ID, r.Seed.ClaimID)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got.Seed.BlocksRun() || got.Seed.Unfinished() || got.Seed.MoveBlock() != "" { |
| + t.Fatal("committed is not ordinary") |
| + } |
| + if _, err := SetRecordSeed(ctx, s, r.Account, r.App, r.Host, SeedAbort(r.Seed.ID)); !errors.Is(err, ErrSeedConflict) { |
| + t.Fatalf("committed abort: %v", err) |
| + } |
| +} |
| + |
| +func TestDemoClaimSeedGate(t *testing.T) { |
| + r := claimSeedRecord(t, "bae") |
| + for _, state := range []string{seeds.StateReserving, seeds.StateReady, seeds.StatePlaced, seeds.StateAborted, seeds.StateRolledBack} { |
| + r.Seed.State = state |
| + if !r.ImportUncommitted() { |
| + t.Fatalf("run/schedule admits %s", state) |
| + } |
| + if err := RunAdmit(RunAdmission{ID: "run", By: "shop@example.com", Deadline: time.Now().Add(time.Minute)})(&r); !errors.Is(err, ErrRunImport) { |
| + t.Fatalf("run %s: %v", state, err) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoClaimSeedCommitAbort(t *testing.T) { |
| + for _, mode := range []string{"ours", "foreignMarker", "unprovenStop", "foreignLifetime", "foreignSeed", "retry"} { |
| + t.Run(mode, func(t *testing.T) { |
| + store := dirStore(t) |
| + data := dirStore(t) |
| + r := claimSeedRecord(t, "bae") |
| + r.Seed.State = seeds.StateAborted |
| + r.Seed.SHA256 = strings.Repeat("a", 64) |
| + r.Seed.Bytes = 4096 |
| + r.Seed.VerifyHash = strings.Repeat("b", 64) |
| + if err := CreateRecord(ctx, store, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + live := r |
| + live.Seed = cloneSeed(r.Seed) |
| + live.Seed.State = seeds.StateReady |
| + live.Seed.SHA256 = strings.Repeat("a", 64) |
| + live.Seed.Bytes = 4096 |
| + live.Seed.VerifyHash = strings.Repeat("b", 64) |
| + dataDir := t.TempDir() |
| + row := RouteFor(live, dataDir, "", true, nil) |
| + if mode == "foreignLifetime" { |
| + row.Incarnation = 9 |
| + } |
| + if mode == "foreignSeed" { |
| + col, _ := seeds.ParseRowSeed(row.SeedSource) |
| + col.ID, _ = seeds.NewID() |
| + row.SeedSource = col.Encode() |
| + } |
| + reg := regWith(t, row) |
| + row = *mustGet(t, reg, r.Host) |
| + cfg := nestedSeedCfg(data) |
| + cfg.Pools = nil |
| + cfg.DataDir = dataDir |
| + calls := []string{} |
| + marker := r.Seed.ID |
| + if mode == "foreignMarker" { |
| + marker = "other" |
| + } |
| + cfg.Seeds.NextFenceGen = func() (uint64, error) { return 7, nil } |
| + cfg.Seeds.FenceForRollback = func(context.Context, string, uint64) (bool, error) { |
| + calls = append(calls, "stop") |
| + current := mustGet(t, reg, r.Host) |
| + if current.ImportGate != registry.ImportGateClosed { |
| + t.Fatal("stop before gate closed") |
| + } |
| + return mode != "unprovenStop", nil |
| + } |
| + cfg.Seeds.LiftFence = func(string, uint64) {} |
| + cfg.Seeds.LocalSeedID = func(string) (string, error) { return marker, nil } |
| + removeCalls := 0 |
| + cfg.Seeds.RemoveLocal = func(registry.Route) error { |
| + calls = append(calls, "remove") |
| + removeCalls++ |
| + if mode == "retry" && removeCalls == 1 { |
| + return errors.New("local removal interrupted") |
| + } |
| + return nil |
| + } |
| + cfg.Seeds.RetireKey = func(string, string, string) error { calls = append(calls, "key"); return nil } |
| + cfg.Seeds.DeleteReplica = func(context.Context, string) error { |
| + t.Fatal("box deleted replica before console lease check") |
| + return nil |
| + } |
| + abortDemoClaimSeed(ctx, store, reg, cfg, r, &row) |
| + if mode == "retry" { |
| + row = *mustGet(t, reg, r.Host) |
| + if row.ImportGate != registry.ImportGateClosed { |
| + t.Fatal("retry opened gate") |
| + } |
| + abortDemoClaimSeed(ctx, store, reg, cfg, r, &row) |
| + } |
| + got, err := GetRecord(ctx, store, r.Account, r.App, r.Host) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + refused := mode == "unprovenStop" || mode == "foreignLifetime" || mode == "foreignSeed" |
| + if refused { |
| + if got.Seed.State != seeds.StateAborted { |
| + t.Fatal("unproven/foreign abort acknowledged") |
| + } |
| + if len(calls) > 1 { |
| + t.Fatal(calls) |
| + } |
| + return |
| + } |
| + if got.Seed.State != seeds.StateRolledBack { |
| + t.Fatalf("not cleaned: %+v", got.Seed) |
| + } |
| + if rt, _ := reg.Get(r.Host); rt != nil { |
| + t.Fatal("row retained") |
| + } |
| + want := []string{"stop", "remove"} |
| + if mode == "retry" { |
| + want = []string{"stop", "remove", "stop", "remove"} |
| + } |
| + if mode == "foreignMarker" { |
| + want = []string{"stop"} |
| + } |
| + if !reflect.DeepEqual(calls, want) { |
| + t.Fatalf("effects %v", calls) |
| + } |
| + if js, _ := reg.ImportJournals(); len(js) != 0 { |
| + t.Fatal("swap journal created") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimFreshSeedMintRace(t *testing.T) { |
| + r := claimSeedRecord(t, "bae") |
| + r.Seed.State = seeds.StateReady |
| + r.Seed.SHA256 = strings.Repeat("a", 64) |
| + r.Seed.Bytes = 4096 |
| + r.Seed.VerifyHash = strings.Repeat("b", 64) |
| + existing := registry.Route{Host: r.Host, Kind: "service", Account: "bab", App: "other", Addr: "127.0.0.1:8080"} |
| + reg := regWith(t, existing) |
| + before := *mustGet(t, reg, r.Host) |
| + if err := reg.CreateSeedRoute(RouteFor(r, "/data", "", true, nil)); err == nil { |
| + t.Fatal("overwrote route minted during reconcile") |
| + } |
| + after := *mustGet(t, reg, r.Host) |
| + if !reflect.DeepEqual(before, after) { |
| + t.Fatal("existing route changed") |
| + } |
| +} |
| + |
| +func TestDemoClaimFreshSeedQuietWatch(t *testing.T) { |
| + f := newViewFixture(t, true, true) |
| + r := claimSeedRecord(t, f.acct[0]) |
| + r.Host = "claim.shop.example.com" |
| + r.Slug = "claim" |
| + if err := CreateRecord(ctx, f.live, r); err != nil { |
| + t.Fatal(err) |
| + } |
| + v := f.view() |
| + mustRebuild(t, v) |
| + for range 3 { |
| + f.live.reset() |
| + mustRefresh(t, v) |
| + if got, want := f.live.got(), []string{"GetIfChanged " + release.ChangeIndexKey}; !reflect.DeepEqual(got, want) { |
| + t.Fatalf("new watch calls: %v", got) |
| + } |
| + } |
| +} |
| + |
| +func TestDemoClaimSeedCommitNeverUsesImportJournal(t *testing.T) { |
| + x := journaledImport(t, seeds.StateCommitted) |
| + r := x.rec |
| + r.Seed = cloneSeed(r.Seed) |
| + r.Seed.Kind = seeds.KindDemoClaim |
| + r.Seed.ClaimID, _ = demobuild.NewJobID() |
| + r.Seed.Replaces = "" |
| + key := RecordKey(r.Account, r.App, r.Host) |
| + _, etag, err := x.s.Get(ctx, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = x.s.Put(ctx, key, mustJSON(t, r), etag); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = Reconcile(ctx, x.s, x.reg, x.cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + x.untouched(t) |
| +} |
diff --git a/internal/provision/forward.go b/internal/provision/forward.go| index 1bb4d72d1..4f101d90f 100644 |
| --- a/internal/provision/forward.go |
| +++ b/internal/provision/forward.go |
| @@ -104,6 +104,8 @@ const ( |
| func decideForward(rec Record, owners map[string]string, disputed map[string]bool, trash trashState) (forwardDecision, string) { |
| fleet, placed := registry.FleetPlacement(rec.Region) |
| switch { |
| + case rec.Seed.DemoClaim() && rec.Seed.BlocksRun(): |
| + return forwardRefuse, "claim seeds cannot be forwarded" |
| case !placed: |
| return forwardRefuse, fmt.Sprintf("region %q is not a fleet placement", rec.Region) |
| case rec.Role == "replica": |
diff --git a/internal/provision/provision.go b/internal/provision/provision.go| index 5c94acbe3..ed7d3e585 100644 |
| --- a/internal/provision/provision.go |
| +++ b/internal/provision/provision.go |
| @@ -677,6 +677,9 @@ const MaxUpstreams = 16 |
| // value that reaches the row unvalidated is discovered months later as an |
| // adopt pass that restarted nothing (the `-backing unti` incident, cli.go). |
| func ValidateShape(rec Record) error { |
| + if err := validateDemoClaimSeed(rec); err != nil { |
| + return err |
| + } |
| if err := validateDemoRecord(rec); err != nil { |
| return err |
| } |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index e60cfacfe..ae0d57da2 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -604,6 +604,10 @@ func RouteFor(rec Record, dataDir, seed string, nested bool, policy *UpdatePolic |
| } |
| projectReplicaAssignment(&rt, rec) |
| stampDemoRoute(&rt, rec) |
| + if rec.Seed.DemoClaim() { |
| + rt.ImportGate = demoClaimSeedGate(rec) |
| + rt.Seed = "" |
| + } |
| if rec.Demo != nil && rec.DemoClaim != nil { |
| rt.Status, rt.HoldOp = "moving", "demo-claim/"+rec.DemoClaim.ID |
| } |
| @@ -1880,6 +1884,10 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| swapImport(ctx, s, reg, cfg, rec, row, mintLayout, p, policies.cols(rec)) |
| continue |
| case seedFinishAbort: |
| + if rec.Seed.DemoClaim() { |
| + abortDemoClaimSeed(ctx, s, reg, cfg, rec, row) |
| + continue |
| + } |
| // A --from seed this box minted is still running: its row |
| // goes first, and a later pass that finds no row rolls the |
| // seed back (seedreconcile.go). |
| @@ -2034,7 +2042,11 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| nr.Kind, rec.Host, rec.App, rec.Account, rec.Channel) |
| return nil |
| } |
| - if replacing != nil { |
| + if rec.Seed.DemoClaim() { |
| + if err := reg.CreateSeedRoute(nr); err != nil { |
| + return err |
| + } |
| + } else if replacing != nil { |
| changed, err := reg.ReplaceReplicaAssignment(*replacing, nr) |
| if err != nil { |
| log.Printf("provision: replace retired %s route %s: %v", replacing.Kind, rec.Host, err) |
| @@ -2160,6 +2172,15 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| // source write failed and the command cleared anyway, the row |
| // would hold neither, and a wake then could boot it empty. |
| sourceConverged := true |
| + if rec.Seed.DemoClaim() && (existing.SeedSource != SeedColumn(rec) || existing.ImportGate != demoClaimSeedGate(rec)) { |
| + if !cfg.DryRun { |
| + if err := reg.CompareSeedGate(existing, SeedColumn(rec), demoClaimSeedGate(rec)); err != nil { |
| + log.Printf("provision: converge claim seed %s: %v", rec.Host, err) |
| + return err |
| + } |
| + existing.SeedSource, existing.ImportGate = SeedColumn(rec), demoClaimSeedGate(rec) |
| + } |
| + } |
| if col := SeedColumn(rec); existing.SeedSource != col { |
| if cfg.DryRun { |
| log.Printf("provision: dry-run: would converge %s seed source", rec.Host) |
diff --git a/internal/provision/seed.go b/internal/provision/seed.go| index 67fbd29d8..419b67aae 100644 |
| --- a/internal/provision/seed.go |
| +++ b/internal/provision/seed.go |
| @@ -14,17 +14,18 @@ import ( |
| // SeedSource is a record's seed (seeded-instances spec §3.2). The run series |
| // declared its Kind and State; those keep their json tags. |
| type SeedSource struct { |
| - ID string `json:"id"` // random, minted with the seed; never reused |
| - Kind string `json:"kind"` // seeds.KindReplica | seeds.KindImport |
| - From string `json:"from,omitempty"` // replica: the source host |
| - TXID string `json:"txid,omitempty"` // replica: the TXID actually restored |
| - SHA256 string `json:"sha256"` // of snapshot.db |
| - Bytes int64 `json:"bytes"` |
| - State string `json:"state"` // seeds.State* |
| - Reason string `json:"reason,omitempty"` // set with refused, and with aborted when the abort names why |
| - By string `json:"by"` // the caller |
| - At time.Time `json:"at"` |
| - // import only: |
| + ClaimID string `json:"claim_id,omitempty"` |
| + ID string `json:"id"` // random, minted with the seed; never reused |
| + Kind string `json:"kind"` // seeds.KindReplica | seeds.KindImport | seeds.KindDemoClaim |
| + From string `json:"from,omitempty"` // replica: the source host |
| + TXID string `json:"txid,omitempty"` // replica: the TXID actually restored |
| + SHA256 string `json:"sha256"` // of snapshot.db |
| + Bytes int64 `json:"bytes"` |
| + State string `json:"state"` // seeds.State* |
| + Reason string `json:"reason,omitempty"` // set with refused, and with aborted when the abort names why |
| + By string `json:"by"` // the caller |
| + At time.Time `json:"at"` |
| + // Replaces is import-only. VerifyHash also gates a fresh demo claim. |
| Replaces string `json:"replaces,omitempty"` // the addr the swap replaces |
| VerifyHash string `json:"verify_hash,omitempty"` // sha256 of the verify token (§5.4) |
| } |
| @@ -69,13 +70,15 @@ func (s *SeedSource) Unfinished() bool { |
| return false |
| } |
| finished := (s.Kind == seeds.KindReplica && s.State == seeds.StatePlaced) || |
| - (s.Kind == seeds.KindImport && s.State == seeds.StateCommitted) |
| + ((s.Import() || s.DemoClaim()) && s.State == seeds.StateCommitted) |
| return !finished |
| } |
| // BlocksRun is run admission's predicate (run spec §5.1 step 9, codex |
| // R2-2): an import that is not committed refuses carlos run. |
| -func (s *SeedSource) BlocksRun() bool { return s.Import() && s.State != seeds.StateCommitted } |
| +func (s *SeedSource) BlocksRun() bool { |
| + return (s.Import() || s.DemoClaim()) && s.State != seeds.StateCommitted |
| +} |
| // MoveBlock is the move doors' and workers' predicate (spec §5.8): a |
| // --from seed moves only once placed, an import only once committed. |
| @@ -83,7 +86,7 @@ func (s *SeedSource) MoveBlock() string { |
| switch { |
| case s == nil: |
| return "" |
| - case s.Import(): |
| + case s.Import() || s.DemoClaim(): |
| if s.State != seeds.StateCommitted { |
| return SeedMoveUncommitted |
| } |
| @@ -186,6 +189,9 @@ func SeedSwapped(id string) func(*Record) error { |
| func SeedPlace(id string) func(*Record) error { |
| return func(rec *Record) error { |
| from := seeds.StateReady |
| + if rec.Seed.DemoClaim() && (rec.Seed.State == seeds.StatePlaced || rec.Seed.State == seeds.StateCommitted) { |
| + return seedIn(rec, id, seeds.KindDemoClaim, seeds.StatePlaced, seeds.StateCommitted) |
| + } |
| if rec.Seed.Import() { |
| from = seeds.StateSwapped |
| } |
| @@ -231,6 +237,9 @@ func SeedAbort(id string) func(*Record) error { return SeedAbortBecause(id, "") |
| func SeedAbortBecause(id, reason string) func(*Record) error { |
| return func(rec *Record) error { |
| from := []string{seeds.StateReserving, seeds.StateReady} |
| + if rec.Seed.DemoClaim() { |
| + from = append(from, seeds.StatePlaced) |
| + } |
| if rec.Seed.Import() { |
| from = []string{seeds.StateAwaitingUpload, seeds.StateUploaded, seeds.StateReady, |
| seeds.StateSwapped, seeds.StatePlaced, seeds.StateRefused} |
| @@ -238,10 +247,10 @@ func SeedAbortBecause(id, reason string) func(*Record) error { |
| if err := seedIn(rec, id, "", from...); err != nil { |
| return err |
| } |
| - if rec.Seed.Import() && rec.ActiveRun.Open() { |
| + if (rec.Seed.Import() || rec.Seed.DemoClaim()) && rec.ActiveRun.Open() { |
| return &RunOpenError{Run: *rec.ActiveRun} |
| } |
| - if rec.Seed.Import() && rec.Interactive != nil { |
| + if (rec.Seed.Import() || rec.Seed.DemoClaim()) && rec.Interactive != nil { |
| return &InteractiveOpenError{State: *rec.Interactive} |
| } |
| rec.Seed.State = seeds.StateAborted |
| @@ -308,7 +317,7 @@ func SeedColumn(rec Record) string { |
| if rec.Seed == nil { |
| return "" |
| } |
| - return seeds.RowSeed{ID: rec.Seed.ID, Kind: rec.Seed.Kind, SHA256: rec.Seed.SHA256, |
| + return seeds.RowSeed{ID: rec.Seed.ID, ClaimID: rec.Seed.ClaimID, Kind: rec.Seed.Kind, SHA256: rec.Seed.SHA256, |
| Bytes: rec.Seed.Bytes, State: rec.Seed.State}.Encode() |
| } |
diff --git a/internal/provision/seedreconcile.go b/internal/provision/seedreconcile.go| index 7862b2fd0..05682a96e 100644 |
| --- a/internal/provision/seedreconcile.go |
| +++ b/internal/provision/seedreconcile.go |
| @@ -99,6 +99,31 @@ func seedAction(rec Record, row *registry.Route, cfg ReconcileConfig, nested fun |
| log.Printf("provision: %s: import %s left alone this pass: the import journal could not be read", rec.Host, src.ID) |
| return seedSkip |
| } |
| + if src.DemoClaim() { |
| + if validateDemoClaimSeed(rec) != nil { |
| + return seedSkip |
| + } |
| + if src.State == seeds.StateCommitted && (row == nil || row.ImportGate == "") { |
| + return seedOrdinary |
| + } |
| + if cfg.ClaimEnabled { |
| + return seedSkip |
| + } |
| + if row != nil && !demoClaimSeedRow(rec, *row) { |
| + return seedSkip |
| + } |
| + if src.State == seeds.StateRolledBack && row != nil { |
| + return seedFinishAbort |
| + } |
| + if src.State == seeds.StateReady || src.State == seeds.StatePlaced { |
| + if row != nil && row.ImportGate != src.VerifyHash { |
| + return seedSkip |
| + } |
| + if ok, err := nested(); err != nil || !ok { |
| + return seedSkip |
| + } |
| + } |
| + } |
| hasRow := row != nil |
| switch src.State { |
| case seeds.StateAborted: |
| @@ -392,6 +417,11 @@ func journalPass(ctx context.Context, s release.Store, reg *registry.Registry, c |
| log.Printf("provision: %s: import %s left alone this pass: its record could not be read", j.Host, j.SeedID) |
| continue |
| } |
| + // A fresh claim never lends authority to an import journal, even |
| + // when corrupted state reuses its seed id. Keep both untouched. |
| + if rec != nil && rec.Seed.DemoClaim() { |
| + continue |
| + } |
| // journalRecord answers only with the journal's own record; this |
| // holds before any decision below, rollbacks first of all. |
| if rec != nil && RecordKey(rec.Account, rec.App, rec.Host) != j.RecordKey { |
diff --git a/internal/registry/demo_claim_seed.go b/internal/registry/demo_claim_seed.go| new file mode 100644 |
| index 000000000..012b099b3 |
| --- /dev/null |
| +++ b/internal/registry/demo_claim_seed.go |
| @@ -0,0 +1,49 @@ |
| +package registry |
| + |
| +// CompareSeedGate changes a fresh seed's gate and source together, only |
| +// while the complete seed, owner and lifetime identity still matches. |
| +func (r *Registry) CompareSeedGate(listed Route, source, gate string) error { |
| + if r.remote != nil { |
| + return errRemoteMethod |
| + } |
| + result, err := r.sql.Exec(`UPDATE routes SET seed_source=?, import_gate=? WHERE host=? AND kind='instance' AND provisioned=1 AND account=? AND app=? AND incarnation=? AND serving_seq=? AND seed_source=? AND import_gate=? AND created_at=?`, |
| + source, gate, listed.Host, listed.Account, listed.App, listed.Incarnation, listed.ServingSeq, listed.SeedSource, listed.ImportGate, listed.CreatedAt) |
| + if err != nil { |
| + return err |
| + } |
| + n, err := result.RowsAffected() |
| + if err != nil { |
| + return err |
| + } |
| + if n != 1 { |
| + return ErrHostHeld |
| + } |
| + return nil |
| +} |
| + |
| +// CreateSeedRoute never takes over a row that appeared after provisioning |
| +// listed the registry. The gate and seed are columns of the same insert. |
| +func (r *Registry) CreateSeedRoute(next Route) error { |
| + if r.remote != nil { |
| + return errRemoteMethod |
| + } |
| + if next.Kind != "instance" || !next.Provisioned || next.SeedSource == "" { |
| + return ErrHostHeld |
| + } |
| + return r.upsert(next, " AND 0") |
| +} |
| + |
| +// DeleteSeedRoute binds deletion to the stopped seed's lifetime as well as |
| +// its owner and seed column. A successor at the same hostname is untouched. |
| +func (r *Registry) DeleteSeedRoute(listed Route) (bool, error) { |
| + if r.remote != nil { |
| + return false, errRemoteMethod |
| + } |
| + result, err := r.sql.Exec(`DELETE FROM routes WHERE host=? AND kind='instance' AND provisioned=1 AND account=? AND app=? AND incarnation=? AND serving_seq=? AND seed_source=? AND import_gate=? AND created_at=?`, |
| + listed.Host, listed.Account, listed.App, listed.Incarnation, listed.ServingSeq, listed.SeedSource, listed.ImportGate, listed.CreatedAt) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := result.RowsAffected() |
| + return n == 1, err |
| +} |
diff --git a/internal/seeds/floor.go b/internal/seeds/floor.go| index 8798041d9..bc0d7f322 100644 |
| --- a/internal/seeds/floor.go |
| +++ b/internal/seeds/floor.go |
| @@ -24,7 +24,8 @@ import ( |
| // door opens (preflight M9). Plan 8 built them, and its Task 6 raised it |
| // to 1. Raising it opens nothing alone: a door opens only once an |
| // operator publishes the seeds floor (spec §10 step 2). |
| -const ProtocolVersion = 1 |
| +// 2 adds fresh demo-claim seeds. The ordinary doors still accept protocol 1. |
| +const ProtocolVersion = 2 |
| // RequiredProtocol is what the console requires every box in the region to |
| // report before it writes any seed state (spec §3.3). |
diff --git a/internal/seeds/row.go b/internal/seeds/row.go| index fecb874db..50c717d0c 100644 |
| --- a/internal/seeds/row.go |
| +++ b/internal/seeds/row.go |
| @@ -1,6 +1,7 @@ |
| package seeds |
| import ( |
| + "encoding/base64" |
| "encoding/json" |
| "fmt" |
| ) |
| @@ -9,11 +10,12 @@ import ( |
| // seed_source): enough for the activator to place the snapshot on first |
| // wake (spec §3.4) without reading the record. |
| type RowSeed struct { |
| - ID string `json:"id"` |
| - Kind string `json:"kind"` |
| - SHA256 string `json:"sha256,omitempty"` |
| - Bytes int64 `json:"bytes,omitempty"` |
| - State string `json:"state"` |
| + ID string `json:"id"` |
| + ClaimID string `json:"claim_id,omitempty"` |
| + Kind string `json:"kind"` |
| + SHA256 string `json:"sha256,omitempty"` |
| + Bytes int64 `json:"bytes,omitempty"` |
| + State string `json:"state"` |
| } |
| // Encode is the column's value: compact JSON in field order. |
| @@ -34,6 +36,17 @@ func ParseRowSeed(s string) (*RowSeed, error) { |
| if !ValidID(r.ID) { |
| return nil, fmt.Errorf("seeds: seed_source column: id %q is not a seed id", r.ID) |
| } |
| + if r.Kind == KindDemoClaim { |
| + claim, err := base64.RawURLEncoding.Strict().DecodeString(r.ClaimID) |
| + if err != nil || len(claim) != 32 { |
| + return nil, fmt.Errorf("seeds: invalid claim id") |
| + } |
| + switch r.State { |
| + case StateReady, StatePlaced, StateCommitted, StateReserving, StateAborted, StateRolledBack: |
| + default: |
| + return nil, fmt.Errorf("seeds: invalid claim state %q", r.State) |
| + } |
| + } |
| return &r, nil |
| } |
diff --git a/internal/seeds/seeds.go b/internal/seeds/seeds.go| index 06874ee0f..1a14b82ba 100644 |
| --- a/internal/seeds/seeds.go |
| +++ b/internal/seeds/seeds.go |
| @@ -22,8 +22,11 @@ import ( |
| // The two kinds of seed (spec §3.2). |
| const ( |
| - KindReplica = "replica" // --from: a sibling's replica |
| - KindImport = "import" // an uploaded snapshot |
| + KindDemoClaim = "demo-claim" |
| + DemoClaimCapability = "demo-claim-seed-v1" |
| + DemoClaimProtocol = 2 |
| + KindReplica = "replica" // --from: a sibling's replica |
| + KindImport = "import" // an uploaded snapshot |
| ) |
| // The states of spec §3.2. |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index 7c92b8b95..adb980ddb 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -35,6 +35,7 @@ import ( |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/seeds" |
| ) |
| // Probes carries everything CollectBox may not read from the registry — |
| @@ -536,6 +537,7 @@ type SystemState struct { |
| // publicly served fleet.json keeps the banded-words-only commitment. See the |
| // package doc comment for why this block is safe to exist at all. |
| type BoxMetrics struct { |
| + Capabilities []string `json:"capabilities,omitempty"` |
| ConsoleProcesses []ConsoleProcess `json:"console_processes,omitempty"` |
| ActivationID string `json:"activation_id,omitempty"` |
| ActivationComplete bool `json:"activation_complete,omitempty"` |
| @@ -1171,6 +1173,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| p.Alerts != nil || p.GeoIP != nil || p.HeldStreams != nil || len(p.BuildStates) > 0 || p.BuildStatesErr != "" || |
| p.UpdateSettings != 0 || len(p.Updates) > 0 || len(p.Egress) > 0 || p.SizeCommittedMiB != nil { |
| box.Metrics = &BoxMetrics{ |
| + Capabilities: []string{seeds.DemoClaimCapability}, |
| ConsoleProcesses: p.ConsoleProcesses, |
| ActivationID: p.ActivationID, ActivationComplete: p.ActivationComplete, |
| Enrollment: p.Enrollment, |
diff --git a/internal/status/snapshot_test.go b/internal/status/snapshot_test.go| index a8bf774be..5e0bc83bb 100644 |
| --- a/internal/status/snapshot_test.go |
| +++ b/internal/status/snapshot_test.go |
| @@ -381,7 +381,7 @@ func TestCollectBoxCarriesAliasesRead(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if !strings.Contains(string(out), `"metrics":{"aliases_read":true}`) { |
| + if !strings.Contains(string(out), `"metrics":{"capabilities":["demo-claim-seed-v1"],"aliases_read":true}`) { |
| t.Fatalf("json lacks the aliases_read-only metrics block: %s", out) |
| } |
| off := CollectBox(nil, Probes{Release: "v1"}, at) |