carlos / platform Public

host, edge: fleet boxes read seed snapshots and the seeds floor

Task 12 of the fleet seeded create plan (#1139, slice 2). A customer-fleet
box reads its file seed's snapshot from the deployment store through the
store door (fleetSeedObjects), and reports placed, failed and rolledback
to the console's seeds door (fleetSeedDoor), authenticated as the replica
doors are. wireSeedPlacement arms CustomerFleet, the door hooks and the
provision pass's fleet hooks; the rollback's replica delete refuses on a
fleet. A box on a fleet that cannot reach the door places no seed.

The store door grants a fleet box a read of control/seeds-protocol.json,
one exact key, so the agent and root can arm the seeds floor. Listing and
write stay closed; a test pins every control/ key the source names.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 2a1dc363202777f1c355863f3a39ed75a5b08744 parent 556a865
5 files changed, +784 −2
  • internal/edge/storedoor.go +11 −1
  • internal/edge/storedoor_test.go +178 −0
  • internal/host/seedfleetdoor.go +217 −0
  • internal/host/seedfleetdoor_test.go +357 −0
  • internal/host/seedwiring.go +21 −1

CI cancelled — superseded by a newer push — run details

diff --git a/internal/edge/storedoor.go b/internal/edge/storedoor.go
index 046704ec8..39cbd72e5 100644
--- a/internal/edge/storedoor.go
+++ b/internal/edge/storedoor.go
@@ -42,6 +42,7 @@ import (
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
)
const (
@@ -685,12 +686,21 @@ func canonicalPrefix(raw string) (string, bool) {
// the one 404 carrying storeAbsentHeader: a box that read a refusal as
// absence would drop the app's policy, so it must be able to tell the two
// apart, and it may already read the key, so the mark is no oracle.
+//
+// The seeds floor (seeds.FloorKey, fleet seeded create design §3.4) is
+// granted because a fleet box must arm it before it can place a seed file:
+// the agent syncs it to the box (syncLocalSeedsFloor), and root reads it
+// for its floor guard (rootseedsfloor.go). It is one deployment-wide control object, the
+// operator's protocol number and minimum release, with no account data in
+// it. The grant is that one exact key, never a prefix of control/: listing
+// is not granted (aclDir and aclListScope are unchanged), and write stays
+// console-only: aclWrite never answers true for it.
func aclRead(sqid, fleet, key string) bool {
if sqid == "" || fleet == "" {
return false
}
switch key {
- case "control/serial", "bootstrap/carlos", release.LayoutIntentKey(), plans.MarkerKey():
+ case "control/serial", "bootstrap/carlos", release.LayoutIntentKey(), plans.MarkerKey(), seeds.FloorKey:
return true
}
if systemReadKey(key) || promotionRecordRead(sqid, key) || appPolicyRead(sqid, key) {
diff --git a/internal/edge/storedoor_test.go b/internal/edge/storedoor_test.go
index 9190f209b..75fce3690 100644
--- a/internal/edge/storedoor_test.go
+++ b/internal/edge/storedoor_test.go
@@ -26,6 +26,7 @@ import (
"github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
"time"
)
@@ -1501,3 +1502,180 @@ func TestStoreDoorReturnsOwnNamespaceClaim(t *testing.T) {
t.Fatalf("bcd's fleet reading bdq's namespace claim = %d %q; want the same 404 an absent claim gets", got.Code, got.Body.String())
}
}
+
+// TestStoreDoorGrantsSeedsFloorReadOnly: a fleet box reads the seeds floor
+// (fleet seeded create design §3.4) so the agent and root can arm it. The
+// grant is one exact key, read only: never a prefix of control/, never a
+// listing, never a write.
+func TestStoreDoorGrantsSeedsFloorReadOnly(t *testing.T) {
+ if seeds.FloorKey != "control/seeds-protocol.json" {
+ t.Fatalf("seeds.FloorKey = %q: the grant below is for control/seeds-protocol.json", seeds.FloorKey)
+ }
+ for _, c := range []struct {
+ key string
+ op aclOp
+ want bool
+ }{
+ {seeds.FloorKey, opRead, true},
+ {seeds.FloorKey, opWrite, false},
+ {seeds.FloorKey, opDelete, false},
+ {"control/seeds-protocol.jsonx", opRead, false},
+ {"control/seeds-protocol.json/x", opRead, false},
+ {"control/seeds-protocol.jso", opRead, false},
+ {"control/seeds-protocol", opRead, false},
+ {"control/seeds-protocol.json.bak", opRead, false},
+ {"Control/seeds-protocol.json", opRead, false},
+ {"control/x/../seeds-protocol.json", opRead, false},
+ {"control/moves-protocol.json", opRead, false},
+ {"control/moves-protocol-auth.json", opRead, false},
+ {"control/", opRead, false},
+ {"control", opRead, false},
+ } {
+ if got := aclAllows(c.key, c.op); got != c.want {
+ t.Errorf("%s %q = %v, want %v", c.op, c.key, got, c.want)
+ }
+ }
+ if aclRead("", testFleet, seeds.FloorKey) || aclRead(testSqid, "", seeds.FloorKey) {
+ t.Error("the seeds floor was readable without both identities")
+ }
+ for _, prefix := range []string{"control", "control/", "control/seeds-protocol.json", "control/seeds"} {
+ if _, ok := aclListScope(testSqid, testFleet, prefix); ok {
+ t.Errorf("listing allowed for %q", prefix)
+ }
+ if aclDir(testSqid, testFleet, prefix) {
+ t.Errorf("directory visible: %q", prefix)
+ }
+ }
+
+ // On the wire: the GET serves the floor; a write and a delete leave it
+ // as it was, and a listing of control/ is refused.
+ d, store := newTestDoor(t)
+ const floor = `{"min":4,"min_release":"v1.2.3"}`
+ seedObject(t, store, seeds.FloorKey, floor)
+ if w := doorDo(d, "GET", "/store/o/"+seeds.FloorKey, "", nil); w.Code != http.StatusOK || w.Body.String() != floor {
+ t.Fatalf("GET the seeds floor = %d %q, want 200 and the floor", w.Code, w.Body.String())
+ }
+ if w := doorDo(d, "PUT", "/store/o/"+seeds.FloorKey, `{"min":0}`, map[string]string{"If-None-Match": "*"}); w.Code != http.StatusNotFound {
+ t.Errorf("PUT the seeds floor = %d, want 404", w.Code)
+ }
+ if w := doorDo(d, "DELETE", "/store/o/"+seeds.FloorKey, "", nil); w.Code != http.StatusNotFound {
+ t.Errorf("DELETE the seeds floor = %d, want 404", w.Code)
+ }
+ if body, _, err := store.Get(context.Background(), seeds.FloorKey); err != nil || string(body) != floor {
+ t.Fatalf("the floor after a refused write and delete = %q, %v", body, err)
+ }
+ for _, target := range []string{"/store/list?prefix=control/", "/store/dirs?prefix=control/", "/store/list?prefix=control/seeds-protocol.json"} {
+ if w := doorDo(d, "GET", target, "", nil); w.Code != http.StatusNotFound {
+ t.Errorf("GET %s = %d, want 404", target, w.Code)
+ }
+ }
+}
+
+// TestStoreDoorSeedsFloorGrantIsTheOnlyNewControlRead pins the exact
+// control/ keys a fleet box may read, against every control/ key the
+// platform's own source names. A grant stated as "everything else under
+// control/ stays closed" is an absence; this looks for the second door
+// (AGENTS.md, "a rule stated as an absence"). The seeds floor is the one
+// key the fleet seeded create added. Every other literal, used as a key or
+// as a prefix of one, must stay unreadable, apart from the shapes granted
+// before it (the system pointers and the box's own app policy).
+func TestStoreDoorSeedsFloorGrantIsTheOnlyNewControlRead(t *testing.T) {
+ exact := map[string]bool{
+ "control/serial": true,
+ release.LayoutIntentKey(): true,
+ plans.MarkerKey(): true,
+ seeds.FloorKey: true,
+ }
+ keys := controlLiteralKeys(t)
+ if len(keys) < 20 || !slices.Contains(keys, seeds.FloorKey) {
+ t.Fatalf("found %d control/ keys in the source, without the seeds floor: the walk is broken", len(keys))
+ }
+ for _, key := range keys {
+ want := exact[key] || systemReadKey(key) || appPolicyRead(testSqid, key)
+ if got := aclAllows(key, opRead); got != want {
+ t.Errorf("read %q = %v, want %v", key, got, want)
+ }
+ if aclAllows(key, opWrite) {
+ t.Errorf("write allowed for %q", key)
+ }
+ }
+ // Another account's estate stays closed, the fleet seed snapshot shape
+ // among it; the box's own fleet snapshot is its own apps/<sqid>/.
+ const host, id = "shop-1.example.com", "sd_abcdefghijklmnopqrstuvwxyz"
+ for _, c := range []struct {
+ key string
+ want bool
+ }{
+ {"apps/" + testSqid + "/shop/seeds/" + host + "/" + id + "/snapshot.db", true},
+ {"apps/zz99/shop/seeds/" + host + "/" + id + "/snapshot.db", false},
+ {"apps/" + testSqid + "x/shop/seeds/" + host + "/" + id + "/snapshot.db", false},
+ {"apps/zz99/shop/instances/" + host + ".json", false},
+ {"seeds/" + host + "/" + id + "/snapshot.db", false},
+ } {
+ if got := aclAllows(c.key, opRead); got != c.want {
+ t.Errorf("read %q = %v, want %v", c.key, got, c.want)
+ }
+ }
+ if _, ok := aclListScope(testSqid, testFleet, "apps/zz99/"); ok {
+ t.Error("another account's apps/ listable")
+ }
+}
+
+// controlLiteralKeys is every string literal under control/ in the module's
+// non-test Go source, as a key, and as a prefix with a file under it.
+// Format verbs and placeholders become one plain segment.
+func controlLiteralKeys(t *testing.T) []string {
+ t.Helper()
+ root := filepath.Join("..", "..")
+ var keys []string
+ seen := map[string]bool{}
+ add := func(k string) {
+ if !seen[k] {
+ seen[k] = true
+ keys = append(keys, k)
+ }
+ }
+ plain := strings.NewReplacer("%s", "x", "%d", "1", "<", "", ">", "", " ", "")
+ err := filepath.WalkDir(root, func(p string, e os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if e.IsDir() {
+ if n := e.Name(); p != root && (strings.HasPrefix(n, ".") || n == "vendor" || n == "node_modules" || n == "testdata") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(p, ".go") || strings.HasSuffix(p, "_test.go") {
+ return nil
+ }
+ f, err := parser.ParseFile(token.NewFileSet(), p, nil, parser.SkipObjectResolution)
+ if err != nil {
+ return err
+ }
+ ast.Inspect(f, func(n ast.Node) bool {
+ lit, ok := n.(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ return true
+ }
+ s := strings.Trim(lit.Value, "`\"")
+ if !strings.HasPrefix(s, "control/") {
+ return true
+ }
+ s = plain.Replace(s)
+ if strings.HasSuffix(s, "/") {
+ add(s + "x.json")
+ add(s + "x/y.json")
+ } else {
+ add(s)
+ add(s + "/x.json")
+ }
+ return true
+ })
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return keys
+}
diff --git a/internal/host/seedfleetdoor.go b/internal/host/seedfleetdoor.go
new file mode 100644
index 000000000..cc37afb40
--- /dev/null
+++ b/internal/host/seedfleetdoor.go
@@ -0,0 +1,217 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// File seeds on a customer-fleet box (fleet seeded create design §3.5): the
+// box reads its snapshot from the deployment store through the store door,
+// and reports every transition to the console's seeds door, because the
+// store door refuses a fleet box's record writes (ruling 4).
+
+// fleetSeedObjects reads fleet seed snapshots from the deployment store:
+// apps/<sqid>/<app>/seeds/<host>/<id>/snapshot.db, the key the console
+// wrote (design §3.3). On a bucketless fleet box the store is the store
+// door's client (fleetapi), which streams.
+type fleetSeedObjects struct{ s release.Store }
+
+// Open streams the fleet snapshot of seed id. The key is built from values
+// that pass the account, app and seed checks, never from anything else: a
+// bad part is an error here, not a read of seeds.FleetSnapshotKey's
+// "invalid" key. A store that cannot stream is refused rather than read
+// whole: a seed can be gigabytes.
+func (o fleetSeedObjects) Open(ctx context.Context, acct, app, host, id string) (io.ReadCloser, error) {
+ if !release.ValidAccount(acct) || !release.ValidApp(app) {
+ return nil, fmt.Errorf("seed %q of %s: account %q or app %q is not one", id, host, acct, app)
+ }
+ if err := seeds.Check(host, id); err != nil {
+ return nil, fmt.Errorf("seed %q of %s: %w", id, host, err)
+ }
+ op, ok := o.s.(release.Opener)
+ if !ok {
+ return nil, errors.New("the deployment store cannot stream")
+ }
+ rc, _, err := op.Open(ctx, seeds.FleetSnapshotKey(acct, app, host, id))
+ return rc, err
+}
+
+// fleetSeedDoorTimeout bounds one report, as the replica doors' client.
+const fleetSeedDoorTimeout = 30 * time.Second
+
+// fleetSeedDoor is the box's client of the console's seeds door:
+// POST /api/fleet/seeds/<acct>/<app>/<host>/<op>, authenticated as the
+// replica doors' client is (replicacoordinator.go): the tunnel bearer token
+// and Carlos-Tunnel-Name <fleet>/<box>.
+type fleetSeedDoor struct {
+ base, fleet, box, token string
+ client *http.Client
+}
+
+// fleetSeedDoorBody is the door's body (plan Task 15). code and held are
+// sent only when set: the door refuses held with any code but
+// copy-in-storage.
+type fleetSeedDoorBody struct {
+ ID string `json:"id"`
+ Code string `json:"code,omitempty"`
+ Held string `json:"held,omitempty"`
+}
+
+// errSeedDoorNotConsole is an answer the console did not give: no
+// X-Carlos-Version header, so the hub or something in front of it.
+var errSeedDoorNotConsole = errors.New("fleet seeds door: the answer did not come from the console")
+
+// report sends one transition. 200 is done. 409 is the console's record
+// saying otherwise: it is logged and answers nil, because asking again
+// cannot change it, and the next pass decides from the record. Anything
+// else, including an answer that is not the console's, is an error for the
+// caller to retry on its next pass.
+//
+// It sends only the door's vocabulary (decisions D4, D12): an op, a code
+// only with failed, held only with copy-in-storage. A call outside it is a
+// bug here and is refused before anything is sent.
+func (d fleetSeedDoor) report(ctx context.Context, acct, app, host, id, op, code, held string) error {
+ if err := fleetSeedDoorRefusal(acct, app, host, id, op, code, held); err != nil {
+ return err
+ }
+ raw, err := json.Marshal(fleetSeedDoorBody{ID: id, Code: code, Held: held})
+ if err != nil {
+ return err
+ }
+ endpoint := strings.TrimRight(d.base, "/") + "/api/fleet/seeds/" + url.PathEscape(acct) + "/" + url.PathEscape(app) + "/" + url.PathEscape(host) + "/" + op
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Authorization", "Bearer "+d.token)
+ req.Header.Set("Carlos-Tunnel-Name", d.fleet+"/"+d.box)
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := d.client.Do(req)
+ if err != nil {
+ return fmt.Errorf("fleet seeds door: %s %s: %w", host, op, err)
+ }
+ defer resp.Body.Close()
+ _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 8192))
+ if resp.Header.Get("X-Carlos-Version") == "" {
+ return fmt.Errorf("%w (%s %s, HTTP %d)", errSeedDoorNotConsole, host, op, resp.StatusCode)
+ }
+ switch resp.StatusCode {
+ case http.StatusOK:
+ return nil
+ case http.StatusConflict:
+ log.Printf("fleet seeds door: %s: seed %s %s: the console's record says otherwise (HTTP 409); the next pass decides from the record", host, id, op)
+ return nil
+ }
+ return fmt.Errorf("fleet seeds door: %s: seed %s %s: HTTP %d", host, id, op, resp.StatusCode)
+}
+
+// fleetSeedDoorRefusal is report's vocabulary check: nil only for a call
+// the door's grammar allows.
+func fleetSeedDoorRefusal(acct, app, host, id, op, code, held string) error {
+ if !release.ValidAccount(acct) || !release.ValidApp(app) {
+ return fmt.Errorf("fleet seeds door: account %q or app %q is not one", acct, app)
+ }
+ if err := seeds.Check(host, id); err != nil {
+ return fmt.Errorf("fleet seeds door: seed %q of %q: %w", id, host, err)
+ }
+ switch op {
+ case provision.FleetSeedPlaced, provision.FleetSeedRolledBack:
+ if code != "" || held != "" {
+ return fmt.Errorf("fleet seeds door: %s carries no code", op)
+ }
+ return nil
+ case provision.FleetSeedFailed:
+ default:
+ return fmt.Errorf("fleet seeds door: %q is not an op", op)
+ }
+ switch code {
+ case provision.SeedCodeMismatch, provision.SeedCodeNotADatabase, provision.SeedCodeCopyExists:
+ if held != "" {
+ return fmt.Errorf("fleet seeds door: %s carries no held", code)
+ }
+ return nil
+ case provision.SeedCodeCopyInStorage:
+ switch held {
+ case provision.SeedHeldReplica, provision.SeedHeldStaging, provision.SeedHeldBoth:
+ return nil
+ }
+ return fmt.Errorf("fleet seeds door: copy-in-storage held %q is not a place", held)
+ }
+ return fmt.Errorf("fleet seeds door: %q is not a reason code", code)
+}
+
+// fleetSeedWiring is what wireSeedPlacement needs to arm a customer-fleet
+// box: its door client. ok is false off a fleet. err is set for a box on a
+// fleet that cannot report: an identity that does not resolve, or no
+// tunnel to the console. Such a box places no seed at all, since nothing
+// it placed could be recorded.
+func fleetSeedWiring(getenv func(string) string) (door fleetSeedDoor, ok bool, err error) {
+ identity, err := resolveFleetIdentity(getenv)
+ if errors.Is(err, errNotFleetBox) {
+ return fleetSeedDoor{}, false, nil
+ }
+ if err != nil {
+ return fleetSeedDoor{}, true, err
+ }
+ base := strings.TrimSpace(getenv("CARLOS_TUNNEL_URL"))
+ token := strings.TrimSpace(getenv("CARLOS_TUNNEL_TOKEN"))
+ if base == "" || token == "" {
+ return fleetSeedDoor{}, true, errors.New("both CARLOS_TUNNEL_URL and CARLOS_TUNNEL_TOKEN must be set to reach the console's seeds door")
+ }
+ return fleetSeedDoor{base: base, fleet: identity.Fleet, box: identity.Label, token: token,
+ client: &http.Client{Timeout: fleetSeedDoorTimeout}}, true, nil
+}
+
+// armFleetSeeds points a customer-fleet box's seed hooks at the door
+// (design §3.5): the fleet reader, placed and failed reported to the
+// console, and, when the rollback's box hooks are armed, the provision
+// pass's fleet hooks. The rollback keeps requiring DeleteReplica, so it
+// stays set, to a delete that refuses: a fleet box proves a seed's copies
+// gone by listing and never deletes them (§3.6).
+//
+// The staging rule reads the bucket through eb.Mirror, which the agent
+// arms before this. A fleet box without one fails every wake of an
+// unplaced seed file and reports nothing, which is safe; it is logged here
+// so the cause is not a mystery.
+func armFleetSeeds(eb *activator.ExecBackend, h *provision.SeedHooks, door fleetSeedDoor, deploy, data release.Store, prefix string) {
+ eb.Seeds = fleetSeedObjects{deploy}
+ eb.OnSeedPlaced = func(ctx context.Context, acct, app, host, id string) error {
+ return door.report(ctx, acct, app, host, id, provision.FleetSeedPlaced, "", "")
+ }
+ eb.OnSeedFailed = func(ctx context.Context, acct, app, host, id, code string) error {
+ return door.report(ctx, acct, app, host, id, provision.FleetSeedFailed, code, "")
+ }
+ if eb.Mirror == nil {
+ log.Printf("agent: seed files: this fleet box has no reader for its bucket's staging prefix; no seed file can be placed here")
+ }
+ if h.DeleteReplica == nil {
+ return
+ }
+ h.DeleteReplica = func(context.Context, string) error {
+ return errors.New("a fleet box never deletes a replica for a seed")
+ }
+ h.Fleet = &provision.FleetSeedHooks{Report: door.report, ListPrefix: data.List, ReplicaPrefix: prefix}
+}
+
+// seedGetenv is box.Getenv, or the process's environment.
+func seedGetenv(box seedBox) func(string) string {
+ if box.Getenv != nil {
+ return box.Getenv
+ }
+ return os.Getenv
+}
diff --git a/internal/host/seedfleetdoor_test.go b/internal/host/seedfleetdoor_test.go
new file mode 100644
index 000000000..b6268aa07
--- /dev/null
+++ b/internal/host/seedfleetdoor_test.go
@@ -0,0 +1,357 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/seeds"
+)
+
+// doorCall is one request the fake console door saw.
+type doorCall struct {
+ method, path, auth, tunnel, ctype string
+ body map[string]any
+}
+
+// fakeSeedDoor is a console seeds door answering every call with code, and
+// with the console's version header unless bare.
+type fakeSeedDoor struct {
+ mu sync.Mutex
+ calls []doorCall
+ code int
+ bare bool
+}
+
+func (f *fakeSeedDoor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ raw, _ := io.ReadAll(r.Body)
+ var body map[string]any
+ _ = json.Unmarshal(raw, &body)
+ f.mu.Lock()
+ f.calls = append(f.calls, doorCall{r.Method, r.URL.EscapedPath(), r.Header.Get("Authorization"),
+ r.Header.Get("Carlos-Tunnel-Name"), r.Header.Get("Content-Type"), body})
+ code, bare := f.code, f.bare
+ f.mu.Unlock()
+ if !bare {
+ w.Header().Set("X-Carlos-Version", "v9.9.9")
+ }
+ w.WriteHeader(code)
+}
+
+func (f *fakeSeedDoor) seen() []doorCall {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]doorCall(nil), f.calls...)
+}
+
+func newFakeSeedDoor(t *testing.T, code int) (*fakeSeedDoor, fleetSeedDoor) {
+ t.Helper()
+ f := &fakeSeedDoor{code: code}
+ srv := httptest.NewServer(f)
+ t.Cleanup(srv.Close)
+ return f, fleetSeedDoor{base: srv.URL + "/", fleet: "pi", box: "box-a", token: "box-a-token", client: srv.Client()}
+}
+
+func testSeedID(t *testing.T) string {
+ t.Helper()
+ id, err := seeds.NewID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return id
+}
+
+// The fleet reader streams the fleet snapshot key in the deployment store,
+// the one the console wrote (design §3.3), and nothing else: not the region
+// key for the same seed, and no key at all for an input that is not one.
+func TestFleetSeedObjectsOpensFleetKey(t *testing.T) {
+ ctx := context.Background()
+ deploy := release.NewDirStore(t.TempDir())
+ sqid, host, id := domains.Sqid(2), "shop-1.example.com", testSeedID(t)
+ if _, err := deploy.Put(ctx, seeds.FleetSnapshotKey(sqid, "shop", host, id), []byte("fleet db"), ""); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := deploy.Put(ctx, seeds.SnapshotKey(host, id), []byte("region db"), ""); err != nil {
+ t.Fatal(err)
+ }
+ o := fleetSeedObjects{deploy}
+ rc, err := o.Open(ctx, sqid, "shop", host, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, _ := io.ReadAll(rc)
+ rc.Close()
+ if string(got) != "fleet db" {
+ t.Fatalf("read %q, want the fleet snapshot", got)
+ }
+ for name, args := range map[string][4]string{
+ "another app": {sqid, "blog", host, id},
+ "a bad account": {"../x", "shop", host, id},
+ "a bad app": {sqid, "", host, id},
+ "a bad host": {sqid, "shop", "../x", id},
+ "a bad seed id": {sqid, "shop", host, "nope"},
+ "another account": {domains.Sqid(3), "shop", host, id},
+ } {
+ if rc, err := o.Open(ctx, args[0], args[1], args[2], args[3]); err == nil {
+ rc.Close()
+ t.Errorf("%s: opened a snapshot", name)
+ }
+ }
+ if _, err := (fleetSeedObjects{noOpenerStore{deploy}}).Open(ctx, sqid, "shop", host, id); err == nil {
+ t.Error("a store that cannot stream was read")
+ }
+}
+
+// noOpenerStore hides DirStore's Open.
+type noOpenerStore struct{ release.Store }
+
+// The door client speaks the replica doors' authentication and the seeds
+// door's body (plan Task 15): the bearer token, the channel name, and only
+// the fields the op carries.
+func TestFleetSeedDoorHeadersAndBody(t *testing.T) {
+ ctx := context.Background()
+ f, d := newFakeSeedDoor(t, http.StatusOK)
+ sqid, host, id := domains.Sqid(2), "shop-1.example.com", testSeedID(t)
+ for _, c := range []struct{ op, code, held string }{
+ {provision.FleetSeedPlaced, "", ""},
+ {provision.FleetSeedFailed, provision.SeedCodeNotADatabase, ""},
+ {provision.FleetSeedFailed, provision.SeedCodeCopyInStorage, provision.SeedHeldBoth},
+ {provision.FleetSeedRolledBack, "", ""},
+ } {
+ if err := d.report(ctx, sqid, "shop", host, id, c.op, c.code, c.held); err != nil {
+ t.Fatalf("%s: %v", c.op, err)
+ }
+ }
+ calls := f.seen()
+ if len(calls) != 4 {
+ t.Fatalf("%d calls, want 4", len(calls))
+ }
+ wantBodies := []map[string]any{
+ {"id": id},
+ {"id": id, "code": "not-a-database"},
+ {"id": id, "code": "copy-in-storage", "held": "both"},
+ {"id": id},
+ }
+ for i, op := range []string{"placed", "failed", "failed", "rolledback"} {
+ c := calls[i]
+ if c.method != http.MethodPost || c.path != "/api/fleet/seeds/"+sqid+"/shop/"+host+"/"+op {
+ t.Errorf("call %d = %s %s", i, c.method, c.path)
+ }
+ if c.auth != "Bearer box-a-token" || c.tunnel != "pi/box-a" || c.ctype != "application/json" {
+ t.Errorf("call %d headers: auth %q tunnel %q type %q", i, c.auth, c.tunnel, c.ctype)
+ }
+ if len(c.body) != len(wantBodies[i]) {
+ t.Errorf("call %d body = %v, want %v", i, c.body, wantBodies[i])
+ }
+ for k, v := range wantBodies[i] {
+ if c.body[k] != v {
+ t.Errorf("call %d body = %v, want %v", i, c.body, wantBodies[i])
+ }
+ }
+ }
+
+ // Nothing a caller supplies outside the door's vocabulary is sent.
+ for name, a := range map[string][7]string{
+ "an unknown op": {sqid, "shop", host, id, "deleted", "", ""},
+ "a code on placed": {sqid, "shop", host, id, "placed", "mismatch", ""},
+ "failed with no code": {sqid, "shop", host, id, "failed", "", ""},
+ "an unknown code": {sqid, "shop", host, id, "failed", "Disk full", ""},
+ "held without copy-in-storage": {sqid, "shop", host, id, "failed", "mismatch", "replica"},
+ "copy-in-storage without held": {sqid, "shop", host, id, "failed", "copy-in-storage", ""},
+ "an unknown held": {sqid, "shop", host, id, "failed", "copy-in-storage", "elsewhere"},
+ "a bad host": {sqid, "shop", "../x", id, "placed", "", ""},
+ "a bad seed id": {sqid, "shop", host, "nope", "placed", "", ""},
+ "a bad account": {"a/b", "shop", host, id, "placed", "", ""},
+ "a bad app": {sqid, "Shop/..", host, id, "placed", "", ""},
+ } {
+ if err := d.report(ctx, a[0], a[1], a[2], a[3], a[4], a[5], a[6]); err == nil {
+ t.Errorf("%s: sent", name)
+ }
+ }
+ if n := len(f.seen()); n != 4 {
+ t.Errorf("%d calls after the refusals, want 4", n)
+ }
+}
+
+// 409 is the console's record saying otherwise: logged, not an error, and
+// not asked again by the client; the next pass decides from the record.
+// Every other answer that is not the console's 200 is an error the caller
+// retries.
+func TestFleetSeedDoor409IsNotRetried(t *testing.T) {
+ ctx := context.Background()
+ sqid, host, id := domains.Sqid(2), "shop-1.example.com", testSeedID(t)
+ f, d := newFakeSeedDoor(t, http.StatusConflict)
+ logs := captureLog(t)
+ if err := d.report(ctx, sqid, "shop", host, id, provision.FleetSeedRolledBack, "", ""); err != nil {
+ t.Fatalf("409 = %v, want nil", err)
+ }
+ if n := len(f.seen()); n != 1 {
+ t.Fatalf("%d calls on a 409, want 1", n)
+ }
+ if !strings.Contains(logs(), "409") {
+ t.Errorf("the 409 was not logged: %q", logs())
+ }
+
+ for _, code := range []int{http.StatusNotFound, http.StatusBadRequest, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusTooManyRequests} {
+ f, d := newFakeSeedDoor(t, code)
+ if err := d.report(ctx, sqid, "shop", host, id, provision.FleetSeedPlaced, "", ""); err == nil {
+ t.Errorf("HTTP %d = nil, want an error to retry", code)
+ }
+ if n := len(f.seen()); n != 1 {
+ t.Errorf("HTTP %d: %d calls, want 1", code, n)
+ }
+ }
+ // A 200 or a 409 that is not the console's (no version header: the hub,
+ // or something in front of it) is not an answer.
+ for _, code := range []int{http.StatusOK, http.StatusConflict} {
+ f, d := newFakeSeedDoor(t, code)
+ f.bare = true
+ if err := d.report(ctx, sqid, "shop", host, id, provision.FleetSeedPlaced, "", ""); err == nil {
+ t.Errorf("a bare %d = nil, want an error", code)
+ }
+ }
+ unreachable := fleetSeedDoor{base: "http://127.0.0.1:1", fleet: "pi", box: "box-a", token: "t", client: &http.Client{}}
+ if err := unreachable.report(ctx, sqid, "shop", host, id, provision.FleetSeedPlaced, "", ""); err == nil {
+ t.Error("an unreachable console = nil, want an error")
+ }
+}
+
+// fleetEnv is a fleet box's environment: CARLOS_FLEET, its box label and
+// the tunnel the door is reached through.
+func fleetEnv(url string) func(string) string {
+ env := map[string]string{"CARLOS_FLEET": "pi", "CARLOS_FLEET_BOX": "box-a", "CARLOS_TUNNEL_URL": url, "CARLOS_TUNNEL_TOKEN": "box-a-token"}
+ return func(k string) string { return env[k] }
+}
+
+// On a fleet box the seed hooks are the door's (design §3.5): the fleet
+// reader, placed and failed to the console, the provision pass's fleet
+// hooks, and a replica delete that refuses. Off a fleet they are today's.
+func TestWireSeedPlacementFleetUsesDoor(t *testing.T) {
+ ctx := context.Background()
+ data, deploy := release.NewDirStore(t.TempDir()), release.NewDirStore(t.TempDir())
+ reg := restartTestRegistry(t)
+ sqid, host, id := domains.Sqid(2), "shop-1.example.com", testSeedID(t)
+ box := func(getenv func(string) string) seedBox {
+ return seedBox{Fence: &fakeFence{gens: map[string]uint64{}}, Prefix: "instances", Swept: func() bool { return true },
+ NextFenceGen: fenceGenerations(reg), Getenv: getenv}
+ }
+
+ t.Run("fleet", func(t *testing.T) {
+ resetArmedSeedHooks(t)
+ f := &fakeSeedDoor{code: http.StatusOK}
+ srv := httptest.NewServer(f)
+ defer srv.Close()
+ eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, NestedOK: func() error { return nil }}
+ wireSeedPlacement(eb, false, storeOpener(data), storeOpener(deploy), box(fleetEnv(srv.URL)))
+ if !eb.CustomerFleet {
+ t.Fatal("CustomerFleet not set on a fleet box")
+ }
+ if o, ok := eb.Seeds.(fleetSeedObjects); !ok || o.s != release.Store(deploy) {
+ t.Fatalf("Seeds = %#v, want the fleet reader on the deployment store", eb.Seeds)
+ }
+ if eb.OnSeedPlaced == nil || eb.OnSeedFailed == nil {
+ t.Fatal("the door's placed and failed hooks are not wired")
+ }
+ if err := eb.OnSeedPlaced(ctx, sqid, "shop", host, id); err != nil {
+ t.Fatal(err)
+ }
+ if err := eb.OnSeedFailed(ctx, sqid, "shop", host, id, provision.SeedCodeMismatch); err != nil {
+ t.Fatal(err)
+ }
+ h := armedSeedHooks.Load()
+ if h == nil || h.Fleet == nil || h.Fleet.Report == nil || h.Fleet.ListPrefix == nil || h.Fleet.ReplicaPrefix != "instances" {
+ t.Fatalf("fleet hooks = %+v", h)
+ }
+ if err := h.Fleet.Report(ctx, sqid, "shop", host, id, provision.FleetSeedFailed, provision.SeedCodeCopyInStorage, provision.SeedHeldReplica); err != nil {
+ t.Fatal(err)
+ }
+ calls := f.seen()
+ wantOps := []string{"placed", "failed", "failed"}
+ if len(calls) != len(wantOps) {
+ t.Fatalf("%d door calls, want %d", len(calls), len(wantOps))
+ }
+ for i, op := range wantOps {
+ if !strings.HasSuffix(calls[i].path, "/"+host+"/"+op) || calls[i].tunnel != "pi/box-a" {
+ t.Errorf("call %d = %s from %s, want %s", i, calls[i].path, calls[i].tunnel, op)
+ }
+ }
+ if calls[1].body["code"] != "mismatch" || calls[2].body["held"] != "replica" {
+ t.Errorf("failed bodies = %v, %v", calls[1].body, calls[2].body)
+ }
+
+ // ListPrefix is the fleet's own bucket, listed whole.
+ replica := activator.HibernatePrefix("instances", host) + "/generations/g/x.ltx"
+ if _, err := data.Put(ctx, replica, []byte("x"), ""); err != nil {
+ t.Fatal(err)
+ }
+ if keys, err := h.Fleet.ListPrefix(ctx, provision.FleetSeedReplicaPrefix("instances", host)); err != nil || len(keys) != 1 || keys[0] != replica {
+ t.Fatalf("ListPrefix = %v, %v", keys, err)
+ }
+ // The rollback's replica delete stays wired, so the rollback's hooks
+ // are whole, and refuses: a fleet box never deletes a replica for a
+ // seed (design §3.6).
+ if h.DeleteReplica == nil {
+ t.Fatal("DeleteReplica is nil: no rollback is armed")
+ }
+ if err := h.DeleteReplica(ctx, host); err == nil {
+ t.Error("DeleteReplica succeeded on a fleet box")
+ }
+ if _, _, err := data.Get(ctx, replica); err != nil {
+ t.Errorf("the refused DeleteReplica removed the replica: %v", err)
+ }
+ if h.FenceForRollback == nil || h.LiftFence == nil || h.RemoveLocal == nil || h.NextFenceGen == nil {
+ t.Error("the rollback's box hooks are not wired on a fleet box")
+ }
+ })
+
+ t.Run("not a fleet", func(t *testing.T) {
+ resetArmedSeedHooks(t)
+ eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, NestedOK: func() error { return nil }}
+ wireSeedPlacement(eb, false, storeOpener(data), storeOpener(deploy), box(func(string) string { return "" }))
+ if eb.CustomerFleet || eb.OnSeedFailed != nil {
+ t.Fatalf("CustomerFleet %v, OnSeedFailed set %v off a fleet", eb.CustomerFleet, eb.OnSeedFailed != nil)
+ }
+ if _, ok := eb.Seeds.(storeSeedObjects); !ok || eb.OnSeedPlaced == nil {
+ t.Fatalf("Seeds = %#v, want the region reader", eb.Seeds)
+ }
+ h := armedSeedHooks.Load()
+ if h == nil || h.Fleet != nil || h.DeleteReplica == nil {
+ t.Fatalf("hooks = %+v, want today's", h)
+ }
+ })
+
+ // A box that says it is on a fleet but cannot say which box it is, or
+ // cannot reach the door, places no seed: there is nobody to report to.
+ for name, getenv := range map[string]func(string) string{
+ "no box label": func(k string) string {
+ if k == "CARLOS_FLEET" {
+ return "pi"
+ }
+ return ""
+ },
+ "no tunnel": func(k string) string {
+ if k == "CARLOS_TUNNEL_URL" {
+ return ""
+ }
+ return fleetEnv("http://127.0.0.1:1")(k)
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ resetArmedSeedHooks(t)
+ eb := &activator.ExecBackend{ServedPools: testSharedPoolEvidence, NestedOK: func() error { return nil }}
+ wireSeedPlacement(eb, false, storeOpener(data), storeOpener(deploy), box(getenv))
+ if eb.Seeds != nil || eb.OnSeedPlaced != nil || eb.OnSeedFailed != nil || armedSeedHooks.Load() != nil {
+ t.Fatal("seed placement armed on a fleet box with no door")
+ }
+ })
+ }
+}
diff --git a/internal/host/seedwiring.go b/internal/host/seedwiring.go
index 98450ab79..f18819cf5 100644
--- a/internal/host/seedwiring.go
+++ b/internal/host/seedwiring.go
@@ -19,7 +19,9 @@ import (
"github.com/carlosframework/platform/internal/seeds"
)
-// storeSeedObjects reads seed snapshots from this box's data bucket.
+// storeSeedObjects reads seed snapshots from this box's data bucket. A
+// customer-fleet box reads them from the deployment store instead
+// (fleetSeedObjects).
type storeSeedObjects struct{ s release.Store }
// Open streams seeds/<host>/<id>/snapshot.db. A store that cannot stream is
@@ -127,6 +129,9 @@ type seedBox struct {
// Judge is the box's lifetime judge, for the placed callback
// (seedPlacedHook). Nil on a claims-on box.
Judge *provision.LifetimeJudge
+ // Getenv is where the box's fleet identity and tunnel are read from
+ // (fleetSeedWiring). Nil: the process's environment.
+ Getenv func(string) string
}
// wireSeedPlacement arms seeded instances on this box (seeded-instances
@@ -148,8 +153,20 @@ type seedBox struct {
// box.NextFenceGen must never repeat one across a restart
// (fenceGenerations). The hooks set no clock: the swap and the rollback
// read the pass's own (ReconcileConfig.Now).
+//
+// A customer-fleet box (CARLOS_FLEET resolves) reads its snapshots and
+// reports its seeds' progress through the console instead (fleet seeded
+// create design §3.5, armFleetSeeds). CustomerFleet is set, like the claim
+// flag, before anything that can fail. A box on a fleet that cannot reach
+// the console's seeds door places no seed.
func wireSeedPlacement(eb *activator.ExecBackend, claimArmed bool, openData, openDeploy func() (release.Store, error), box seedBox) {
eb.ClaimArmed = claimArmed
+ door, onFleet, err := fleetSeedWiring(seedGetenv(box))
+ eb.CustomerFleet = onFleet && err == nil
+ if err != nil {
+ log.Printf("agent: seed files: %v (no seed can be placed on this fleet box)", err)
+ return
+ }
data, err := openData()
if err != nil {
log.Printf("agent: seed reader: %v (no seed can be placed on this box)", err)
@@ -182,6 +199,9 @@ func wireSeedPlacement(eb *activator.ExecBackend, claimArmed bool, openData, ope
h.NextFenceGen = box.NextFenceGen
}
}
+ if onFleet {
+ armFleetSeeds(eb, h, door, deploy, data, box.Prefix)
+ }
armSeedHooks(h)
}