carlos / platform Public

activator: production-wired witnesses for held streams with a real child (#432)

Human

Prompt

Task 8 of #432: production-wired witnesses (real Service on
ExecBackend, real edge.New, real SSE child) for spec cases 1-7, 10, 13
and the leg header and cookie witnesses.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

fakeAppMain gains an SSE mode (ACTIVATOR_FAKE_APP_SSE=1) that
streams ids from a file, honours Last-Event-ID, and logs requests and
its SIGTERM drain. heldstream_e2e_test.go wires a real registry, Service
(process seams on ExecBackend), edge and an SSE-spec browser stand-in,
and adds twelve TestHeldE2E witnesses. Dropping cancelHeldLegsLocked
from beginStopLocked makes the fast-drain witness fail (15 s drain).
The edge's home-map arming moves into an exported ArmHomeMap so a
witness can sign legs with a real mesh key; startup calls it as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0ece5cf995fd93d537d04a132dfcf8ddbebd5d58 parent c9bcf63
4 files changed, +1,116 −8
  • internal/activator/activator_test.go +136 −0
  • internal/activator/heldstream_e2e_test.go +957 −0
  • internal/edge/edge.go +2 −8
  • internal/edge/homemap.go +21 −0

CI cancelled — superseded by a newer push — run details

diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go
index d678dea3c..1d7af31a5 100644
--- a/internal/activator/activator_test.go
+++ b/internal/activator/activator_test.go
@@ -12,6 +12,7 @@ package activator
import (
"context"
"database/sql"
+ "encoding/json"
"errors"
"fmt"
"io"
@@ -21,8 +22,10 @@ import (
"net/http/httputil"
"os"
"os/exec"
+ "os/signal"
"path/filepath"
"slices"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -6247,6 +6250,10 @@ func fakeAppMain() {
if err := os.Chmod(socket, 0o600); err != nil {
os.Exit(1)
}
+ if os.Getenv("ACTIVATOR_FAKE_APP_SSE") == "1" {
+ fakeAppSSEMain(ln)
+ return
+ }
status := http.StatusOK
if os.Getenv("ACTIVATOR_FAKE_APP_UNHEALTHY") == "1" {
status = http.StatusInternalServerError
@@ -6256,6 +6263,135 @@ func fakeAppMain() {
}))
}
+// fakeAppRecord is one line of the SSE-mode child's log
+// (ACTIVATOR_FAKE_APP_LOG): "start" when it binds, "req" per request,
+// "sigterm" when SIGTERM arrives and "shutdown" when srv.Shutdown returns.
+// At is wall-clock nanoseconds; Ms is the shutdown's duration.
+type fakeAppRecord struct {
+ Pid int `json:"pid"`
+ Kind string `json:"kind"`
+ At int64 `json:"at"`
+ Path string `json:"path,omitempty"`
+ Query string `json:"query,omitempty"`
+ Header map[string][]string `json:"header,omitempty"`
+ Ms int64 `json:"ms,omitempty"`
+ Err string `json:"err,omitempty"`
+}
+
+// fakeAppSSEMain is fakeAppMain's SSE mode (ACTIVATOR_FAKE_APP_SSE=1), the
+// real child the edge-held stream witnesses run (heldstream_e2e_test.go).
+// GET /live is an event stream: event n is line n of the file
+// ACTIVATOR_FAKE_APP_EVENTS (the test appends lines; the handler polls the
+// file every 20 ms, a stand-in for an app's own notify), sent as "id: n",
+// starting after Last-Event-ID when the request carries one. The handler
+// returns as soon as r.Context() is done. Query switches: expire=1 answers
+// 401; redirect=1 answers 303 to /login; cookie=1 sets a cross-domain
+// Set-Cookie on the process's first /live answer; oneshot=1 ends the stream
+// after one event; end=1 ends it right after the head. Every other path
+// answers 200 (the health wait, a plain waking request). On SIGTERM it runs
+// srv.Shutdown with a 15 s context: an open /live handler that nothing
+// cancels holds that drain, which the log's shutdown duration shows.
+func fakeAppSSEMain(ln net.Listener) {
+ pid := os.Getpid()
+ logPath, eventsPath := os.Getenv("ACTIVATOR_FAKE_APP_LOG"), os.Getenv("ACTIVATOR_FAKE_APP_EVENTS")
+ var logMu sync.Mutex
+ logRec := func(rec fakeAppRecord) {
+ rec.Pid = pid
+ if rec.At == 0 {
+ rec.At = time.Now().UnixNano()
+ }
+ b, _ := json.Marshal(rec)
+ logMu.Lock()
+ defer logMu.Unlock()
+ f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
+ if err != nil {
+ return
+ }
+ _, _ = f.Write(append(b, '\n'))
+ _ = f.Close()
+ }
+ events := func() []string {
+ raw, _ := os.ReadFile(eventsPath)
+ lines := strings.SplitAfter(string(raw), "\n")
+ var out []string
+ for _, l := range lines {
+ if strings.HasSuffix(l, "\n") { // a line still being written waits
+ out = append(out, strings.TrimSuffix(l, "\n"))
+ }
+ }
+ return out
+ }
+ var cookieSent atomic.Bool
+ h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ logRec(fakeAppRecord{Kind: "req", Path: r.URL.Path, Query: r.URL.RawQuery, Header: r.Header.Clone()})
+ if r.URL.Path != "/live" {
+ w.WriteHeader(http.StatusOK)
+ return
+ }
+ q := r.URL.Query()
+ switch {
+ case q.Get("expire") == "1":
+ http.Error(w, "session expired", http.StatusUnauthorized)
+ return
+ case q.Get("redirect") == "1":
+ http.Redirect(w, r, "/login", http.StatusSeeOther)
+ return
+ }
+ if q.Get("cookie") == "1" && cookieSent.CompareAndSwap(false, true) {
+ w.Header().Add("Set-Cookie", "s=1; Path=/; Domain=other.example.com")
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.Header().Set("X-Fake-App", "sse")
+ w.WriteHeader(http.StatusOK)
+ rc := http.NewResponseController(w)
+ _ = rc.Flush()
+ if q.Get("end") == "1" {
+ return
+ }
+ last, _ := strconv.Atoi(r.Header.Get("Last-Event-ID"))
+ tick := time.NewTicker(20 * time.Millisecond)
+ defer tick.Stop()
+ for {
+ ev := events()
+ for last < len(ev) {
+ last++
+ if _, err := fmt.Fprintf(w, "id: %d\ndata: %s\n\n", last, ev[last-1]); err != nil {
+ return
+ }
+ if rc.Flush() != nil {
+ return
+ }
+ if q.Get("oneshot") == "1" {
+ return
+ }
+ }
+ select {
+ case <-r.Context().Done():
+ return
+ case <-tick.C:
+ }
+ }
+ })
+ srv := &http.Server{Handler: h}
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, syscall.SIGTERM)
+ logRec(fakeAppRecord{Kind: "start"})
+ go func() { _ = srv.Serve(ln) }()
+ <-sig
+ began := time.Now()
+ logRec(fakeAppRecord{Kind: "sigterm", At: began.UnixNano()})
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ err := srv.Shutdown(ctx)
+ cancel()
+ rec := fakeAppRecord{Kind: "shutdown", Ms: time.Since(began).Milliseconds()}
+ if err != nil {
+ rec.Err = err.Error()
+ }
+ logRec(rec)
+ os.Exit(0)
+}
+
// stageServingLive points live/<host> at the test binary itself (see
// TestMain) so Start spawns a child that actually binds and serves.
func stageServingLive(t *testing.T, b *ExecBackend, host string) {
diff --git a/internal/activator/heldstream_e2e_test.go b/internal/activator/heldstream_e2e_test.go
new file mode 100644
index 000000000..9575d723f
--- /dev/null
+++ b/internal/activator/heldstream_e2e_test.go
@@ -0,0 +1,957 @@
+package activator
+
+// Production-wired witnesses for edge-held event streams (spec
+// docs/superpowers/specs/2026-10-28-edge-held-streams-design.md §5, §7): a
+// real activator.Service whose processes are real ExecBackend children (the
+// test binary in fakeAppMain's SSE mode, fakeAppSSEMain), a real edge built
+// with edge.New over the same registry, and a browser stand-in that parses
+// the stream by the SSE spec's rules. The lease, restore and cgroup-parent
+// seams are the package's fakes (fakeSwapBackend), as in every other
+// real-child test here; every process start, stop and generation spawn is
+// ExecBackend's own.
+//
+// Socket tests: run with the sandbox off, TMPDIR a short root
+// (common.md: T=$(mktemp -d /tmp/hsXXXX)).
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgeproof"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const e2eHost = "shop.example.com"
+
+// heldE2EBackend is the fake lease/restore/parent-limit seams with every
+// process seam on a real ExecBackend: the wake's identity capture and spawn
+// (LiveIdentity, StartGenExe, StartGen, Start), a swap's successor
+// (StartStaged), and the layout the swap decides on.
+type heldE2EBackend struct {
+ *fakeSwapBackend
+ exec *ExecBackend
+}
+
+func (b *heldE2EBackend) Start(ctx context.Context, rt registry.Route) (Proc, string, error) {
+ return b.exec.Start(ctx, rt)
+}
+
+func (b *heldE2EBackend) StartGen(ctx context.Context, rt registry.Route, n uint64, perGen bool) (Proc, Gen, error) {
+ return b.exec.StartGen(ctx, rt, n, perGen)
+}
+
+func (b *heldE2EBackend) NextDueVia(ctx context.Context, rt registry.Route, _ string) (int64, error) {
+ return b.fakeBackend.NextDue(ctx, rt)
+}
+
+func (b *heldE2EBackend) LiveIdentity(ctx context.Context, rt registry.Route) (release.StagedIdentity, error) {
+ return b.exec.LiveIdentity(ctx, rt)
+}
+
+func (b *heldE2EBackend) StartGenExe(ctx context.Context, rt registry.Route, n uint64, perGen bool, id release.StagedIdentity) (Proc, Gen, error) {
+ return b.exec.StartGenExe(ctx, rt, n, perGen, id)
+}
+
+func (b *heldE2EBackend) StartStaged(ctx context.Context, rt registry.Route, g Gen) (Gen, Proc, error) {
+ return b.exec.StartStaged(ctx, rt, g)
+}
+
+func (b *heldE2EBackend) Layout(rt registry.Route) (Layout, string) { return b.exec.Layout(rt) }
+
+func (b *heldE2EBackend) GenLayout(rt registry.Route) Layout { return b.exec.GenLayout(rt) }
+
+func (b *heldE2EBackend) GenReady(rt registry.Route, g Gen, p Proc) { b.exec.GenReady(rt, g, p) }
+
+// e2eHeldConfig is the held-stream config the witnesses run: the spec's
+// shapes, shortened (Tick 200 ms).
+func e2eHeldConfig() edge.HeldConfig {
+ c := edge.DefaultHeldConfig
+ c.Commit = 300 * time.Millisecond
+ c.LegHeader = 3 * time.Second
+ c.WriteDeadline = 3 * time.Second
+ c.Tick = 200 * time.Millisecond
+ c.ReopenSpacing = 50 * time.Millisecond
+ c.BackoffCap = time.Second
+ return c
+}
+
+type heldE2EOpts struct {
+ idle time.Duration
+ cfg edge.HeldConfig
+ gens bool
+ // beforeReload runs on the edge after edge.New, before its first Reload.
+ beforeReload func(e *edge.Edge)
+}
+
+// heldE2E is one production-wired box: registry, Service, edge, front
+// server, and the child's log and event files.
+type heldE2E struct {
+ t *testing.T
+ a *Service
+ exec *ExecBackend
+ reg *registry.Registry
+ e *edge.Edge
+ front *httptest.Server
+ rt registry.Route
+ cfg edge.HeldConfig
+ log string
+ events string
+}
+
+func newHeldE2E(t *testing.T, o heldE2EOpts) *heldE2E {
+ t.Helper()
+ requireUnixSockets(t)
+ if o.cfg == (edge.HeldConfig{}) {
+ o.cfg = e2eHeldConfig()
+ }
+ exec := testExecBackend(t)
+ exec.RunDirOverride = shortRunDir(t)
+ dir := t.TempDir()
+ h := &heldE2E{t: t, exec: exec, cfg: o.cfg, log: filepath.Join(dir, "app.log"), events: filepath.Join(dir, "events")}
+ if err := os.WriteFile(h.events, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ stageVersion(t, exec, e2eHost, "v1", servingBody(t, filepath.Join(dir, "argv0")))
+ t.Setenv("ACTIVATOR_FAKE_APP_SSE", "1")
+ t.Setenv("ACTIVATOR_FAKE_APP_LOG", h.log)
+ t.Setenv("ACTIVATOR_FAKE_APP_EVENTS", h.events)
+
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ h.reg = reg
+ h.rt = flatGenRoute(exec, e2eHost)
+ h.rt.Status, h.rt.Incarnation = "ready", 1
+ if err := reg.Upsert(h.rt); err != nil {
+ t.Fatal(err)
+ }
+ be := &heldE2EBackend{fakeSwapBackend: &fakeSwapBackend{fakeBackend: &fakeBackend{}}, exec: exec}
+ h.a = New(Config{Bucket: "test-bucket", Idle: o.idle}, be, reg)
+ h.a.gens = o.gens
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ h.a.Shutdown(ctx)
+ })
+ stop := make(chan struct{})
+ swept := make(chan struct{})
+ go func() {
+ defer close(swept)
+ tk := time.NewTicker(50 * time.Millisecond)
+ defer tk.Stop()
+ for {
+ select {
+ case <-stop:
+ return
+ case <-tk.C:
+ h.a.sweepOnce()
+ }
+ }
+ }()
+ t.Cleanup(func() { close(stop); <-swept })
+ h.e, h.front = h.newEdge(o.beforeReload)
+ return h
+}
+
+// newEdge builds an edge over h's registry and Service with h's held
+// config, points the Service's held wake hook at it, and serves it.
+func (h *heldE2E) newEdge(beforeReload func(*edge.Edge)) (*edge.Edge, *httptest.Server) {
+ t := h.t
+ t.Helper()
+ e, err := edge.New(h.reg, h.a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e.SetHeldConfig(h.cfg)
+ if beforeReload != nil {
+ beforeReload(e)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ h.a.SetHeldWakeHook(e.HeldWake)
+ front := httptest.NewServer(e)
+ t.Cleanup(func() {
+ front.CloseClientConnections()
+ front.Close()
+ })
+ return e, front
+}
+
+// plain sends one ordinary (unmarked) request: it wakes the host and is
+// activity.
+func (h *heldE2E) plain(path string) int {
+ h.t.Helper()
+ req, err := http.NewRequest(http.MethodGet, h.front.URL+path, nil)
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ req.Host = e2eHost
+ c := &http.Client{Timeout: 30 * time.Second}
+ resp, err := c.Do(req)
+ if err != nil {
+ h.t.Fatalf("plain %s: %v", path, err)
+ }
+ _, _ = io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ return resp.StatusCode
+}
+
+// wake wakes the host with a plain request and returns the child's pid.
+func (h *heldE2E) wake() int {
+ h.t.Helper()
+ before := len(h.starts())
+ if code := h.plain("/ping"); code != http.StatusOK {
+ h.t.Fatalf("plain wake answered %d", code)
+ }
+ starts := h.starts()
+ if len(starts) != before+1 {
+ h.t.Fatalf("plain wake: %d child starts, want %d", len(starts), before+1)
+ }
+ return starts[len(starts)-1]
+}
+
+func (h *heldE2E) appendEvent(data string) {
+ h.t.Helper()
+ f, err := os.OpenFile(h.events, os.O_APPEND|os.O_WRONLY, 0o644)
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ defer f.Close()
+ if _, err := f.WriteString(data + "\n"); err != nil {
+ h.t.Fatal(err)
+ }
+}
+
+// records is the child log so far, every process's.
+func (h *heldE2E) records() []fakeAppRecord {
+ h.t.Helper()
+ raw, err := os.ReadFile(h.log)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ h.t.Fatal(err)
+ }
+ var out []fakeAppRecord
+ for _, line := range bytes.Split(raw, []byte("\n")) {
+ if len(line) == 0 {
+ continue
+ }
+ var r fakeAppRecord
+ if err := json.Unmarshal(line, &r); err != nil {
+ continue // a line still being written
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+// starts is the pids of every child started, in order.
+func (h *heldE2E) starts() []int {
+ var pids []int
+ for _, r := range h.records() {
+ if r.Kind == "start" {
+ pids = append(pids, r.Pid)
+ }
+ }
+ return pids
+}
+
+// find returns pid's first record of kind.
+func (h *heldE2E) find(pid int, kind string) (fakeAppRecord, bool) {
+ for _, r := range h.records() {
+ if r.Pid == pid && r.Kind == kind {
+ return r, true
+ }
+ }
+ return fakeAppRecord{}, false
+}
+
+// liveReqs is every /live request the child pid served, in order.
+func (h *heldE2E) liveReqs(pid int) []fakeAppRecord {
+ var out []fakeAppRecord
+ for _, r := range h.records() {
+ if r.Kind == "req" && r.Path == "/live" && (pid == 0 || r.Pid == pid) {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+// asleep reports whether the Service has no entry for the host.
+func (h *heldE2E) asleep() bool {
+ h.a.mu.Lock()
+ defer h.a.mu.Unlock()
+ return h.a.entries[e2eHost] == nil
+}
+
+// shutdownOf waits for pid's logged shutdown, up to within.
+func (h *heldE2E) shutdownOf(pid int, within time.Duration) fakeAppRecord {
+ h.t.Helper()
+ var rec fakeAppRecord
+ waitE2E(h.t, within, fmt.Sprintf("child %d's shutdown", pid), func() bool {
+ var ok bool
+ rec, ok = h.find(pid, "shutdown")
+ return ok
+ })
+ return rec
+}
+
+// waitE2E polls cond every 20 ms until it holds or within passes.
+func waitE2E(t *testing.T, within time.Duration, what string, cond func() bool) {
+ t.Helper()
+ deadline := time.Now().Add(within)
+ for !cond() {
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out after %s waiting for %s", within, what)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+}
+
+// --- the browser stand-in ----------------------------------------------------
+
+type sseEvent struct{ id, data string }
+
+// sseBrowser is an EventSource stand-in that follows the SSE spec's parsing
+// rules: each connection's stream starts with an empty last-event-ID
+// buffer; an "id" field without NUL sets it; a blank line dispatches, which
+// copies the buffer to the source's last event ID string whether or not
+// the block had data; a comment line dispatches nothing. A reconnect sends
+// the last event ID string as Last-Event-ID when it is not empty.
+type sseBrowser struct {
+ t *testing.T
+ url string
+ header http.Header
+ tr *http.Transport
+
+ mu sync.Mutex
+ lastID string
+ events []sseEvent
+ pings int
+ sent []string // the Last-Event-ID each connection sent
+}
+
+type sseConn struct {
+ resp *http.Response
+ body []byte // a non-event-stream answer's body
+ cancel context.CancelFunc
+ done chan struct{}
+}
+
+func newBrowser(t *testing.T, base, target string) *sseBrowser {
+ b := &sseBrowser{t: t, url: base + target, header: http.Header{}, tr: &http.Transport{DisableCompression: true}}
+ t.Cleanup(b.tr.CloseIdleConnections)
+ return b
+}
+
+// connect opens one connection. Its reader runs until the stream ends; the
+// test ends it with close.
+func (b *sseBrowser) connect() *sseConn {
+ b.t.Helper()
+ ctx, cancel := context.WithCancel(context.Background())
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, b.url, nil)
+ if err != nil {
+ b.t.Fatal(err)
+ }
+ req.Host = e2eHost
+ for k, vs := range b.header {
+ req.Header[k] = vs
+ }
+ req.Header.Set("Accept", "text/event-stream")
+ b.mu.Lock()
+ id := b.lastID
+ b.sent = append(b.sent, id)
+ b.mu.Unlock()
+ if id != "" {
+ req.Header.Set("Last-Event-ID", id)
+ }
+ c := &http.Client{Transport: b.tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ resp, err := c.Do(req)
+ if err != nil {
+ cancel()
+ b.t.Fatalf("connect %s: %v", b.url, err)
+ }
+ conn := &sseConn{resp: resp, cancel: cancel, done: make(chan struct{})}
+ b.t.Cleanup(conn.close)
+ if resp.StatusCode != http.StatusOK || !strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") {
+ conn.body, _ = io.ReadAll(resp.Body)
+ resp.Body.Close()
+ close(conn.done)
+ return conn
+ }
+ go b.read(conn)
+ return conn
+}
+
+func (c *sseConn) close() {
+ c.cancel()
+ <-c.done
+}
+
+// ended reports whether the stream has ended.
+func (c *sseConn) ended() bool {
+ select {
+ case <-c.done:
+ return true
+ default:
+ return false
+ }
+}
+
+func (b *sseBrowser) read(c *sseConn) {
+ defer close(c.done)
+ defer c.resp.Body.Close()
+ rd := bufio.NewReader(c.resp.Body)
+ idBuf := "" // the last-event-ID buffer: empty on every new connection
+ var data []string
+ hasData := false
+ for {
+ line, err := rd.ReadString('\n')
+ if err != nil {
+ return
+ }
+ line = strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r")
+ switch {
+ case line == "":
+ b.mu.Lock()
+ b.lastID = idBuf
+ if hasData {
+ b.events = append(b.events, sseEvent{id: idBuf, data: strings.Join(data, "\n")})
+ }
+ b.mu.Unlock()
+ data, hasData = nil, false
+ case strings.HasPrefix(line, ":"):
+ if line == ": ping" {
+ b.mu.Lock()
+ b.pings++
+ b.mu.Unlock()
+ }
+ default:
+ field, value, _ := strings.Cut(line, ":")
+ value = strings.TrimPrefix(value, " ")
+ switch field {
+ case "id":
+ if !strings.Contains(value, "\x00") {
+ idBuf = value
+ }
+ case "data":
+ data, hasData = append(data, value), true
+ }
+ }
+ }
+}
+
+func (b *sseBrowser) snapshot() (events []sseEvent, pings int, lastID string) {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return append([]sseEvent(nil), b.events...), b.pings, b.lastID
+}
+
+func (b *sseBrowser) pingCount() int {
+ _, p, _ := b.snapshot()
+ return p
+}
+
+func (b *sseBrowser) eventCount() int {
+ ev, _, _ := b.snapshot()
+ return len(ev)
+}
+
+// waitEvents waits until the browser has n events.
+func (b *sseBrowser) waitEvents(n int, within time.Duration) []sseEvent {
+ b.t.Helper()
+ waitE2E(b.t, within, fmt.Sprintf("%d events", n), func() bool { return b.eventCount() >= n })
+ ev, _, _ := b.snapshot()
+ return ev
+}
+
+// waitPings waits for n more heartbeats than the browser has now.
+func (b *sseBrowser) waitPings(n int, within time.Duration) {
+ b.t.Helper()
+ from := b.pingCount()
+ waitE2E(b.t, within, fmt.Sprintf("%d heartbeats", n), func() bool { return b.pingCount() >= from+n })
+}
+
+// wantEvents checks the browser's events are exactly ids 1..n with data
+// e1..en, in order: nothing missed, nothing duplicated.
+func wantEvents(t *testing.T, got []sseEvent, n int) {
+ t.Helper()
+ if len(got) != n {
+ t.Fatalf("browser has %d events %v, want exactly %d", len(got), got, n)
+ }
+ for i, ev := range got {
+ if want := (sseEvent{id: fmt.Sprint(i + 1), data: fmt.Sprintf("e%d", i+1)}); ev != want {
+ t.Fatalf("event %d = %+v, want %+v (all: %v)", i, ev, want, got)
+ }
+ }
+}
+
+const heldPath = "/live?carlos_hold=1"
+
+// --- the witnesses -----------------------------------------------------------
+
+// Case 1: asleep, a browser connects. The edge answers 200 itself and
+// heartbeats; nothing wakes, nothing is activity.
+func TestHeldE2EAsleepNoWake(t *testing.T) {
+ idle := 500 * time.Millisecond
+ h := newHeldE2E(t, heldE2EOpts{idle: idle})
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ if c.resp.StatusCode != http.StatusOK || c.resp.Header.Get("X-Fake-App") != "" {
+ t.Fatalf("held answer: %d %v, want the edge's own 200", c.resp.StatusCode, c.resp.Header)
+ }
+ time.Sleep(3 * idle)
+ if s := h.starts(); len(s) != 0 {
+ t.Fatalf("a held stream on an asleep host started %d child(ren)", len(s))
+ }
+ if !h.asleep() {
+ t.Fatal("the held stream made an activator entry for an asleep host")
+ }
+ if p := b.pingCount(); p < 3 {
+ t.Fatalf("%d heartbeats in %s at Tick %s, want at least 3", p, 3*idle, h.cfg.Tick)
+ }
+ if c.ended() {
+ t.Fatal("the held stream ended")
+ }
+ if st := h.e.HeldStreamStats(); st.Held != 1 || st.Hosts[e2eHost] != 1 {
+ t.Fatalf("held-stream stats %+v, want one stream held for %s", st, e2eHost)
+ }
+}
+
+// Case 2: awake, a browser connects. The app's own answer is passed
+// through, and the instance still hibernates after its idle window with
+// the stream open: the leg is not activity.
+func TestHeldE2EAwakeStillSleeps(t *testing.T) {
+ idle := 600 * time.Millisecond
+ h := newHeldE2E(t, heldE2EOpts{idle: idle})
+ pid := h.wake()
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ if c.resp.StatusCode != http.StatusOK || c.resp.Header.Get("X-Fake-App") != "sse" {
+ t.Fatalf("first answer %d %v, want the app's own 200 passed through", c.resp.StatusCode, c.resp.Header)
+ }
+ if got := c.resp.Header.Get("Cache-Control"); got != "no-store" {
+ t.Fatalf("Cache-Control = %q, want no-store in place of the app's", got)
+ }
+ opened := time.Now()
+ waitE2E(t, 10*idle, "the instance to hibernate under the open stream", h.asleep)
+ if took := time.Since(opened); took < idle/2 {
+ t.Fatalf("slept %s after the stream opened; the idle window is %s", took, idle)
+ }
+ h.shutdownOf(pid, 5*time.Second)
+ if c.ended() {
+ t.Fatal("the browser's stream ended with the instance's sleep")
+ }
+ b.waitPings(2, 5*time.Second)
+ if len(h.liveReqs(pid)) != 1 {
+ t.Fatalf("/live requests %d, want the one leg", len(h.liveReqs(pid)))
+ }
+}
+
+// Case 3 (Review Focus 3): the instance sleeps under an open stream.
+// beginStopLocked cancels the leg before SIGTERM, so the app's drain has no
+// stream handler to wait for: its logged srv.Shutdown takes well under the
+// 15 s the open handler would otherwise hold it. Mutation (report): with the
+// cancelHeldLegsLocked call dropped from beginStopLocked, the logged drain
+// is ~15 s and this fails.
+func TestHeldE2ESleepFastDrain(t *testing.T) {
+ idle := 600 * time.Millisecond
+ h := newHeldE2E(t, heldE2EOpts{idle: idle})
+ pid := h.wake()
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ h.appendEvent("e1")
+ b.waitEvents(1, 5*time.Second)
+ rec := h.shutdownOf(pid, 25*time.Second)
+ if rec.Ms >= 2000 || rec.Err != "" {
+ t.Fatalf("the app's SIGTERM drain took %d ms (%q) with a held stream open, want under 2000: the leg was not cancelled before the stop", rec.Ms, rec.Err)
+ }
+ b.waitPings(2, 5*time.Second)
+ if c.ended() {
+ t.Fatal("the browser's stream ended with the instance's sleep")
+ }
+}
+
+// Case 4: events 1-2 relayed; the instance sleeps; a plain request wakes it
+// and the test appends event 3. The stream resumes on the new process with
+// Last-Event-ID 2, and the browser receives event 3 next, with no duplicate.
+func TestHeldE2EResumeAcrossSleep(t *testing.T) {
+ idle := 600 * time.Millisecond
+ h := newHeldE2E(t, heldE2EOpts{idle: idle})
+ pid1 := h.wake()
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ h.appendEvent("e1")
+ h.appendEvent("e2")
+ b.waitEvents(2, 5*time.Second)
+ waitE2E(t, 10*idle, "sleep", h.asleep)
+ h.shutdownOf(pid1, 5*time.Second)
+ b.waitPings(1, 5*time.Second)
+
+ pid2 := h.wake()
+ h.appendEvent("e3")
+ wantEvents(t, b.waitEvents(3, 5*time.Second), 3)
+ time.Sleep(300 * time.Millisecond) // nothing more arrives
+ ev, _, lastID := b.snapshot()
+ wantEvents(t, ev, 3)
+ if lastID != "3" {
+ t.Fatalf("browser last event ID %q, want 3", lastID)
+ }
+ legs := h.liveReqs(pid2)
+ if len(legs) != 1 || http.Header(legs[0].Header).Get("Last-Event-ID") != "2" {
+ t.Fatalf("legs on the woken process: %+v, want one with Last-Event-ID 2", legs)
+ }
+ if c.ended() {
+ t.Fatal("the browser's stream ended")
+ }
+ if st := h.e.HeldStreamStats(); st.Resumes < 1 {
+ t.Fatalf("held-stream stats %+v, want at least one resume", st)
+ }
+ if n := len(h.starts()); n != 2 {
+ t.Fatalf("%d child starts, want 2 (the two plain wakes)", n)
+ }
+}
+
+// Review Focus 1: a browser that follows the SSE parsing rules reconnects
+// twice, across two sleeps, with heartbeats between; each reconnect sends
+// the last event id it received. The edge's seed block on a held answer
+// and its blank-line-free heartbeats leave the browser's cursor alone.
+func TestHeldE2ETwoReconnectsKeepCursor(t *testing.T) {
+ idle := 600 * time.Millisecond
+ h := newHeldE2E(t, heldE2EOpts{idle: idle})
+ pid1 := h.wake()
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ h.appendEvent("e1")
+ h.appendEvent("e2")
+ b.waitEvents(2, 5*time.Second)
+
+ // Sleep 1, heartbeats, reconnect 1 (held: the edge's own answer).
+ waitE2E(t, 10*idle, "sleep 1", h.asleep)
+ h.shutdownOf(pid1, 5*time.Second)
+ b.waitPings(2, 5*time.Second)
+ c.close()
+ c = b.connect()
+ if c.resp.Header.Get("X-Fake-App") != "" {
+ t.Fatal("reconnect 1 reached the app while asleep")
+ }
+ b.waitPings(2, 5*time.Second)
+ if _, _, id := b.snapshot(); id != "2" {
+ t.Fatalf("after reconnect 1 and heartbeats the browser's cursor is %q, want 2", id)
+ }
+
+ // Wake, event 3, sleep 2, heartbeats, reconnect 2.
+ pid2 := h.wake()
+ h.appendEvent("e3")
+ b.waitEvents(3, 5*time.Second)
+ waitE2E(t, 10*idle, "sleep 2", h.asleep)
+ h.shutdownOf(pid2, 5*time.Second)
+ b.waitPings(2, 5*time.Second)
+ c.close()
+ c = b.connect()
+ b.waitPings(2, 5*time.Second)
+
+ b.mu.Lock()
+ sent := append([]string(nil), b.sent...)
+ b.mu.Unlock()
+ if len(sent) != 3 || sent[0] != "" || sent[1] != "2" || sent[2] != "3" {
+ t.Fatalf("Last-Event-ID per connection %q, want [\"\" 2 3]", sent)
+ }
+ // And the cursor survives into the next wake: the leg resumes after 3.
+ pid3 := h.wake()
+ h.appendEvent("e4")
+ wantEvents(t, b.waitEvents(4, 5*time.Second), 4)
+ legs := h.liveReqs(pid3)
+ if len(legs) != 1 || http.Header(legs[0].Header).Get("Last-Event-ID") != "3" {
+ t.Fatalf("legs after reconnect 2: %+v, want one with Last-Event-ID 3", legs)
+ }
+ if c.ended() {
+ t.Fatal("the stream ended")
+ }
+}
+
+// Case 5: the app ends /live after each event while awake. The edge
+// reopens without a new wake, its legs at least ReopenSpacing apart, and
+// the browser's one connection carries every event once.
+func TestHeldE2EAppEndsStreamWhileAwake(t *testing.T) {
+ cfg := e2eHeldConfig()
+ cfg.ReopenSpacing = 300 * time.Millisecond
+ cfg.ShortLeg = 0 // every leg counts as long: this is the spacing rule alone
+ h := newHeldE2E(t, heldE2EOpts{idle: time.Minute, cfg: cfg})
+ pid := h.wake()
+ for i := 1; i <= 4; i++ {
+ h.appendEvent(fmt.Sprintf("e%d", i))
+ }
+ b := newBrowser(t, h.front.URL, "/live?oneshot=1&carlos_hold=1")
+ c := b.connect()
+ wantEvents(t, b.waitEvents(4, 10*time.Second), 4)
+ waitE2E(t, 5*time.Second, "the fifth leg", func() bool { return len(h.liveReqs(pid)) >= 5 })
+ legs := h.liveReqs(pid)
+ // The edge spaces its opens on its own clock; the child sees each one a
+ // dial later, so a gap may read a few ms short of the spacing.
+ const dialJitter = 20 * time.Millisecond
+ for i := 1; i < len(legs); i++ {
+ gap := time.Duration(legs[i].At - legs[i-1].At)
+ if gap < cfg.ReopenSpacing-dialJitter {
+ t.Fatalf("legs %d and %d opened %s apart, want at least ReopenSpacing %s", i-1, i, gap, cfg.ReopenSpacing)
+ }
+ if want := fmt.Sprint(i); http.Header(legs[i].Header).Get("Last-Event-ID") != want && i <= 4 {
+ t.Fatalf("leg %d sent Last-Event-ID %q, want %s", i, legs[i].Header["Last-Event-Id"], want)
+ }
+ }
+ if s := h.starts(); len(s) != 1 {
+ t.Fatalf("%d child starts, want 1: a reopen woke something", len(s))
+ }
+ if c.ended() {
+ t.Fatal("the browser's stream ended")
+ }
+}
+
+// Case 6: an edge restart. A stream held on an asleep host loses its edge;
+// the browser reconnects to a new edge over the same registry and
+// activator, is held there, and the child is never started.
+func TestHeldE2EEdgeRestart(t *testing.T) {
+ h := newHeldE2E(t, heldE2EOpts{idle: 500 * time.Millisecond})
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ b.waitPings(1, 5*time.Second)
+
+ e2, front2 := h.newEdge(nil)
+ h.front.CloseClientConnections() // the first edge goes away
+ waitE2E(t, 5*time.Second, "the first edge's stream to end", c.ended)
+ waitE2E(t, 5*time.Second, "the first edge's held set to empty", func() bool { return h.e.HeldStreamStats().Held == 0 })
+
+ b.url = front2.URL + heldPath
+ c = b.connect()
+ if c.resp.StatusCode != http.StatusOK || c.resp.Header.Get("X-Fake-App") != "" {
+ t.Fatalf("reconnect answer %d %v, want the new edge's own held 200", c.resp.StatusCode, c.resp.Header)
+ }
+ b.waitPings(3, 5*time.Second)
+ if st := e2.HeldStreamStats(); st.Held != 1 {
+ t.Fatalf("new edge's stats %+v, want one held stream", st)
+ }
+ if s := h.starts(); len(s) != 0 {
+ t.Fatalf("%d child starts, want none: a reconnect woke the host", len(s))
+ }
+ if !h.asleep() {
+ t.Fatal("the reconnect made an activator entry")
+ }
+}
+
+// Case 7 (Review Focus 4): generations on, an overlap swap with a stream
+// open. The switch cancels the retiring generation's leg in its critical
+// section, so the retiring child's drain is fast, and the stream reopens on
+// the successor and receives the next event from it.
+func TestHeldE2EOverlapSwap(t *testing.T) {
+ h := newHeldE2E(t, heldE2EOpts{idle: time.Minute, gens: true})
+ pid1 := h.wake()
+ b := newBrowser(t, h.front.URL, heldPath)
+ c := b.connect()
+ h.appendEvent("e1")
+ b.waitEvents(1, 5*time.Second)
+
+ v2 := stageVersion(t, h.exec, e2eHost, "v2", servingBody(t, filepath.Join(t.TempDir(), "argv0")))
+ digest, err := release.FileSHA256(v2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ res := h.a.Swap(ctx, Attempt{Host: e2eHost, Cause: CauseRelease, Build: "v2", StagedPath: v2, Digest: digest, Mode: ModeOverlap, SchedRev: 1},
+ func(string) uint64 { return 1 })
+ if res.Outcome != SwapDone || res.Mode != ModeOverlap {
+ t.Fatalf("Swap = %+v, want an overlap done", res)
+ }
+ rec := h.shutdownOf(pid1, 25*time.Second)
+ if rec.Ms >= 2000 || rec.Err != "" {
+ t.Fatalf("the retiring generation's drain took %d ms (%q) with a held stream open, want under 2000", rec.Ms, rec.Err)
+ }
+ starts := h.starts()
+ if len(starts) != 2 {
+ t.Fatalf("%d child starts, want 2 (the wake and the successor)", len(starts))
+ }
+ pid2 := starts[1]
+ h.appendEvent("e2")
+ wantEvents(t, b.waitEvents(2, 5*time.Second), 2)
+ legs := h.liveReqs(pid2)
+ if len(legs) != 1 || http.Header(legs[0].Header).Get("Last-Event-ID") != "1" {
+ t.Fatalf("legs on the successor %+v, want one with Last-Event-ID 1", legs)
+ }
+ if c.ended() {
+ t.Fatal("the browser's stream ended at the swap")
+ }
+}
+
+// Case 10: the stop race. A stream reopens its leg in a tight loop
+// (ReopenSpacing 1 ms; the app ends each leg at once) while the idle sweep
+// stops the instance, 50 times. After each stop the child's log shows no
+// /live request that started after its SIGTERM, and its drain stayed under
+// 2000 ms: every leg admitted before the stop was cancelled by it, and none
+// was admitted after.
+func TestHeldE2EStopAdmitRace(t *testing.T) {
+ cfg := e2eHeldConfig()
+ cfg.ReopenSpacing = time.Millisecond
+ cfg.ShortLeg = 0
+ h := newHeldE2E(t, heldE2EOpts{idle: 150 * time.Millisecond, cfg: cfg})
+ b := newBrowser(t, h.front.URL, "/live?end=1&carlos_hold=1")
+ c := b.connect()
+ raced := 0
+ for i := 0; i < 50; i++ {
+ pid := h.wake()
+ waitE2E(t, 10*time.Second, fmt.Sprintf("iteration %d's stop", i), h.asleep)
+ term, ok := h.find(pid, "sigterm")
+ if !ok {
+ t.Fatalf("iteration %d: child %d stopped with no SIGTERM logged", i, pid)
+ }
+ rec := h.shutdownOf(pid, 5*time.Second)
+ if rec.Ms >= 2000 || rec.Err != "" {
+ t.Fatalf("iteration %d: drain %d ms (%q), want under 2000", i, rec.Ms, rec.Err)
+ }
+ legs := h.liveReqs(pid)
+ for _, l := range legs {
+ if l.At > term.At {
+ t.Fatalf("iteration %d: a /live leg started %s after child %d's SIGTERM", i, time.Duration(l.At-term.At), pid)
+ }
+ }
+ if len(legs) > 0 {
+ raced++
+ }
+ if c.ended() {
+ t.Fatalf("iteration %d: the browser's stream ended", i)
+ }
+ }
+ if raced < 25 {
+ t.Fatalf("legs reached only %d of 50 processes: the reopen loop did not run against the stops", raced)
+ }
+}
+
+// Case 13: the session expired while asleep. The stream is held; on wake
+// its reopen gets the app's 401 (or 303) and the stream closes; the
+// browser's reconnect, now admissible, gets the 401 itself (or 204 for the
+// redirect) and stops.
+func TestHeldE2EExpiredSession(t *testing.T) {
+ for _, tc := range []struct {
+ name, target string
+ reconnect int
+ }{
+ {"expired", "/live?expire=1&carlos_hold=1", http.StatusUnauthorized},
+ {"redirect", "/live?redirect=1&carlos_hold=1", http.StatusNoContent},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := newHeldE2E(t, heldE2EOpts{idle: time.Minute})
+ b := newBrowser(t, h.front.URL, tc.target)
+ c := b.connect()
+ if c.resp.StatusCode != http.StatusOK || c.resp.Header.Get("X-Fake-App") != "" {
+ t.Fatalf("asleep answer %d, want the edge's held 200", c.resp.StatusCode)
+ }
+ b.waitPings(1, 5*time.Second)
+ pid := h.wake()
+ waitE2E(t, 5*time.Second, "the reopen's refusal to close the stream", c.ended)
+ if n := len(h.liveReqs(pid)); n != 1 {
+ t.Fatalf("%d /live legs, want the one reopen", n)
+ }
+ if st := h.e.HeldStreamStats(); st.Closes["refused"] != 1 {
+ t.Fatalf("held-stream stats %+v, want one refused close", st)
+ }
+ c = b.connect()
+ if c.resp.StatusCode != tc.reconnect {
+ t.Fatalf("reconnect answered %d %q, want %d", c.resp.StatusCode, c.body, tc.reconnect)
+ }
+ if loc := c.resp.Header.Get("Location"); loc != "" {
+ t.Fatalf("reconnect carried Location %q: a redirect reached the browser", loc)
+ }
+ if n := len(h.starts()); n != 1 {
+ t.Fatalf("%d child starts, want 1", n)
+ }
+ })
+ }
+}
+
+// A leg carries the edge's own forwarded chain and its edge proof, not the
+// client's forged ones, and never X-Carlos-Sidecar.
+func TestHeldE2ELegHeaders(t *testing.T) {
+ store := release.NewDirStore(t.TempDir())
+ if err := edge.MintMeshKey(context.Background(), store); err != nil {
+ t.Fatal(err)
+ }
+ current, next, err := edgeproof.LoadKeys(context.Background(), store)
+ if err != nil || len(current) == 0 {
+ t.Fatalf("mesh key: %v", err)
+ }
+ h := newHeldE2E(t, heldE2EOpts{idle: time.Minute, beforeReload: func(e *edge.Edge) {
+ e.EnableStatic(store, nil, "")
+ if e.ArmHomeMap() == nil {
+ t.Fatal("no home map armed")
+ }
+ }})
+ pid := h.wake()
+ b := newBrowser(t, h.front.URL, heldPath)
+ forged := edgeproof.Sign(current, e2eHost, "6.6.6.6", time.Now())
+ b.header.Set("X-Forwarded-For", "6.6.6.6")
+ b.header.Set(edgeproof.Header, forged)
+ b.header.Set("X-Carlos-Sidecar", "1")
+ c := b.connect()
+ if c.resp.Header.Get("X-Fake-App") != "sse" {
+ t.Fatalf("first answer %d %v, want the app's", c.resp.StatusCode, c.resp.Header)
+ }
+ legs := h.liveReqs(pid)
+ if len(legs) != 1 {
+ t.Fatalf("%d legs, want 1", len(legs))
+ }
+ hd := http.Header(legs[0].Header)
+ xff := strings.Join(hd.Values("X-Forwarded-For"), ", ")
+ if xff == "" || strings.Contains(xff, "6.6.6.6") {
+ t.Fatalf("leg X-Forwarded-For = %q, want the edge's own chain without the client's forged hop", xff)
+ }
+ proof := hd.Get(edgeproof.Header)
+ if proof == "" || proof == forged {
+ t.Fatalf("leg proof header %q, want the edge's own signature", proof)
+ }
+ if !edgeproof.Verify(current, next, e2eHost, xff, proof, time.Now()) {
+ t.Fatalf("leg proof %q does not verify against the mesh key for %q", proof, xff)
+ }
+ if v := hd.Values("X-Carlos-Sidecar"); len(v) != 0 {
+ t.Fatalf("leg carried X-Carlos-Sidecar %q", v)
+ }
+ if got := hd.Get("Accept-Encoding"); got != "identity" {
+ t.Fatalf("leg Accept-Encoding %q, want identity", got)
+ }
+ if q := legs[0].Query; q != "" {
+ t.Fatalf("leg query %q, want the marker stripped", q)
+ }
+}
+
+// A first leg's Set-Cookie reaches the browser scoped exactly as the edge
+// scopes a proxied response's (cookiescope.go): a Domain outside the host
+// and its account's namespace is dropped, the rest byte for byte.
+func TestHeldE2EFirstLegCookieScoped(t *testing.T) {
+ t.Setenv("PLATFORM_APPS_DOMAIN", "example.com")
+ h := newHeldE2E(t, heldE2EOpts{idle: time.Minute})
+ h.wake()
+ b := newBrowser(t, h.front.URL, "/live?cookie=1&carlos_hold=1")
+ c := b.connect()
+ if c.resp.Header.Get("X-Fake-App") != "sse" {
+ t.Fatalf("first answer %d %v, want the app's", c.resp.StatusCode, c.resp.Header)
+ }
+ got := c.resp.Header.Values("Set-Cookie")
+ if len(got) != 1 || got[0] != "s=1; Path=/" {
+ t.Fatalf("browser Set-Cookie %q, want [\"s=1; Path=/\"] (the child sent Domain=other.example.com)", got)
+ }
+}
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index c7dcb98e8..07000619e 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -4537,14 +4537,8 @@ func RunWithActivatorReady(args []string, act Activator, cache *Cache, ready fun
// mirror from, one synchronous refresh before anything listens so the
// first request does not meet an empty map, then the 30s loop. Stored
// before either listener binds, so ServeHTTP never sees a half-armed edge.
- if hm := e.newHomeMap(); hm != nil {
- ctx, cancel := context.WithTimeout(context.Background(), homeMapBootTimeout)
- if err := hm.Refresh(ctx); err != nil {
- log.Printf("edge: first home map refresh failed: %v — hosts homed on another box are unreachable from here until a later poll lands", err)
- }
- cancel()
- e.homes.Store(hm)
- go hm.run(make(chan struct{})) // process-lifetime; never stopped, like the cert mirror's
+ if run := e.ArmHomeMap(); run != nil {
+ go run(make(chan struct{})) // process-lifetime; never stopped, like the cert mirror's
}
// The edge-local door (door.go, #175 P7), armed right after the home map
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index c49b7d676..2a7fe1914 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -380,6 +380,27 @@ func (e *Edge) newHomeMap() *homeMap {
return m
}
+// ArmHomeMap builds the home map and the mesh keys from the deployment
+// store (EnableStatic), refreshes it once and installs it, so the first
+// request does not meet an empty map. It returns the map's 30s poll loop
+// for the caller to run, or nil when there is no store to mirror from.
+// Call it before serving. The edge's own startup calls it; production-wired
+// tests in other packages call it to sign the forwarded chain with a real
+// mesh key.
+func (e *Edge) ArmHomeMap() (run func(stop <-chan struct{})) {
+ hm := e.newHomeMap()
+ if hm == nil {
+ return nil
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), homeMapBootTimeout)
+ if err := hm.Refresh(ctx); err != nil {
+ log.Printf("edge: first home map refresh failed: %v — hosts homed on another box are unreachable from here until a later poll lands", err)
+ }
+ cancel()
+ e.homes.Store(hm)
+ return hm.run
+}
+
// Refresh rebuilds the host fold and re-reads the mesh keys. The two halves
// fail INDEPENDENTLY — a bucket that answered the edges list but not the key
// object should still land the fold — so both run and their errors join.