demobuild: admit one build output into root's memory at a time (F3)
A finished build now takes a process-wide output turn before root reads out/app, and keeps it until instance-control has written the response; every failure path, discarded output and the readiness probe hand it back. The other finished builds wait within their own deadlines. The response write is bounded at the build window plus 5 s, as the client is, so a stalled reader cannot keep the turn. Root reads the output into one buffer sized from the open file and validates and digests exactly those bytes; size, ELF-segment and digest checks are unchanged. MemoryMax stays as it is. On a build-worker box claimUnitContent already renders carlos-instance-control with MemoryMax=1073741824 and GOMEMLIMIT=768MiB (since b21e4da8), not the base 64M the plan assumed; the unit-text test now pins those exact lines. Measured on docs-t1 (amd64, go1.26.10): four 32 MiB outputs in turn through Run and json.NewEncoder, sampled every 1 ms with ReadMemStats plus getrusage maxrss (CARLOS_DEMO_TRANSFER_PEAK=1 go test ./internal/demobuild -run '^TestDemoBuildOutputTransferPeak$' -v): - no GOMEMLIMIT: peak HeapAlloc 182 MiB, maxrss 46 -> 206 MiB (+160); - GOMEMLIMIT=768MiB: peak HeapAlloc 182 MiB, maxrss +161 MiB; - GOMEMLIMIT=96MiB: peak HeapAlloc 118 MiB (the live floor: raw 32 + base64 buffer ~43 + its append copy ~43), maxrss +87 MiB. One transfer fits the 1 GiB cap with room; four at once (~470 MiB live plus garbage) did not fit comfortably under GOMEMLIMIT. The post-release witness reads the service cgroup's memory.peak and memory.events.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+435
−5
internal/demobuild/gvisor_build_rootrunner_linux_test.go+2 −1internal/demobuild/gvisor_cleanup_test.go+2 −1internal/demobuild/job.go+2 −0internal/demobuild/probe.go+2 −1internal/demobuild/runner.go+38 −1internal/demobuild/transfer.go+39 −0internal/demobuild/transfer_test.go+227 −0internal/demobuild/worker.go+1 −0internal/demobuild/worker_test.go+1 −0internal/host/demo_build_linux_test.go+8 −1internal/instancectl/demo_build.go+6 −0internal/instancectl/demo_build_transfer_test.go+107 −0
diff --git a/internal/demobuild/gvisor_build_rootrunner_linux_test.go b/internal/demobuild/gvisor_build_rootrunner_linux_test.go| index 2c3339a50..e9e9d5b84 100644 |
| --- a/internal/demobuild/gvisor_build_rootrunner_linux_test.go |
| +++ b/internal/demobuild/gvisor_build_rootrunner_linux_test.go |
| @@ -205,6 +205,7 @@ func rootrunnerBuild(t *testing.T, capture bool) { |
| defer func() { systemctl = ctl }() |
| start = time.Now() |
| built, err := w.runUnit(ctx, l.dir, lock) |
| + built.Release() // the bytes stay readable; only the transfer turn goes back |
| elapsed := time.Since(start) |
| if err != nil { |
| b, _ := os.ReadFile(l.work + "/diagnostics") |
| @@ -245,7 +246,7 @@ func rootrunnerBuild(t *testing.T, capture bool) { |
| l, cleanup = prepare(strings.Replace(large, "40<<20", "20<<20", 1)) |
| buildCtx, stop := context.WithCancel(ctx) |
| done := make(chan error, 1) |
| - go func() { _, err := w.runUnit(buildCtx, l.dir, lock); done <- err }() |
| + go func() { out, err := w.runUnit(buildCtx, l.dir, lock); out.Release(); done <- err }() |
| active := false |
| for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(10 * time.Millisecond) { |
| out, err := systemctl(ctx, "show", l.unit, "-p", "MainPID,ActiveState") |
diff --git a/internal/demobuild/gvisor_cleanup_test.go b/internal/demobuild/gvisor_cleanup_test.go| index ba8d12fa6..6a1543b27 100644 |
| --- a/internal/demobuild/gvisor_cleanup_test.go |
| +++ b/internal/demobuild/gvisor_cleanup_test.go |
| @@ -87,7 +87,8 @@ func TestGVisorBuildExitDiagnosticsOnly(t *testing.T) { |
| return stopBuildContext(ctx, buildLayout{unit: "carlos-demo-build-gvisor@test.service", family: execsandbox.FamilyGVisor}) |
| }, |
| } |
| - _, err := Run(context.WithValue(t.Context(), runContextKey{}, i), dir, testLock(t)) |
| + out, err := Run(context.WithValue(t.Context(), runContextKey{}, i), dir, testLock(t)) |
| + out.Release() |
| if (err == nil) != (fault == "") { |
| t.Fatalf("fault=%s fields=%q: %v", fault, fields, err) |
| } |
diff --git a/internal/demobuild/job.go b/internal/demobuild/job.go| index 1c85f761c..e5067e1ea 100644 |
| --- a/internal/demobuild/job.go |
| +++ b/internal/demobuild/job.go |
| @@ -157,6 +157,8 @@ type BuildOutput struct { |
| SHA256 string `json:"sha256"` |
| Diagnostics []Diagnostic `json:"diagnostics"` |
| DiagnosticsTruncated bool `json:"diagnostics_truncated,omitempty"` |
| + // hold is this output's turn in the one-at-a-time transfer (transfer.go). |
| + hold *outputHold |
| } |
| // StreamMessage carries signed work or a reconciliation hint. Hints grant no |
diff --git a/internal/demobuild/probe.go b/internal/demobuild/probe.go| index 917860a65..2a07bbb5c 100644 |
| --- a/internal/demobuild/probe.go |
| +++ b/internal/demobuild/probe.go |
| @@ -35,7 +35,8 @@ func (w *Worker) probeBundle(ctx context.Context) (err error) { |
| if err != nil { |
| return err |
| } |
| - _, err = w.runUnit(ctx, dir, w.lock) |
| + out, err := w.runUnit(ctx, dir, w.lock) |
| + out.Release() |
| return err |
| } |
diff --git a/internal/demobuild/runner.go b/internal/demobuild/runner.go| index 53d35f506..7062838ab 100644 |
| --- a/internal/demobuild/runner.go |
| +++ b/internal/demobuild/runner.go |
| @@ -58,6 +58,30 @@ func ValidateOutput(r io.Reader) (BuildOutput, error) { |
| if err != nil || len(b) > BinaryMaxBytes { |
| return BuildOutput{}, ErrBuild |
| } |
| + return validateBinary(b) |
| +} |
| + |
| +// readOutput is ValidateOutput for the build's own output file in root. It |
| +// sizes one buffer from the open file instead of growing one as it reads, |
| +// so a transfer holds the output once, and it validates and digests exactly |
| +// the bytes the response will carry. The build has stopped; a file that |
| +// still grows past its size is refused. |
| +func readOutput(f *os.File) (BuildOutput, error) { |
| + st, err := f.Stat() |
| + if err != nil || !st.Mode().IsRegular() || st.Size() > BinaryMaxBytes { |
| + return BuildOutput{}, ErrBuild |
| + } |
| + b := make([]byte, st.Size()) |
| + if _, err = io.ReadFull(f, b); err != nil { |
| + return BuildOutput{}, ErrBuild |
| + } |
| + if n, _ := f.Read(make([]byte, 1)); n != 0 { |
| + return BuildOutput{}, ErrBuild |
| + } |
| + return validateBinary(b) |
| +} |
| + |
| +func validateBinary(b []byte) (BuildOutput, error) { |
| f, err := elf.NewFile(bytes.NewReader(b)) |
| if err != nil { |
| return BuildOutput{}, ErrBuild |
| @@ -178,12 +202,25 @@ func Run(ctx context.Context, workDir string, lock Lock) (BuildOutput, error) { |
| if runErr != nil { |
| return out, buildFailure("runUnit.start-wait", runErr) |
| } |
| + // The turn is held from here until the caller releases the output after |
| + // writing its response; every failure below hands it back. |
| + held, err := AwaitOutputTransfer(ctx) |
| + if err != nil { |
| + return out, buildFailure("runUnit.await-transfer", err) |
| + } |
| f, err := instancefs.OpenBeneath(workDir, "out/app", os.O_RDONLY, 0) |
| if err != nil { |
| + held.Release() |
| return out, buildFailure("runUnit.open-output", err) |
| } |
| defer f.Close() |
| - validated, err := ValidateOutput(f) |
| + validated, err := readOutput(f) |
| + if err != nil { |
| + held.Release() |
| + validated = BuildOutput{} |
| + } else { |
| + validated.hold = held.hold |
| + } |
| validated.Diagnostics = out.Diagnostics |
| validated.DiagnosticsTruncated = out.DiagnosticsTruncated |
| return validated, buildFailure("runUnit.validate-output", err) |
diff --git a/internal/demobuild/transfer.go b/internal/demobuild/transfer.go| new file mode 100644 |
| index 000000000..dad54d6ae |
| --- /dev/null |
| +++ b/internal/demobuild/transfer.go |
| @@ -0,0 +1,39 @@ |
| +package demobuild |
| + |
| +import ( |
| + "context" |
| + "sync" |
| +) |
| + |
| +// outputTransfer admits one finished build's output into root's memory at a |
| +// time (F3). An output is up to BinaryMaxBytes raw and about 4/3 of that |
| +// again once instance-control JSON-encodes it, so four slots finishing |
| +// together would hold four of each. The turn is taken before the output is |
| +// read and given back after its response is written; other finished builds |
| +// wait for it within their own deadline. |
| +var outputTransfer = make(chan struct{}, 1) |
| + |
| +type outputHold struct{ once sync.Once } |
| + |
| +// AwaitOutputTransfer waits for this process's output turn and returns an |
| +// empty output that holds it until Release. It fails when ctx ends first. |
| +func AwaitOutputTransfer(ctx context.Context) (BuildOutput, error) { |
| + if err := ctx.Err(); err != nil { |
| + return BuildOutput{}, err |
| + } |
| + select { |
| + case outputTransfer <- struct{}{}: |
| + return BuildOutput{hold: &outputHold{}}, nil |
| + case <-ctx.Done(): |
| + return BuildOutput{}, ctx.Err() |
| + } |
| +} |
| + |
| +// Release gives back the output turn o holds, if any. The holder calls it |
| +// once the output's bytes are no longer needed: after the response is |
| +// written, or when the output is discarded. Calling it again does nothing. |
| +func (o BuildOutput) Release() { |
| + if o.hold != nil { |
| + o.hold.once.Do(func() { <-outputTransfer }) |
| + } |
| +} |
diff --git a/internal/demobuild/transfer_test.go b/internal/demobuild/transfer_test.go| new file mode 100644 |
| index 000000000..459bdf16c |
| --- /dev/null |
| +++ b/internal/demobuild/transfer_test.go |
| @@ -0,0 +1,227 @@ |
| +//go:build linux |
| + |
| +package demobuild |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/binary" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "sync/atomic" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// arm64ELFOfSize is arm64ELF padded to n bytes, its one load segment |
| +// covering the whole file. |
| +func arm64ELFOfSize(n int) []byte { |
| + b := append(arm64ELF(), make([]byte, n-120)...) |
| + binary.LittleEndian.PutUint64(b[96:], uint64(n)) |
| + binary.LittleEndian.PutUint64(b[104:], uint64(n)) |
| + return b |
| +} |
| + |
| +func finishedBuild(t *testing.T, output []byte) (context.Context, string) { |
| + t.Helper() |
| + dir := t.TempDir() |
| + if err := os.Mkdir(filepath.Join(dir, "out"), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "out/app"), output, 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + i := &runInvocation{dir: dir, startWait: func(context.Context) error { return nil }, stop: func() error { return nil }} |
| + return context.WithValue(t.Context(), runContextKey{}, i), dir |
| +} |
| + |
| +// transferFree reports whether the one-at-a-time output turn is free now. |
| +func transferFree(t *testing.T) bool { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) |
| + defer cancel() |
| + out, err := AwaitOutputTransfer(ctx) |
| + if err != nil { |
| + return false |
| + } |
| + out.Release() |
| + return true |
| +} |
| + |
| +// Four builds that finish together read their outputs into memory one at a |
| +// time: each waits until the previous output is released (after its |
| +// response is written), and all four succeed. |
| +func TestDemoBuildOutputTransferSerialises(t *testing.T) { |
| + type result struct { |
| + out BuildOutput |
| + err error |
| + } |
| + results := make(chan result, 4) |
| + for range 4 { |
| + ctx, dir := finishedBuild(t, arm64ELFOfSize(1<<20)) |
| + go func() { |
| + out, err := Run(ctx, dir, testLock(t)) |
| + results <- result{out, err} |
| + }() |
| + } |
| + for n := range 4 { |
| + var r result |
| + select { |
| + case r = <-results: |
| + case <-time.After(5 * time.Second): |
| + t.Fatalf("build %d never admitted to transfer", n) |
| + } |
| + if r.err != nil || len(r.out.Binary) != 1<<20 || !ValidDigest(r.out.SHA256) { |
| + t.Fatalf("build %d: len=%d err=%v", n, len(r.out.Binary), r.err) |
| + } |
| + select { |
| + case other := <-results: |
| + other.out.Release() |
| + t.Fatalf("a second output was admitted while build %d held its turn", n) |
| + case <-time.After(100 * time.Millisecond): |
| + } |
| + r.out.Release() |
| + r.out.Release() // idempotent |
| + } |
| + if !transferFree(t) { |
| + t.Fatal("turn still held after every release") |
| + } |
| +} |
| + |
| +// A refused output and a failed build return the turn themselves. |
| +func TestDemoBuildOutputTransferReleasedOnFailure(t *testing.T) { |
| + ctx, dir := finishedBuild(t, []byte("not an executable")) |
| + if _, err := Run(ctx, dir, testLock(t)); err == nil { |
| + t.Fatal("accepted invalid output") |
| + } |
| + if !transferFree(t) { |
| + t.Fatal("refused output kept the turn") |
| + } |
| + ctx, dir = finishedBuild(t, arm64ELFOfSize(BinaryMaxBytes+1)) |
| + if _, err := Run(ctx, dir, testLock(t)); err == nil { |
| + t.Fatal("accepted oversized output") |
| + } |
| + if !transferFree(t) { |
| + t.Fatal("oversized output kept the turn") |
| + } |
| + // Scratch cleanup failing after a good output discards the output and |
| + // must hand its turn back. |
| + w, j, key, src := workerFixture(t) |
| + w.run = func(ctx context.Context, _ string, _ Lock) (BuildOutput, error) { |
| + return AwaitOutputTransfer(ctx) |
| + } |
| + w.prepare = func(context.Context, string, Source) (func() error, error) { |
| + return func() error { return errors.New("cleanup") }, nil |
| + } |
| + wire, err := SignJob(key, j) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := w.Build(t.Context(), wire, bytes.NewReader(src)); err == nil { |
| + t.Fatal("cleanup failure ignored") |
| + } |
| + if !transferFree(t) { |
| + t.Fatal("discarded output kept the turn") |
| + } |
| +} |
| + |
| +// The turn waits for the build's own deadline, no longer. |
| +func TestDemoBuildOutputTransferWaitHonoursDeadline(t *testing.T) { |
| + held, err := AwaitOutputTransfer(t.Context()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer held.Release() |
| + ctx, dir := finishedBuild(t, arm64ELF()) |
| + ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) |
| + defer cancel() |
| + if out, err := Run(ctx, dir, testLock(t)); err == nil || len(out.Binary) != 0 { |
| + t.Fatal("admitted a second output past its deadline") |
| + } |
| +} |
| + |
| +// TestDemoBuildOutputTransferPeak is a diagnostic, not a gate: it pushes |
| +// four 32 MiB outputs, one after another, through Run's read and |
| +// validation and the control response's JSON encoding, and logs the peak |
| +// Go heap and the process's peak RSS. Run it alone so the RSS is this |
| +// test's: |
| +// |
| +// CARLOS_DEMO_TRANSFER_PEAK=1 go test ./internal/demobuild -run '^TestDemoBuildOutputTransferPeak$' -count=1 -v |
| +// |
| +// The authority for the control service's cap is its cgroup's memory.peak |
| +// on a demo box, not this figure. |
| +func TestDemoBuildOutputTransferPeak(t *testing.T) { |
| + if os.Getenv("CARLOS_DEMO_TRANSFER_PEAK") == "" { |
| + t.Skip("set CARLOS_DEMO_TRANSFER_PEAK=1 to measure") |
| + } |
| + dir := t.TempDir() |
| + if err := os.Mkdir(filepath.Join(dir, "out"), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Written sparse so the fixture costs no memory of its own. |
| + header := arm64ELF() |
| + binary.LittleEndian.PutUint64(header[96:], BinaryMaxBytes) |
| + binary.LittleEndian.PutUint64(header[104:], BinaryMaxBytes) |
| + f, err := os.Create(filepath.Join(dir, "out/app")) |
| + if err == nil { |
| + _, err = f.Write(header) |
| + } |
| + if err == nil { |
| + err = f.Truncate(BinaryMaxBytes) |
| + } |
| + if err == nil { |
| + err = f.Close() |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + maxRSS := func() int64 { |
| + var ru syscall.Rusage |
| + _ = syscall.Getrusage(syscall.RUSAGE_SELF, &ru) |
| + return ru.Maxrss << 10 |
| + } |
| + var peakHeap, peakSys atomic.Uint64 |
| + stop := make(chan struct{}) |
| + sampled := make(chan struct{}) |
| + go func() { |
| + defer close(sampled) |
| + var m runtime.MemStats |
| + for { |
| + runtime.ReadMemStats(&m) |
| + if m.HeapAlloc > peakHeap.Load() { |
| + peakHeap.Store(m.HeapAlloc) |
| + } |
| + if m.Sys-m.HeapReleased > peakSys.Load() { |
| + peakSys.Store(m.Sys - m.HeapReleased) |
| + } |
| + select { |
| + case <-stop: |
| + return |
| + case <-time.After(time.Millisecond): |
| + } |
| + } |
| + }() |
| + runtime.GC() |
| + before := maxRSS() |
| + for n := range 4 { |
| + i := &runInvocation{dir: dir, startWait: func(context.Context) error { return nil }, stop: func() error { return nil }} |
| + out, err := Run(context.WithValue(t.Context(), runContextKey{}, i), dir, testLock(t)) |
| + if err != nil || len(out.Binary) != BinaryMaxBytes { |
| + t.Fatalf("transfer %d: %v", n, err) |
| + } |
| + if err := json.NewEncoder(io.Discard).Encode(out); err != nil { |
| + t.Fatal(err) |
| + } |
| + out.Release() |
| + } |
| + close(stop) |
| + <-sampled |
| + after := maxRSS() |
| + t.Logf("GOMEMLIMIT=%q GOGC=%q: peak HeapAlloc=%d MiB, peak Sys-HeapReleased=%d MiB, maxrss before=%d MiB after=%d MiB (delta %d MiB)", |
| + os.Getenv("GOMEMLIMIT"), os.Getenv("GOGC"), peakHeap.Load()>>20, peakSys.Load()>>20, before>>20, after>>20, (after-before)>>20) |
| +} |
diff --git a/internal/demobuild/worker.go b/internal/demobuild/worker.go| index 29c3c4cf2..5cfa7ff6a 100644 |
| --- a/internal/demobuild/worker.go |
| +++ b/internal/demobuild/worker.go |
| @@ -274,6 +274,7 @@ func (w *Worker) Build(ctx context.Context, wire []byte, source io.Reader) (out |
| w.mu.Lock() |
| w.poisoned = true |
| w.mu.Unlock() |
| + out.Release() |
| out = BuildOutput{} |
| err = errors.Join(err, e) |
| } |
diff --git a/internal/demobuild/worker_test.go b/internal/demobuild/worker_test.go| index e0cc2ba04..e8a4a73de 100644 |
| --- a/internal/demobuild/worker_test.go |
| +++ b/internal/demobuild/worker_test.go |
| @@ -171,6 +171,7 @@ func TestDemoBuildCleanupOrder(t *testing.T) { |
| return nil |
| }} |
| out, err := Run(context.WithValue(context.Background(), runContextKey{}, i), dir, testLock(t)) |
| + out.Release() |
| if !stopped || (err == nil) != (failure == "success") { |
| t.Fatalf("stop=%v err=%v", stopped, err) |
| } |
diff --git a/internal/host/demo_build_linux_test.go b/internal/host/demo_build_linux_test.go| index 25c29850f..858ff41d8 100644 |
| --- a/internal/host/demo_build_linux_test.go |
| +++ b/internal/host/demo_build_linux_test.go |
| @@ -63,11 +63,18 @@ func TestDemoBuildInstallation(t *testing.T) { |
| for n := 1; n <= 4; n++ { |
| cfg := claimUnitSettings{demo: demo.Config{Account: "shop", Fleet: "demo", Domain: "example.com", BuildWorker: true, BuildConcurrency: n}} |
| got := string(claimUnitContent(claimControlUnit, control, cfg)) |
| - for _, want := range []string{"StateDirectory=carlos-demo-builds", "StateDirectoryMode=0700", "ReadWritePaths=/var/lib/carlos-demo-builds", "MemoryMax=1073741824"} { |
| + for _, want := range []string{"StateDirectory=carlos-demo-builds", "StateDirectoryMode=0700", "ReadWritePaths=/var/lib/carlos-demo-builds"} { |
| if !strings.Contains(got, want) { |
| t.Error(want) |
| } |
| } |
| + // F3: the build worker's control service holds one 32 MiB output |
| + // transfer at a time (demobuild.AwaitOutputTransfer), measured at |
| + // about 118 MiB of live heap and 161 MiB of RSS growth. This cap and |
| + // collector limit cover it with room over the service's baseline. |
| + if strings.Count(got, "\nMemoryMax=") != 1 || !strings.Contains(got, "\nMemoryMax=1073741824\nEnvironment=GOMEMLIMIT=768MiB\n") { |
| + t.Errorf("build worker control memory:\n%s", got) |
| + } |
| got = string(claimUnitContent("carlos-demo-builds.slice", slice, cfg)) |
| if !strings.Contains(got, "MemoryMax="+strconv.FormatInt(int64(n)*1073741824, 10)+"\n") { |
| t.Fatal(got) |
diff --git a/internal/instancectl/demo_build.go b/internal/instancectl/demo_build.go| index 18f385aad..41ce48751 100644 |
| --- a/internal/instancectl/demo_build.go |
| +++ b/internal/instancectl/demo_build.go |
| @@ -165,6 +165,12 @@ func (s *Server) handleDemoBuild(w http.ResponseWriter, r *http.Request) { |
| _ = ctl.SetReadDeadline(grantDeadline) |
| } |
| out, err := s.DemoBuilder.Build(ctx, wire, r.Body) |
| + // A finished output holds the process's one output turn until its |
| + // response is written (demobuild.AwaitOutputTransfer). The write is |
| + // bounded so a stalled reader cannot keep the turn: the client gives up |
| + // five seconds after the build window too. |
| + defer out.Release() |
| + _ = ctl.SetWriteDeadline(deadline.Add(5 * time.Second)) |
| w.Header().Set("Content-Type", "application/json") |
| if err != nil { |
| out.Binary = nil |
diff --git a/internal/instancectl/demo_build_transfer_test.go b/internal/instancectl/demo_build_transfer_test.go| new file mode 100644 |
| index 000000000..1f581c156 |
| --- /dev/null |
| +++ b/internal/instancectl/demo_build_transfer_test.go |
| @@ -0,0 +1,107 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/binary" |
| + "encoding/hex" |
| + "io" |
| + "net" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demobuild" |
| +) |
| + |
| +// transferBuilder stands in for the worker: each build "finishes" by taking |
| +// the process's output turn, exactly as demobuild.Run does before it reads |
| +// the output, and returns an output still holding it. |
| +type transferBuilder struct { |
| + binary []byte |
| + turns atomic.Int32 |
| +} |
| + |
| +func (b *transferBuilder) Initialize(context.Context) error { return nil } |
| +func (b *transferBuilder) Readiness(context.Context) (demobuild.WorkerReady, error) { |
| + return demobuild.WorkerReady{Capability: "anonymous-demo-v1", GOARCH: "arm64", BundleSHA256: strings.Repeat("b", 64), Slots: 4}, nil |
| +} |
| +func (b *transferBuilder) GrantDeadline([]byte) (time.Time, error) { |
| + return time.Now().Add(time.Minute), nil |
| +} |
| +func (b *transferBuilder) Build(ctx context.Context, _ []byte, source io.Reader) (demobuild.BuildOutput, error) { |
| + if _, err := io.Copy(io.Discard, source); err != nil { |
| + return demobuild.BuildOutput{}, err |
| + } |
| + out, err := demobuild.AwaitOutputTransfer(ctx) |
| + if err != nil { |
| + return demobuild.BuildOutput{}, err |
| + } |
| + b.turns.Add(1) |
| + sum := sha256.Sum256(b.binary) |
| + out.Binary, out.SHA256 = b.binary, hex.EncodeToString(sum[:]) |
| + return out, nil |
| +} |
| + |
| +func transferELF(n int) []byte { |
| + b := make([]byte, n) |
| + copy(b, "\x7fELF\x02\x01\x01") |
| + binary.LittleEndian.PutUint16(b[16:], 2) |
| + binary.LittleEndian.PutUint16(b[18:], 183) |
| + binary.LittleEndian.PutUint32(b[20:], 1) |
| + binary.LittleEndian.PutUint64(b[24:], 0x400000) |
| + binary.LittleEndian.PutUint64(b[32:], 64) |
| + binary.LittleEndian.PutUint16(b[52:], 64) |
| + binary.LittleEndian.PutUint16(b[54:], 56) |
| + binary.LittleEndian.PutUint16(b[56:], 1) |
| + binary.LittleEndian.PutUint32(b[64:], 1) |
| + binary.LittleEndian.PutUint32(b[68:], 5) |
| + binary.LittleEndian.PutUint64(b[80:], 0x400000) |
| + binary.LittleEndian.PutUint64(b[96:], uint64(n)) |
| + binary.LittleEndian.PutUint64(b[104:], uint64(n)) |
| + return b |
| +} |
| + |
| +// Four builds that finish together each get the output turn in turn: the |
| +// handler hands it back once the response is written, so all four |
| +// responses arrive whole. A handler that kept the turn would leave the |
| +// other three waiting until their deadlines. |
| +func TestDemoBuildFourFinishedBuildsTakeTurns(t *testing.T) { |
| + b := &transferBuilder{binary: transferELF(4 << 20)} |
| + s := &Server{DemoBox: true, DemoBuilder: b} |
| + srv := httptest.NewServer(s.Handler()) |
| + defer srv.Close() |
| + addr := strings.TrimPrefix(srv.URL, "http://") |
| + c := &Client{Path: "control", Dial: func(ctx context.Context, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "tcp", addr) |
| + }} |
| + errs := make(chan error, 4) |
| + for range 4 { |
| + go func() { |
| + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) |
| + defer cancel() |
| + out, err := c.BuildDemo(ctx, []byte("grant"), strings.NewReader("source")) |
| + if err == nil && len(out.Binary) != 4<<20 { |
| + err = demobuild.ErrBuild |
| + } |
| + errs <- err |
| + }() |
| + } |
| + for range 4 { |
| + if err := <-errs; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if b.turns.Load() != 4 { |
| + t.Fatalf("turns=%d", b.turns.Load()) |
| + } |
| + ctx, cancel := context.WithTimeout(t.Context(), time.Second) |
| + defer cancel() |
| + free, err := demobuild.AwaitOutputTransfer(ctx) |
| + if err != nil { |
| + t.Fatal("the output turn was not handed back after the last response") |
| + } |
| + free.Release() |
| +} |