carlos / platform Public

fix: demo build worker review round 1

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev de382cbbc0c6143b275ba1588c05e6e6dded13e8 parent e08f8ab
7 files changed, +421 −40
  • internal/demobuild/unit.go +1 −5
  • internal/demobuild/unit_test.go +33 −0
  • internal/demobuild/worker.go +65 −24
  • internal/demobuild/worker_test.go +147 −2
  • internal/instancectl/demo_build.go +19 −0
  • internal/instancectl/demo_build_test.go +128 −0
  • internal/instancectl/server.go +28 −9

CI failed — run details

Intent

Human

<task-notification> <task-id>b3x93fmh4</task-id> <tool-use-id>toolu_01RQ3BRPiRgs3JAk2m2bTMFA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/b3x93fmh4.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 5 fix" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a5bbfbf4e5cf8e7e9</task-id> <tool-use-id>toolu_01XobGb2MCmMYBDNteE9wxvG</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a5bbfbf4e5cf8e7e9.output</output-file> <status>completed</status> <summary>Agent "Re-review Task 5 fix round 1" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Review written to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/agent-start-demo-1/.superpowers/sdd/2026-11-02-agent-start-demo-1-anonymous-apps/task-5-review-r2.md`. - **P1-1 ADDRESSED** (internal/host/demo_jobs.go:83-87, :423-436). The worker now reaches the stream, pickup and result doors through the console origin, the same route the run relay uses, and refuses the tunnel host. `CARLOS_CONSOLE` is a new operator step: nothing on boxes sets it today. If it is missing or invalid, the worker logs once and returns. It does not crash or retry, and the console has no eligible peer, so create is refused (fails closed). - **P2-1 ADDRESSED** (internal/console/demo_jobs.go:446-490, demo_spool.go:184-192). The loop is event- and deadline-driven, and a read-only check runs before any writer transaction. An idle console does no DB write and no store request. - **P2-2 ADDRESSED** (lifetimes_cutover.go:385, server.go:2317). The stream path is exempt from the cutover gate and perf measurement; pickup and result stay admitted. - **P2-3 ADDRESSED** (demo_spool.go, apidemobox.go:318-345). - No path can come from HTTP. The upload is bounded and spooled to a 0700 directory with 0600 files. - Spools are cleaned when jobs fail or are published, and after a failed commit. - Startup re-hashes ready spools and sweeps orphans before the console listens. - **P2-4 ADDRESSED** (host/demo_jobs.go:155, demobuild/worker.go:129). A 5 s clock-skew allowance, and the build is still capped locally at 180 s. - **P3-2, P3-5, P3-7 (idle half) ADDRESSED.** **P3-6 ADDRESSED**, but it causes new P2-A. The other P3s are carried over, as the fix report says. New findings in the fix diff: - **P2-A** (apidemo.go:375). Anonymous create now requires the policy writer lease to be held already. That lease is only taken on first need (policylease.go:15-21), and nothing in the demo flow takes it. On a console with a configured lease, every create after a restart returns 503 until some unrelated operation takes the lease. Fault family: admission liveness. - **P2-B** (demo_spool.go:247-249, cmd/console/main.go:689-693). A `spool_path` that is stale or not in the expected form makes `cleanDemoSpools` return an error, and startup recovery treats that as fatal. If console.db is moved or restored to another path, or its configured path string changes, the whole console crash-loops on every start. Fault family: recovery blast radius. - **P3:** 1. `CARLOS_CONSOLE` reuses the CLI's console-selection variable name. It also needs adding to the plan's operator settings table and the demo-box runbook. 2. `revalidateDemoPeers` no longer has a production caller, but the revocation tests still call it directly. 3. A file of up to 32 MiB is fsynced while the writer transaction is held. 4. `MkdirAll` does not tighten permissions on a spool directory that already exists. Census: no new root read from agent-, app- or tenant-writable input. **Verdict: READY AFTER FIXES** (no P1; P2-A and P2-B to fix)</result> <usage><subagent_tokens>115115</subagent_tokens><tool_uses>22</tool_uses><duration_ms>296172</duration_ms></usage> </task-notification>

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

diff --git a/internal/demobuild/unit.go b/internal/demobuild/unit.go
index f9b7226bf..d8221e22f 100644
--- a/internal/demobuild/unit.go
+++ b/internal/demobuild/unit.go
@@ -107,11 +107,7 @@ func (w *Worker) prepareUnit(ctx context.Context, dir string, src Source) (func(
return nil, err
}
cleanup := func() error {
- end := time.Now().Add(BuildStopSeconds * time.Second)
- if deadline, ok := ctx.Deadline(); ok && deadline.Add(BuildStopSeconds*time.Second).Before(end) {
- end = deadline.Add(BuildStopSeconds * time.Second)
- }
- cleanCtx, cancel := context.WithDeadline(context.Background(), end)
+ cleanCtx, cancel := context.WithTimeout(context.Background(), BuildStopSeconds*time.Second)
defer cancel()
return w.cleanUnit(cleanCtx, l)
}
diff --git a/internal/demobuild/unit_test.go b/internal/demobuild/unit_test.go
index bd7557bbc..5f8cb42b0 100644
--- a/internal/demobuild/unit_test.go
+++ b/internal/demobuild/unit_test.go
@@ -133,3 +133,36 @@ func TestDemoBuildBudgetReadback(t *testing.T) {
t.Fatal("canonical systemd 257 readback refused", err)
}
}
+
+func TestDemoBuildCleanupHasIndependentDeadline(t *testing.T) {
+ fakeUnitController(t)
+ w, j, _, _ := workerFixture(t)
+ ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(-time.Minute))
+ defer cancel()
+ // Refuse preparation after its cleanup closure exists, before any mount starts.
+ os.Remove(unitRoot)
+ cleanup, err := w.prepareUnit(ctx, filepath.Join(w.root, j.ID, "1"), Source{})
+ if err == nil || cleanup == nil {
+ t.Fatalf("prepare: cleanup=%v err=%v", cleanup != nil, err)
+ }
+ if err := os.Mkdir(unitRoot, 0700); err != nil {
+ t.Fatal(err)
+ }
+ ctl := systemctl
+ calls := 0
+ systemctl = func(ctx context.Context, args ...string) (string, error) {
+ calls++
+ deadline, ok := ctx.Deadline()
+ remaining := time.Until(deadline)
+ if !ok || remaining < 4*time.Second || remaining > BuildStopSeconds*time.Second {
+ t.Errorf("cleanup inherited expired job deadline: remaining=%s", remaining)
+ }
+ return ctl(ctx, args...)
+ }
+ if err := cleanup(); err != nil {
+ t.Fatal(err)
+ }
+ if calls == 0 {
+ t.Fatal("cleanup did not stop unit")
+ }
+}
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go
index edfe38412..b03d22e3d 100644
--- a/internal/demobuild/worker.go
+++ b/internal/demobuild/worker.go
@@ -1,8 +1,11 @@
package demobuild
import (
+ "bytes"
"context"
"crypto/ed25519"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"errors"
"io"
@@ -38,6 +41,9 @@ type Worker struct {
processLock *os.File
mu sync.Mutex
poisoned bool
+ ready bool
+ initOnce sync.Once
+ initErr error
}
func NewWorker(getenv func(string) string, proof func(context.Context) error) (*Worker, error) {
@@ -71,10 +77,6 @@ func NewWorker(getenv func(string) string, proof func(context.Context) error) (*
if err != nil {
return nil, err
}
- digest, err := CheckBundle(cfg.ToolchainDir, lock)
- if err != nil {
- return nil, err
- }
r, err := instancefs.OpenRootBeneath(BuildRoot, ".")
if err != nil {
return nil, err
@@ -88,22 +90,55 @@ func NewWorker(getenv func(string) string, proof func(context.Context) error) (*
if err != nil {
return nil, err
}
- w := &Worker{cfg: cfg, box: box, pub: pub, lock: lock, digest: digest, root: BuildRoot, slots: make(chan struct{}, cfg.BuildConcurrency), proof: proof, processLock: guard}
+ w := &Worker{cfg: cfg, box: box, pub: pub, lock: lock, root: BuildRoot, slots: make(chan struct{}, cfg.BuildConcurrency), proof: proof, processLock: guard}
w.prepare = w.prepareUnit
w.run = w.runUnit
- ctx, cancel := context.WithTimeout(context.Background(), BuildWindow)
- defer cancel()
- if err = w.recover(ctx); err != nil {
- guard.Close()
- return nil, err
- }
- if err = w.probeBundle(ctx); err != nil {
- guard.Close()
- return nil, err
- }
return w, nil
}
+// Initialize runs after the control server starts. Readiness and admission stay
+// closed until every startup check succeeds, including probe cleanup.
+func (w *Worker) Initialize(ctx context.Context) error {
+ return w.initialize(ctx, func(context.Context) error {
+ digest, err := CheckBundle(w.cfg.ToolchainDir, w.lock)
+ if err == nil {
+ w.digest = digest
+ }
+ return err
+ }, w.recover, w.probeBundle)
+}
+
+func (w *Worker) initialize(ctx context.Context, stages ...func(context.Context) error) error {
+ w.initOnce.Do(func() {
+ ctx, cancel := context.WithTimeout(ctx, BuildWindow)
+ defer cancel()
+ for _, stage := range stages {
+ if w.initErr = ctx.Err(); w.initErr != nil {
+ return
+ }
+ if w.initErr = stage(ctx); w.initErr != nil {
+ return
+ }
+ }
+ if w.initErr = ctx.Err(); w.initErr != nil {
+ return
+ }
+ w.mu.Lock()
+ w.ready = true
+ w.mu.Unlock()
+ })
+ return w.initErr
+}
+
+func (w *Worker) available() bool {
+ if w == nil {
+ return false
+ }
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ return w.ready && !w.poisoned
+}
+
func (w *Worker) Close() error {
if w == nil || w.processLock == nil {
return nil
@@ -112,10 +147,7 @@ func (w *Worker) Close() error {
}
func (w *Worker) Readiness(ctx context.Context) (WorkerReady, error) {
- w.mu.Lock()
- bad := w.poisoned
- w.mu.Unlock()
- if bad || w.proof == nil || w.proof(ctx) != nil {
+ if !w.available() || w.proof == nil || w.proof(ctx) != nil {
return WorkerReady{}, ErrBuild
}
if err := w.assertBudget(ctx); err != nil {
@@ -125,6 +157,9 @@ func (w *Worker) Readiness(ctx context.Context) (WorkerReady, error) {
}
func (w *Worker) validate(wire []byte) (Job, error) {
+ if !w.available() {
+ return Job{}, ErrBuild
+ }
j, err := VerifyJob(w.pub, wire, time.Now())
if err != nil || time.Until(j.Deadline) > BuildWindow+ClockSkew || j.Box != w.box || j.BundleSHA256 != w.digest {
return Job{}, ErrJob
@@ -154,16 +189,21 @@ func (w *Worker) Build(ctx context.Context, wire []byte, source io.Reader) (out
default:
return out, ErrBuild
}
- w.mu.Lock()
- bad := w.poisoned
- w.mu.Unlock()
- if bad || w.proof(ctx) != nil {
+ if !w.available() || w.proof(ctx) != nil {
return out, ErrBuild
}
if err = w.reserve(j); err != nil {
return out, err
}
- src, diags, err := ValidateSource(source, w.lock)
+ original, err := io.ReadAll(io.LimitReader(source, demo.SourceMaxBytes+1))
+ if err != nil || len(original) > demo.SourceMaxBytes {
+ return out, ErrJob
+ }
+ digest := sha256.Sum256(original)
+ if hex.EncodeToString(digest[:]) != j.SourceSHA256 || ctx.Err() != nil {
+ return out, ErrJob
+ }
+ src, diags, err := ValidateSource(bytes.NewReader(original), w.lock)
if err != nil {
return BuildOutput{Diagnostics: diags}, err
}
@@ -204,6 +244,7 @@ func (w *Worker) reserve(j Job) error {
return err
}
if err = w.expireMarkers(); err != nil {
+ w.poisoned = true
return err
}
f, err := instancefs.OpenBeneath(w.root, "seen/"+j.ID, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
diff --git a/internal/demobuild/worker_test.go b/internal/demobuild/worker_test.go
index 97d27178a..88929e7c9 100644
--- a/internal/demobuild/worker_test.go
+++ b/internal/demobuild/worker_test.go
@@ -7,7 +7,9 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
+ "crypto/sha256"
"encoding/base64"
+ "encoding/hex"
"errors"
"io"
"os"
@@ -28,7 +30,7 @@ func workerFixture(t *testing.T) (*Worker, Job, ed25519.PrivateKey, []byte) {
if err != nil {
t.Fatal(err)
}
- w := &Worker{cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }}
+ w := &Worker{ready: true, cfg: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildConcurrency: 1}, box: "box-1", pub: pub, lock: testLock(t), digest: strings.Repeat("b", 64), root: t.TempDir(), slots: make(chan struct{}, 1), proof: func(context.Context) error { return nil }}
w.prepare = func(context.Context, string, Source) (func() error, error) { return func() error { return nil }, nil }
w.run = func(context.Context, string, Lock) (BuildOutput, error) { return BuildOutput{}, nil }
j := Job{ID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)), DemoID: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{2}, 16)), Account: "shop", App: "tmp-demo-bright-otter-42", Host: "bright-otter-42.example.com", Lifetime: "life-1", Fleet: "demo", Box: "box-1", SourceSHA256: v.SHA256, BundleSHA256: w.digest, Generation: 1, Attempt: 1, Deadline: time.Now().UTC().Add(time.Minute)}
@@ -91,7 +93,7 @@ func TestDemoBuildSlotsAndReplay(t *testing.T) {
t.Fatal("replayed completed attempt")
}
// A new process reads the same durable marker before it opens source.
- w2 := &Worker{cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run}
+ w2 := &Worker{ready: true, cfg: w.cfg, box: w.box, pub: w.pub, lock: w.lock, digest: w.digest, root: w.root, slots: make(chan struct{}, 1), proof: w.proof, prepare: w.prepare, run: w.run}
if _, err := w2.Build(context.Background(), wire, neverRead{t}); err == nil {
t.Fatal("replayed after root restart")
}
@@ -175,3 +177,146 @@ func TestDemoBuildGrantClockSkew(t *testing.T) {
}
}
}
+
+func TestDemoBuildSourceHashBeforeParse(t *testing.T) {
+ w, j, key, _ := workerFixture(t)
+ wire, _ := SignJob(key, j)
+ out, err := w.Build(t.Context(), wire, strings.NewReader("not a gzip archive"))
+ if !errors.Is(err, ErrJob) || len(out.Diagnostics) != 0 {
+ t.Fatalf("mismatched source reached parser: err=%v diagnostics=%v", err, out.Diagnostics)
+ }
+}
+
+func TestDemoBuildTornMarkerPoisonsReadiness(t *testing.T) {
+ fakeUnitController(t)
+ systemctl = func(context.Context, ...string) (string, error) {
+ return "MemoryMax=1073741824\nMemorySwapMax=0\nTasksMax=128\nCPUQuotaPerSecUSec=500ms\n", nil
+ }
+ w, j, key, _ := workerFixture(t)
+ if err := os.Mkdir(filepath.Join(w.root, "seen"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(w.root, "seen", j.ID), nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ wire, _ := SignJob(key, j)
+ if _, err := w.Build(t.Context(), wire, neverRead{t}); err == nil {
+ t.Fatal("accepted torn marker")
+ }
+ ready, err := w.Readiness(t.Context())
+ if err == nil || ready.Capability != "" {
+ t.Fatalf("torn marker advertised readiness: %+v %v", ready, err)
+ }
+}
+
+func TestDemoBuildInitializationGatesReadinessAndBuilds(t *testing.T) {
+ for _, failure := range []string{"success", "bundle", "recovery", "probe", "cancel"} {
+ t.Run(failure, func(t *testing.T) {
+ fakeUnitController(t)
+ systemctl = func(context.Context, ...string) (string, error) {
+ return "MemoryMax=1073741824\nMemorySwapMax=0\nTasksMax=128\nCPUQuotaPerSecUSec=500ms\n", nil
+ }
+ w, j, key, src := workerFixture(t)
+ w.ready = false
+ wire, _ := SignJob(key, j)
+ refuse := func() {
+ t.Helper()
+ if ready, err := w.Readiness(t.Context()); err == nil || ready.Capability != "" {
+ t.Fatalf("uninitialized worker advertised: %+v %v", ready, err)
+ }
+ if _, err := w.Build(t.Context(), wire, neverRead{t}); err == nil {
+ t.Fatal("uninitialized build accepted")
+ }
+ if _, err := w.GrantDeadline(wire); err == nil {
+ t.Fatal("uninitialized grant accepted")
+ }
+ }
+ refuse()
+ stages := make(chan string)
+ proceed := make(chan struct{})
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ stage := func(name string) func(context.Context) error {
+ return func(ctx context.Context) error {
+ stages <- name
+ select {
+ case <-proceed:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ if name == failure {
+ return ErrBuild
+ }
+ return nil
+ }
+ }
+ done := make(chan error, 1)
+ go func() { done <- w.initialize(ctx, stage("bundle"), stage("recovery"), stage("probe")) }()
+ for _, name := range []string{"bundle", "recovery", "probe"} {
+ if got := <-stages; got != name {
+ t.Fatalf("stage=%s want=%s", got, name)
+ }
+ refuse()
+ if failure == "cancel" {
+ cancel()
+ break
+ }
+ proceed <- struct{}{}
+ if name == failure {
+ break
+ }
+ }
+ err := <-done
+ if failure != "success" {
+ if err == nil {
+ t.Fatal("initialization unexpectedly succeeded")
+ }
+ refuse()
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if ready, err := w.Readiness(t.Context()); err != nil || ready.Capability != "anonymous-demo-v1" {
+ t.Fatalf("ready=%+v err=%v", ready, err)
+ }
+ if _, err := w.Build(t.Context(), wire, bytes.NewReader(src)); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.initialize(t.Context(), func(context.Context) error { t.Fatal("initialized twice"); return nil }); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+
+func TestDemoBuildSignedMalformedSourceReachesValidation(t *testing.T) {
+ w, j, key, _ := workerFixture(t)
+ source := []byte("not a gzip archive")
+ digest := sha256.Sum256(source)
+ j.SourceSHA256 = hex.EncodeToString(digest[:])
+ wire, err := SignJob(key, j)
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, err := w.Build(t.Context(), wire, bytes.NewReader(source))
+ if !errors.Is(err, ErrSource) || len(out.Diagnostics) == 0 {
+ t.Fatalf("matching signed bytes skipped validation: err=%v diagnostics=%v", err, out.Diagnostics)
+ }
+}
+
+func TestDemoBuildMissingBundleRemainsUnavailable(t *testing.T) {
+ w, j, key, _ := workerFixture(t)
+ w.ready = false
+ w.cfg.ToolchainDir = filepath.Join(t.TempDir(), "absent")
+ if err := w.Initialize(t.Context()); err == nil {
+ t.Fatal("missing bundle initialized")
+ }
+ if ready, err := w.Readiness(t.Context()); err == nil || ready.Capability != "" {
+ t.Fatalf("missing bundle advertised: %+v %v", ready, err)
+ }
+ wire, _ := SignJob(key, j)
+ if _, err := w.Build(t.Context(), wire, neverRead{t}); err == nil {
+ t.Fatal("missing bundle admitted build")
+ }
+}
diff --git a/internal/instancectl/demo_build.go b/internal/instancectl/demo_build.go
index 4e3b78184..5d46526f0 100644
--- a/internal/instancectl/demo_build.go
+++ b/internal/instancectl/demo_build.go
@@ -13,6 +13,13 @@ import (
"github.com/carlosframework/platform/internal/demobuild"
)
+type demoBuilder interface {
+ Initialize(context.Context) error
+ Readiness(context.Context) (demobuild.WorkerReady, error)
+ GrantDeadline([]byte) (time.Time, error)
+ Build(context.Context, []byte, io.Reader) (demobuild.BuildOutput, error)
+}
+
// The request is a big-endian uint32 grant length, signed grant bytes, then
// the bounded original source archive. There is no path or command field.
func (c *Client) BuildDemo(ctx context.Context, signedJob []byte, source io.Reader) (demobuild.BuildOutput, error) {
@@ -81,6 +88,10 @@ func (c *Client) DemoBuildReadiness(ctx context.Context) (demobuild.WorkerReady,
func (s *Server) handleDemoBuildReady(w http.ResponseWriter, r *http.Request) {
w.Header().Set(BuildHeader, s.Build)
+ if s.DemoBuilder == nil {
+ http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable)
+ return
+ }
ready, err := s.DemoBuilder.Readiness(r.Context())
if err != nil {
http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable)
@@ -91,6 +102,14 @@ func (s *Server) handleDemoBuildReady(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) handleDemoBuild(w http.ResponseWriter, r *http.Request) {
+ if s.DemoBuilder == nil {
+ http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable)
+ return
+ }
+ if _, err := s.DemoBuilder.Readiness(r.Context()); err != nil {
+ http.Error(w, demobuild.ErrBuild.Error(), http.StatusServiceUnavailable)
+ return
+ }
// Reading a stalled body must share the hard wall-clock bound. Context
// cancellation alone does not interrupt a net/http request-body read.
deadline := time.Now().Add(demobuild.BuildWindow)
diff --git a/internal/instancectl/demo_build_test.go b/internal/instancectl/demo_build_test.go
index 0ef87164c..5495e276d 100644
--- a/internal/instancectl/demo_build_test.go
+++ b/internal/instancectl/demo_build_test.go
@@ -3,9 +3,13 @@ package instancectl
import (
"context"
"io"
+ "net"
+ "net/http"
"net/http/httptest"
"strings"
+ "sync/atomic"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/demobuild"
)
@@ -29,3 +33,127 @@ func TestDemoBuildOff(t *testing.T) {
}
}
}
+
+type startupBuilder struct {
+ entered chan struct{}
+ release chan struct{}
+ done chan struct{}
+ fail bool
+ ready atomic.Bool
+}
+
+func (b *startupBuilder) Initialize(ctx context.Context) error {
+ defer close(b.done)
+ close(b.entered)
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-b.release:
+ }
+ if b.fail {
+ return demobuild.ErrBuild
+ }
+ b.ready.Store(true)
+ return nil
+}
+func (b *startupBuilder) Readiness(context.Context) (demobuild.WorkerReady, error) {
+ if !b.ready.Load() {
+ return demobuild.WorkerReady{}, demobuild.ErrBuild
+ }
+ return demobuild.WorkerReady{Capability: "anonymous-demo-v1", GOARCH: "arm64", BundleSHA256: strings.Repeat("b", 64), Slots: 1}, nil
+}
+func (b *startupBuilder) GrantDeadline([]byte) (time.Time, error) {
+ return time.Time{}, demobuild.ErrJob
+}
+func (b *startupBuilder) Build(context.Context, []byte, io.Reader) (demobuild.BuildOutput, error) {
+ return demobuild.BuildOutput{}, demobuild.ErrBuild
+}
+
+func TestDemoBuildStartupKeepsInstanceVerbsServed(t *testing.T) {
+ for _, outcome := range []string{"success", "failure", "unavailable", "cancel"} {
+ t.Run(outcome, func(t *testing.T) {
+ b := &startupBuilder{entered: make(chan struct{}), release: make(chan struct{}), done: make(chan struct{}), fail: outcome == "failure"}
+ s := &Server{DemoBox: true, PeerOK: func(net.Conn) error { return nil }, Systemctl: new(fakeCtl).run}
+ if outcome != "unavailable" {
+ s.DemoBuilder = b
+ }
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(t.Context())
+ stopped := make(chan error, 1)
+ go func() { stopped <- s.Serve(ctx, ln) }()
+ t.Cleanup(func() {
+ cancel()
+ ln.Close()
+ if err := <-stopped; err != nil {
+ t.Error(err)
+ }
+ })
+ c := &http.Client{Timeout: time.Second}
+ defer c.CloseIdleConnections()
+ url := "http://" + ln.Addr().String()
+ check := func(method, path string, want int) string {
+ t.Helper()
+ req, _ := http.NewRequest(method, url+path, nil)
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != want {
+ t.Fatalf("%s: status=%d want=%d body=%s", path, resp.StatusCode, want, body)
+ }
+ return string(body)
+ }
+ ordinary := func() {
+ t.Helper()
+ check("POST", "/stop?host=shop.example.com&role=run", http.StatusNoContent)
+ check("POST", "/reset?host=shop.example.com&role=run", http.StatusNoContent)
+ }
+ ordinary()
+ if outcome != "unavailable" {
+ select {
+ case <-b.entered:
+ case <-time.After(time.Second):
+ t.Fatal("Serve did not initialize worker")
+ }
+ }
+ if body := check("GET", "/demo-build/ready", 503); strings.Contains(body, "anonymous-demo-v1") {
+ t.Fatal("advertised while pending")
+ }
+ check("POST", "/demo-build", 503)
+ if outcome == "unavailable" {
+ return
+ }
+ if outcome == "cancel" {
+ cancel()
+ select {
+ case <-b.done:
+ case <-time.After(time.Second):
+ t.Fatal("worker initialization survived server cancellation")
+ }
+ if b.ready.Load() {
+ t.Fatal("canceled initialization advertised ready")
+ }
+ return
+ }
+ close(b.release)
+ <-b.done
+ ordinary()
+ want := 503
+ if outcome == "success" {
+ want = 200
+ }
+ body := check("GET", "/demo-build/ready", want)
+ if strings.Contains(body, "anonymous-demo-v1") != (outcome == "success") {
+ t.Fatal("wrong capability", body)
+ }
+ if outcome == "failure" {
+ check("POST", "/demo-build", 503)
+ }
+ })
+ }
+}
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go
index 283fca5cd..1d0963ade 100644
--- a/internal/instancectl/server.go
+++ b/internal/instancectl/server.go
@@ -43,7 +43,7 @@ import (
type Server struct {
// DemoBox is fixed from root-owned environment at service startup.
DemoBox bool
- DemoBuilder *demobuild.Worker
+ DemoBuilder demoBuilder
ClaimStop http.Handler
// ClaimHeldRelease is the moves held-release route's handler (moves
@@ -321,10 +321,13 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s.InspectMountpoints(ctx)
- if os.Getenv("CARLOS_DEMO_BUILD_WORKER") != "" {
- s.RunProbe(ctx)
- }
- s.DemoBuilder, err = demobuild.NewWorker(os.Getenv, func(context.Context) error {
+ firstProbe := make(chan struct{})
+ builder, err := demobuild.NewWorker(os.Getenv, func(ctx context.Context) error {
+ select {
+ case <-firstProbe:
+ case <-ctx.Done():
+ return ctx.Err()
+ }
if _, ready := s.Ready(); !ready {
return demobuild.ErrBuild
}
@@ -333,8 +336,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
if err != nil {
log.Fatalf("instance-control: demo builder: %v", err)
}
- defer s.DemoBuilder.Close()
- go s.probeLoop(ctx)
+ defer builder.Close()
+ if builder != nil {
+ s.DemoBuilder = builder
+ }
+ go s.probeLoop(ctx, firstProbe)
go s.diskLoop(ctx)
go s.Egress.Loop(ctx, s.DiskEvery)
if err := s.Serve(ctx, ln); err != nil {
@@ -346,6 +352,18 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV
// ones to the HTTP server one at a time through a listener that only ever
// yields vetted connections.
func (s *Server) Serve(ctx context.Context, ln net.Listener) error {
+ ctx, cancel := context.WithCancel(ctx)
+ defer cancel()
+ if s.DemoBuilder != nil {
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ if err := s.DemoBuilder.Initialize(ctx); err != nil {
+ s.logf("instance-control: demo builder: %v", err)
+ }
+ }()
+ defer func() { cancel(); <-done }()
+ }
vetted := &vettedListener{Listener: ln, ok: s.peerOK, logf: s.logf}
srv := &http.Server{Handler: s.Handler(), ReadHeaderTimeout: 5 * time.Second, ConnContext: s.connContext}
// One request per connection (#292): a connection's accept order is the
@@ -425,7 +443,7 @@ func (s *Server) peerOK(c net.Conn) error { return s.PeerOK(c) }
func (s *Server) Handler() http.Handler {
mux := http.NewServeMux()
- if s.DemoBox && s.DemoBuilder != nil {
+ if s.DemoBox {
mux.HandleFunc("POST /demo-build", s.handleDemoBuild)
mux.HandleFunc("GET /demo-build/ready", s.handleDemoBuildReady)
}
@@ -1278,9 +1296,10 @@ func waitCgroupFileEmpty(ctx context.Context, events, unit string, every time.Du
// probeLoop runs the probe at start and every ProbeEvery, and beside it
// denyLoop, which keeps the box-address deny current between probes.
-func (s *Server) probeLoop(ctx context.Context) {
+func (s *Server) probeLoop(ctx context.Context, firstProbe chan<- struct{}) {
go s.denyLoop(ctx)
s.RunProbe(ctx)
+ close(firstProbe)
t := time.NewTicker(s.ProbeEvery)
defer t.Stop()
for {