ha: retain verified identities and complete departure observations
Persist independently bound immutable identities and bounded discovery cursors. Capture both record families before policy filtering and preserve source refresh provenance. Export exact edges revisions after every poll, including skips and failures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+642
−23
internal/edge/edge.go+2 −1internal/edge/hadepartures.go+38 −0internal/edge/hadepartures_test.go+54 −0internal/edge/homemap.go+18 −4internal/host/hadeparture_identity.go+201 −0internal/host/hadeparture_identity_test.go+99 −0internal/provision/departure_inventory.go+115 −0internal/provision/departure_inventory_test.go+62 −0internal/provision/reconcile.go+18 −7internal/provision/recordview.go+2 −0internal/provision/recordview_store.go+17 −7internal/provision/sidecar_reconcile.go+16 −4
diff --git a/internal/edge/edge.go b/internal/edge/edge.go| index 41757f75f..c7127d904 100644 |
| --- a/internal/edge/edge.go |
| +++ b/internal/edge/edge.go |
| @@ -329,7 +329,8 @@ type Edge struct { |
| // changeWatch resolves the process's change-index watch (#336), handed |
| // down through WithChangeWatch. The cert mirror and the home map call it |
| // on every poll. nil, or a nil watch, keeps both on today's full reads. |
| - changeWatch func() *release.ChangeWatch |
| + departureTick func(context.Context, DepartureView) |
| + changeWatch func() *release.ChangeWatch |
| // homes, when non-nil, is the mirror of control/edges/ plus the mesh keys |
| // (homemap.go): who homes a host this box does not serve, and what proves |
| // an inbound hop. Atomic because it is armed in RunWithActivatorReady after |
diff --git a/internal/edge/hadepartures.go b/internal/edge/hadepartures.go| new file mode 100644 |
| index 000000000..df0420809 |
| --- /dev/null |
| +++ b/internal/edge/hadepartures.go |
| @@ -0,0 +1,38 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "slices" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| +) |
| + |
| +type DepartureView = hadeparture.DepartureView |
| + |
| +func WithDepartureTick(tick func(context.Context, DepartureView)) RunOption { |
| + return func(e *Edge) { e.departureTick = tick } |
| +} |
| +func (m *homeMap) departureView() DepartureView { |
| + s := m.snapshot() |
| + v := DepartureView{Complete: s.read && s.departureComplete} |
| + keys := make([]string, 0, len(s.files)) |
| + for key := range s.files { |
| + keys = append(keys, key) |
| + } |
| + slices.Sort(keys) |
| + for _, key := range keys { |
| + f := s.files[key] |
| + var gen string |
| + _ = json.Unmarshal(f.Generation, &gen) |
| + at, _ := time.Parse(time.RFC3339Nano, gen) |
| + o := hadeparture.BoxObservation{Box: hadeparture.Box{Ref: f.Box, Scope: hadeparture.Scope{CloudRegion: f.Region, Placement: f.Placement, DataBucket: f.DataBucket, SecretsKeyFP: f.SecretsKeyFP}}, Known: true, PlacementNull: f.placementNull, EdgesKey: key, EdgesETag: f.etag, Generation: gen, PublishedAt: at} |
| + if f.Box == m.self { |
| + v.Self = o |
| + } else { |
| + v.Peers = append(v.Peers, o) |
| + } |
| + } |
| + return v |
| +} |
diff --git a/internal/edge/hadepartures_test.go b/internal/edge/hadepartures_test.go| new file mode 100644 |
| index 000000000..1b068b0fb |
| --- /dev/null |
| +++ b/internal/edge/hadepartures_test.go |
| @@ -0,0 +1,54 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestDepartureAgeOnSkippedFold(t *testing.T) { |
| + s := release.NewDirStore(t.TempDir()) |
| + now := time.Now().UTC().Truncate(time.Second) |
| + raw := []byte(`{"v":1,"box":"peer","region":"eu-west-1","placement":"","data_bucket":"data","secrets_key_fp":"fp","generation":"` + now.Format(time.RFC3339) + `","hosts":{}}`) |
| + etag, err := s.Put(context.Background(), "control/edges/peer.json", raw, "") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + m := newHomeMap(s, "self") |
| + calls := 0 |
| + m.departureTick = func(ctx context.Context, v DepartureView) { |
| + calls++ |
| + if len(v.Peers) != 1 || v.Peers[0].EdgesETag != etag || !v.Peers[0].PublishedAt.Equal(now) { |
| + t.Fatalf("observation %+v", v) |
| + } |
| + } |
| + _ = m.poll(context.Background()) |
| + // The callback runs on the real poll even when its hosts refresh is skipped. |
| + m.watch = func() *release.ChangeWatch { return release.NewChangeWatch(s) } |
| + _ = m.poll(context.Background()) |
| + _ = m.poll(context.Background()) |
| + if calls != 3 { |
| + t.Fatalf("callbacks %d", calls) |
| + } |
| + _ = s.Put // keep fixture writes separate from observations |
| +} |
| +func TestDepartureHomeScopeAndPools(t *testing.T) { |
| + for _, placement := range []string{"", `,"placement":""`, `,"placement":null`} { |
| + raw := []byte(`{"v":1,"box":"hapair-a1","region":"eu-west-1","data_bucket":"data","secrets_key_fp":"fp","generation":"2026-11-03T10:00:00Z","hosts":{}` + placement + `}`) |
| + f, err := parseEdgesFile("control/edges/hapair-a1.json", raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.etag = "exact" |
| + m := newHomeMap(nil, "hapair-a1") |
| + m.snap = &homeSnapshot{files: map[string]edgesFileView{"control/edges/hapair-a1.json": f}, read: true} |
| + v := m.departureView() |
| + if v.Self.PlacementNull != (placement == `,"placement":null`) || v.Self.Box.Scope.Placement != "" { |
| + b, _ := json.Marshal(v) |
| + t.Fatalf("scope %s", b) |
| + } |
| + } |
| +} |
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go| index 900e23345..ac0170d8c 100644 |
| --- a/internal/edge/homemap.go |
| +++ b/internal/edge/homemap.go |
| @@ -133,6 +133,7 @@ var ( |
| // version. Additive growth on the writer's side lands here as fields this |
| // decoder ignores, which is the point. |
| type edgesFileView struct { |
| + etag string |
| V int `json:"v"` |
| Box string `json:"box"` |
| EIP string `json:"eip"` |
| @@ -268,6 +269,7 @@ type homeEntry struct { |
| // homeSnapshot is one poll's result, swapped in whole and immutable once |
| // published, so a reader holds no lock past the pointer read. |
| type homeSnapshot struct { |
| + departureComplete bool |
| // files is the parsed per-box file, keyed by its BUCKET key. This is the |
| // carry-forward unit: an object that could not be read (or could not be |
| // parsed) this poll keeps its previous parse, per box, so one bad file |
| @@ -283,7 +285,8 @@ type homeSnapshot struct { |
| var emptyHomeSnapshot = &homeSnapshot{files: map[string]edgesFileView{}, hosts: map[string]homeEntry{}} |
| type homeMap struct { |
| - s release.Store |
| + departureTick func(context.Context, DepartureView) |
| + s release.Store |
| // self is THIS box's label — the same derivation the box's own edges file |
| // is published under (internal/host's metricsBoxLabel), handed down at |
| // edge construction through WithBoxLabel. "" means this process does not |
| @@ -382,6 +385,7 @@ func (e *Edge) newHomeMap() *homeMap { |
| m.privateDial = regionHAFromEnv(os.Getenv) |
| m.health = e.lbHealth |
| m.watch = e.changeWatch |
| + m.departureTick = e.departureTick |
| return m |
| } |
| @@ -430,7 +434,16 @@ func (m *homeMap) Refresh(ctx context.Context) error { |
| // objects (control/edge-mesh-key and .next) bump no scope, so a rotation |
| // must not wait on control/edges (codex 8). Poll's moved list is advisory |
| // (the watch is shared), so the decision compares generations instead. |
| -func (m *homeMap) poll(ctx context.Context) error { |
| +func (m *homeMap) poll(ctx context.Context) (pollErr error) { |
| + defer func() { |
| + if m.departureTick != nil { |
| + v := m.departureView() |
| + if pollErr != nil { |
| + v.Complete = false |
| + } |
| + m.departureTick(ctx, v) |
| + } |
| + }() |
| w := m.changeWatch() |
| if w == nil { |
| return m.Refresh(ctx) |
| @@ -521,7 +534,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error { |
| continue |
| } |
| tried++ |
| - body, _, err := m.s.Get(ctx, key) |
| + body, etag, err := m.s.Get(ctx, key) |
| if errors.Is(err, os.ErrNotExist) { |
| // Raced a delete between the list and the get — the box was |
| // retired mid-poll. Not a fault; it is simply gone. |
| @@ -537,6 +550,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error { |
| } else if f, perr := parseEdgesFile(key, body); perr != nil { |
| err = perr |
| } else { |
| + f.etag = etag |
| next[key] = f |
| continue |
| } |
| @@ -564,7 +578,7 @@ func (m *homeMap) refreshHosts(ctx context.Context) error { |
| // deterministic; say so once a refresh. |
| log.Printf("edge: home map: %d host(s) published by two boxes at the same installation stamp, e.g. %s", len(tied), tied[0]) |
| } |
| - snap := &homeSnapshot{files: next, hosts: hosts, read: true} |
| + snap := &homeSnapshot{files: next, hosts: hosts, read: true, departureComplete: failed == 0} |
| m.mu.Lock() |
| m.snap = snap |
| wake := m.hostsWake |
diff --git a/internal/host/hadeparture_identity.go b/internal/host/hadeparture_identity.go| new file mode 100644 |
| index 000000000..c459a0681 |
| --- /dev/null |
| +++ b/internal/host/hadeparture_identity.go |
| @@ -0,0 +1,201 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/termfence" |
| +) |
| + |
| +var errDepartureIdentity = errors.New("ha_departure_identity_unbound") |
| + |
| +type departureIdentities struct { |
| + Registry *registry.Registry |
| + Store release.Store |
| + Verifier boxid.Verifier |
| + Fixed map[string]string |
| + Region string |
| + Now func() time.Time |
| +} |
| + |
| +func (r *departureIdentities) now() time.Time { |
| + if r.Now != nil { |
| + return r.Now() |
| + } |
| + return time.Now() |
| +} |
| +func (r *departureIdentities) verify(ctx context.Context, ref string, raw []byte) (registry.HABoxIdentity, error) { |
| + if len(raw) > 64*1024 { |
| + return registry.HABoxIdentity{}, errDepartureIdentity |
| + } |
| + var rec boxid.Record |
| + if json.Unmarshal(raw, &rec) != nil { |
| + return registry.HABoxIdentity{}, errDepartureIdentity |
| + } |
| + doc, err := base64.StdEncoding.DecodeString(rec.IdentityDocument) |
| + if err != nil { |
| + return registry.HABoxIdentity{}, errDepartureIdentity |
| + } |
| + var cloud struct { |
| + Region string `json:"region"` |
| + } |
| + if json.Unmarshal(doc, &cloud) != nil { |
| + return registry.HABoxIdentity{}, errDepartureIdentity |
| + } |
| + // The region selects a certificate. Enroll verifies the signed document |
| + // before any field from it can be used as evidence. |
| + ev, err := r.Verifier.Enroll(raw, boxid.Expect{Box: ref, AWSRegion: cloud.Region}) |
| + if err != nil { |
| + return registry.HABoxIdentity{}, err |
| + } |
| + old, known, err := r.Registry.HAIdentity(ctx, ref, "") |
| + if err != nil { |
| + return old, err |
| + } |
| + expected := r.Fixed[ref] |
| + if known { |
| + expected = old.IID |
| + if old.Digest != ev.RecordSHA256 { |
| + return old, errDepartureIdentity |
| + } |
| + } |
| + if expected == "" && ref == groupReferenceOf(ev.Cloud.Account, ev.Cloud.InstanceID) { |
| + expected = ev.Cloud.InstanceID |
| + } |
| + if expected == "" || expected != ev.Cloud.InstanceID { |
| + return old, errDepartureIdentity |
| + } |
| + b := registry.HABoxIdentity{Ref: ref, IID: ev.Cloud.InstanceID, Account: ev.Cloud.Account, Region: ev.Cloud.Region, Digest: ev.RecordSHA256, Raw: raw} |
| + if known { |
| + b.Observation = old.Observation |
| + } |
| + if err = r.Registry.SaveHAIdentity(ctx, b); err != nil { |
| + return b, err |
| + } |
| + return b, nil |
| +} |
| +func (r *departureIdentities) Resolve(ctx context.Context, ref, iid string) (hadeparture.BoxObservation, bool, error) { |
| + b, ok, err := r.Registry.HAIdentity(ctx, ref, iid) |
| + if err != nil || !ok { |
| + return hadeparture.BoxObservation{}, false, err |
| + } |
| + ev, err := r.Verifier.Enroll(b.Raw, boxid.Expect{Box: b.Ref, AWSRegion: b.Region, TofuInstanceID: b.IID}) |
| + if err != nil || ev.RecordSHA256 != b.Digest { |
| + return hadeparture.BoxObservation{}, false, errDepartureIdentity |
| + } |
| + o := b.Observation |
| + o.Box.Ref = b.Ref |
| + o.Box.InstanceID = b.IID |
| + o.Box.Account = b.Account |
| + o.Box.RecordSHA256 = b.Digest |
| + if o.Box.Scope.CloudRegion != "" && o.Box.Scope.CloudRegion != b.Region { |
| + return hadeparture.BoxObservation{}, false, errDepartureIdentity |
| + } |
| + return o, true, nil |
| +} |
| +func (r *departureIdentities) Observe(ctx context.Context, o hadeparture.BoxObservation) (hadeparture.BoxObservation, error) { |
| + if !o.Known || o.PlacementNull || o.Box.Scope.CloudRegion == "" || o.Box.Scope.DataBucket == "" || o.Box.Scope.SecretsKeyFP == "" || !boxid.ValidBox(o.Box.Ref) || o.EdgesKey != "control/edges/"+o.Box.Ref+".json" || o.EdgesETag == "" { |
| + return o, errDepartureIdentity |
| + } |
| + b, ok, err := r.Registry.HAIdentity(ctx, o.Box.Ref, "") |
| + if err != nil { |
| + return o, err |
| + } |
| + if !ok { |
| + raw, e := boxid.Load(ctx, r.Store, o.Box.Ref) |
| + if e != nil { |
| + return o, e |
| + } |
| + b, err = r.verify(ctx, o.Box.Ref, raw) |
| + if err != nil { |
| + return o, err |
| + } |
| + } |
| + ev, err := r.Verifier.Enroll(b.Raw, boxid.Expect{Box: b.Ref, AWSRegion: o.Box.Scope.CloudRegion, TofuInstanceID: b.IID}) |
| + if err != nil || ev.RecordSHA256 != b.Digest { |
| + return o, errDepartureIdentity |
| + } |
| + o.Box.InstanceID = b.IID |
| + o.Box.Account = b.Account |
| + o.Box.RecordSHA256 = b.Digest |
| + b.Observation = o |
| + return o, r.Registry.SaveHAIdentity(ctx, b) |
| +} |
| +func (r *departureIdentities) Proof(ctx context.Context, ref, iid string) (termfence.ProofIdentity, error) { |
| + o, ok, err := r.Resolve(ctx, ref, iid) |
| + if err != nil || !ok || !o.Known || o.PlacementNull || o.Box.Scope.CloudRegion != r.Region { |
| + return termfence.ProofIdentity{}, errDepartureIdentity |
| + } |
| + b, ok, err := r.Registry.HAIdentity(ctx, ref, iid) |
| + if err != nil || !ok { |
| + return termfence.ProofIdentity{}, errDepartureIdentity |
| + } |
| + return termfence.VerifyProofIdentity(r.Verifier, b.Raw, boxid.Expect{Box: ref, AWSRegion: r.Region, TofuInstanceID: iid}, o.Box.Scope.DataBucket) |
| +} |
| +func (r *departureIdentities) Walk(ctx context.Context) (bool, time.Time, error) { |
| + w, err := r.Registry.LoadHAIdentityWalk(ctx) |
| + if err != nil { |
| + return false, time.Time{}, err |
| + } |
| + if w.StartedAt.IsZero() { |
| + w.StartedAt = r.now() |
| + } |
| + l, ok := r.Store.(release.PageLister) |
| + if !ok { |
| + return false, w.StartedAt, errDepartureIdentity |
| + } |
| + keys, err := l.ListPage(ctx, boxid.Prefix, w.Cursor, 32) |
| + if err != nil { |
| + return false, w.StartedAt, err |
| + } |
| + if len(keys) > 32 { |
| + return false, w.StartedAt, errDepartureIdentity |
| + } |
| + for _, key := range keys { |
| + if key <= w.Cursor || !strings.HasPrefix(key, boxid.Prefix) || !strings.HasSuffix(key, ".json") { |
| + w.Failed = true |
| + continue |
| + } |
| + ref := strings.TrimSuffix(strings.TrimPrefix(key, boxid.Prefix), ".json") |
| + if !boxid.ValidBox(ref) { |
| + w.Failed = true |
| + continue |
| + } |
| + _, known, e := r.Resolve(ctx, ref, "") |
| + if e != nil { |
| + w.Failed = true |
| + continue |
| + } |
| + if known { |
| + continue |
| + } |
| + raw, e := boxid.Load(ctx, r.Store, ref) |
| + if e == nil { |
| + _, e = r.verify(ctx, ref, raw) |
| + } |
| + if e != nil { |
| + w.Failed = true |
| + } |
| + } |
| + if len(keys) > 0 { |
| + w.Cursor = keys[len(keys)-1] |
| + } |
| + finished := len(keys) < 32 |
| + complete := finished && !w.Failed |
| + at := w.StartedAt |
| + if finished { |
| + w = registry.HAIdentityWalk{} |
| + } |
| + if err = r.Registry.SaveHAIdentityWalk(ctx, w); err != nil { |
| + return false, at, err |
| + } |
| + return complete, at, nil |
| +} |
diff --git a/internal/host/hadeparture_identity_test.go b/internal/host/hadeparture_identity_test.go| new file mode 100644 |
| index 000000000..a5d8f4ba5 |
| --- /dev/null |
| +++ b/internal/host/hadeparture_identity_test.go |
| @@ -0,0 +1,99 @@ |
| +package host |
| + |
| +import ( |
| + "context" |
| + "fmt" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/boxid" |
| + "github.com/carlosframework/platform/internal/boxid/boxidtest" |
| + "github.com/carlosframework/platform/internal/hadeparture" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func TestDepartureIdentityWithoutEdges(t *testing.T) { |
| + ctx := context.Background() |
| + s := boxidtest.NewSigner(t) |
| + store := release.NewDirStore(t.TempDir()) |
| + p := filepath.Join(t.TempDir(), "registry.db") |
| + reg, err := registry.Open(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer func() { reg.Close() }() |
| + repo := &departureIdentities{Registry: reg, Store: store, Verifier: boxid.Verifier{Account: "111122223333", Certs: s.Certs()}, Fixed: map[string]string{"fixed": "i-1123456789abcdef0"}, Region: "eu-west-1"} |
| + _, raw := s.Record(t, "fixed", "111122223333", "eu-west-1", "i-1123456789abcdef0") |
| + if _, err = store.Put(ctx, boxid.Key("fixed"), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + obs := hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "fixed", Scope: hadeparture.Scope{CloudRegion: "eu-west-1", DataBucket: "data", SecretsKeyFP: "fp"}}, EdgesKey: "control/edges/fixed.json", EdgesETag: "exact"} |
| + got, err := repo.Observe(ctx, obs) |
| + if err != nil || got.Box.InstanceID != "i-1123456789abcdef0" { |
| + t.Fatalf("observe %+v %v", got, err) |
| + } |
| + reg.Close() |
| + reg, err = registry.Open(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + repo.Registry = reg |
| + got, ok, err := repo.Resolve(ctx, "fixed", "i-1123456789abcdef0") |
| + if err != nil || !ok || got.EdgesETag != "exact" || !got.Known { |
| + t.Fatalf("retained %+v %v %v", got, ok, err) |
| + } |
| + _, poison := s.Record(t, "poison", "111122223333", "eu-west-1", "i-1123456789abcdef0") |
| + if _, err = repo.verify(ctx, "poison", poison); err == nil { |
| + t.Fatal("unsigned reference accepted") |
| + } |
| + repo.Fixed["poison"] = "i-1123456789abcdef0" |
| + if _, err = repo.verify(ctx, "poison", poison); err == nil { |
| + t.Fatal("duplicate iid accepted") |
| + } |
| + obs.PlacementNull = true |
| + if _, err = repo.Observe(ctx, obs); err == nil { |
| + t.Fatal("null placement accepted") |
| + } |
| +} |
| +func TestDepartureUnknownIdentityBudget(t *testing.T) { |
| + ctx := context.Background() |
| + s := boxidtest.NewSigner(t) |
| + store := release.NewDirStore(t.TempDir()) |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer reg.Close() |
| + repo := &departureIdentities{Registry: reg, Store: store, Verifier: boxid.Verifier{Account: "111122223333", Certs: s.Certs()}, Region: "eu-west-1", Now: func() time.Time { return time.Unix(100, 0) }} |
| + for n := 0; n < 35; n++ { |
| + iid := fmt.Sprintf("i-%017x", n+1) |
| + ref := groupReferenceOf("111122223333", iid) |
| + _, raw := s.Record(t, ref, "111122223333", "eu-west-1", iid) |
| + if _, err = store.Put(ctx, boxid.Key(ref), raw, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + done, _, err := repo.Walk(ctx) |
| + if err != nil || done { |
| + t.Fatalf("first page %v %v", done, err) |
| + } |
| + walk, err := reg.LoadHAIdentityWalk(ctx) |
| + if err != nil || walk.Cursor == "" { |
| + t.Fatalf("durable cursor %+v %v", walk, err) |
| + } |
| + done, at, err := repo.Walk(ctx) |
| + if err != nil || !done || !at.Equal(time.Unix(100, 0)) { |
| + t.Fatalf("complete %v %v %v", done, at, err) |
| + } |
| + if _, err = store.Put(ctx, boxid.Key("bad"), []byte(`{}`), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + for n := 0; n < 2; n++ { |
| + done, _, _ = repo.Walk(ctx) |
| + if done { |
| + t.Fatal("malformed record certified unrelated") |
| + } |
| + } |
| +} |
diff --git a/internal/provision/departure_inventory.go b/internal/provision/departure_inventory.go| new file mode 100644 |
| index 000000000..f73864e1c |
| --- /dev/null |
| +++ b/internal/provision/departure_inventory.go |
| @@ -0,0 +1,115 @@ |
| +package provision |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/json" |
| + "fmt" |
| + "slices" |
| + "sync" |
| + "time" |
| +) |
| + |
| +type DepartureHost struct { |
| + Account, App, Host, Kind, Placement, Pool, Lifetime, Revision string |
| + HA bool |
| +} |
| +type InventorySnapshot struct { |
| + Generation string |
| + Records []DepartureHost |
| + Complete bool |
| + WalkStartedAt, SourceReadStartedAt time.Time |
| +} |
| + |
| +func (s InventorySnapshot) FreshAfter(at time.Time) bool { |
| + return s.Complete && s.WalkStartedAt.After(at) && s.SourceReadStartedAt.After(at) |
| +} |
| + |
| +type DepartureInventory struct { |
| + mu sync.Mutex |
| + snapshot InventorySnapshot |
| + serial uint64 |
| +} |
| +type DeparturePass struct { |
| + inventory *DepartureInventory |
| + serial uint64 |
| + families map[string][]DepartureHost |
| + complete map[string]bool |
| + sourceComplete bool |
| +} |
| + |
| +func (i *DepartureInventory) Snapshot() InventorySnapshot { |
| + i.mu.Lock() |
| + defer i.mu.Unlock() |
| + s := i.snapshot |
| + s.Records = slices.Clone(s.Records) |
| + return s |
| +} |
| +func (i *DepartureInventory) Begin(generation string, walk, source time.Time, complete bool) *DeparturePass { |
| + i.mu.Lock() |
| + defer i.mu.Unlock() |
| + i.serial++ |
| + i.snapshot.Generation = generation |
| + i.snapshot.WalkStartedAt = walk |
| + i.snapshot.SourceReadStartedAt = source |
| + i.snapshot.Complete = false |
| + return &DeparturePass{inventory: i, serial: i.serial, families: map[string][]DepartureHost{}, complete: map[string]bool{}, sourceComplete: complete} |
| +} |
| +func (p *DeparturePass) family(kind string, hosts []DepartureHost, complete bool) { |
| + if p == nil { |
| + return |
| + } |
| + i := p.inventory |
| + i.mu.Lock() |
| + defer i.mu.Unlock() |
| + if p.serial != i.serial { |
| + return |
| + } |
| + p.families[kind] = slices.Clone(hosts) |
| + p.complete[kind] = complete |
| + if len(p.families) != 2 { |
| + return |
| + } |
| + all := append(slices.Clone(p.families["instance"]), p.families["sidecar"]...) |
| + good := p.sourceComplete && p.complete["instance"] && p.complete["sidecar"] |
| + seen := map[string]bool{} |
| + for _, h := range all { |
| + if seen[h.Host] { |
| + good = false |
| + } |
| + seen[h.Host] = true |
| + } |
| + if !good { |
| + for _, h := range i.snapshot.Records { |
| + if !seen[h.Host] { |
| + all = append(all, h) |
| + } |
| + } |
| + } |
| + slices.SortFunc(all, func(a, b DepartureHost) int { |
| + if a.Host < b.Host { |
| + return -1 |
| + } |
| + if a.Host > b.Host { |
| + return 1 |
| + } |
| + return 0 |
| + }) |
| + i.snapshot.Records = all |
| + i.snapshot.Complete = good |
| +} |
| +func departureInstance(rec Record, raw []byte) (DepartureHost, bool) { |
| + life, err := LifetimeEntryOf(rec) |
| + return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: rec.Kind, Placement: rec.Region, Pool: rec.Pool, Lifetime: life.ID, Revision: fmt.Sprintf("%x", sha256.Sum256(raw)), HA: rec.HA}, err == nil && !departureNullRegion(raw) |
| +} |
| +func departureSidecar(rec SidecarRecord, raw []byte) (DepartureHost, bool) { |
| + life, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt) |
| + return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: SidecarKind, Placement: rec.Region, Pool: rec.Pool, Lifetime: life, Revision: fmt.Sprintf("%x", sha256.Sum256(raw))}, err == nil && !departureNullRegion(raw) |
| +} |
| +func departureNullRegion(raw []byte) bool { |
| + var o map[string]json.RawMessage |
| + if json.Unmarshal(raw, &o) != nil { |
| + return true |
| + } |
| + return bytes.Equal(bytes.TrimSpace(o["region"]), []byte("null")) |
| +} |
diff --git a/internal/provision/departure_inventory_test.go b/internal/provision/departure_inventory_test.go| new file mode 100644 |
| index 000000000..518f6f4d1 |
| --- /dev/null |
| +++ b/internal/provision/departure_inventory_test.go |
| @@ -0,0 +1,62 @@ |
| +package provision |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestDepartureInventoryComplete(t *testing.T) { |
| + f := sidecarSetup(t) |
| + defer f.reg.Close() |
| + f.putRecord(t, SidecarRecord{Name: "worker", App: "shop", Channel: "edge", Pool: "cohort1"}) |
| + inv := &DepartureInventory{} |
| + at := time.Now() |
| + pass := inv.Begin("one", at, at, true) |
| + cfg := ReconcileConfig{DataDir: f.dir, Departures: pass} |
| + if err := Reconcile(ctx, f.store, f.reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + if inv.Snapshot().Complete { |
| + t.Fatal("one family certified coverage") |
| + } |
| + if err := ReconcileSidecars(ctx, f.store, f.reg, cfg); err != nil { |
| + t.Fatal(err) |
| + } |
| + snap := inv.Snapshot() |
| + if !snap.Complete || len(snap.Records) != 1 || snap.Records[0].Pool != "cohort1" || snap.Records[0].Kind != "sidecar" { |
| + t.Fatalf("hidden pre-filter sidecar %+v", snap) |
| + } |
| + if rt, _ := f.reg.Get(f.host("worker", "shop")); rt != nil { |
| + t.Fatal("inventory widened policy") |
| + } |
| + f.store.failReadsFor("apps/") |
| + pass = inv.Begin("two", at.Add(time.Second), at.Add(time.Second), true) |
| + cfg.Departures = pass |
| + _ = Reconcile(ctx, f.store, f.reg, cfg) |
| + _ = ReconcileSidecars(ctx, f.store, f.reg, cfg) |
| + snap = inv.Snapshot() |
| + if snap.Complete || len(snap.Records) != 1 { |
| + t.Fatalf("failed scan discarded evidence or certified coverage %+v", snap) |
| + } |
| +} |
| +func TestDepartureInventoryAfterEvidence(t *testing.T) { |
| + inv := &DepartureInventory{} |
| + evidence := time.Now() |
| + p := inv.Begin("old-source", evidence.Add(time.Second), evidence.Add(-time.Second), true) |
| + p.family("instance", nil, true) |
| + p.family("sidecar", nil, true) |
| + if inv.Snapshot().FreshAfter(evidence) { |
| + t.Fatal("old source re-stamped") |
| + } |
| + p = inv.Begin("new", evidence.Add(time.Second), evidence.Add(time.Second), true) |
| + p.family("instance", nil, true) |
| + p.family("sidecar", nil, true) |
| + if !inv.Snapshot().FreshAfter(evidence) { |
| + t.Fatal("fresh full pass refused") |
| + } |
| + copy := inv.Snapshot() |
| + copy.Records = append(copy.Records, DepartureHost{Host: "mutation"}) |
| + if len(inv.Snapshot().Records) != 0 { |
| + t.Fatal("mutable snapshot") |
| + } |
| +} |
diff --git a/internal/provision/reconcile.go b/internal/provision/reconcile.go| index 24f761168..0dee0faf1 100644 |
| --- a/internal/provision/reconcile.go |
| +++ b/internal/provision/reconcile.go |
| @@ -34,6 +34,7 @@ import ( |
| // injection-seam shape domains.Config uses (tests supply fixtures, the host |
| // agent supplies production values). |
| type ReconcileConfig struct { |
| + Departures *DeparturePass |
| ClaimEnabled bool |
| ClaimInstall func(context.Context, ClaimRecord, func(registry.ClaimOwnership) error) error |
| ClaimRetire func(context.Context, registry.Route) error |
| @@ -1091,12 +1092,14 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| // failedAccts the accounts whose manifest would not read; partial a |
| // listing that came back incomplete, which could hide any app's record. |
| type recordScan struct { |
| - recs map[string]Record |
| - protect map[string]bool |
| - readFailed bool |
| - unread map[string]bool |
| - failedAccts map[string]bool |
| - partial bool |
| + departureRecords []DepartureHost |
| + departureInvalid bool |
| + recs map[string]Record |
| + protect map[string]bool |
| + readFailed bool |
| + unread map[string]bool |
| + failedAccts map[string]bool |
| + partial bool |
| // known is the scan's account set and stale the hosts whose listed |
| // record the judge found its slot no longer vouches for; the |
| // removal phase reads both for the scan it judges. |
| @@ -1114,6 +1117,8 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| unreadHosts map[string]bool |
| } |
| scan := func(st release.Store) (recordScan, error) { |
| + var departureRecords []DepartureHost |
| + departureInvalid := false |
| known, failedAccts, err := knownAccountsNaming(ctx, st) |
| if err != nil { |
| return recordScan{}, err |
| @@ -1301,6 +1306,11 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| if hosts != nil { |
| hosts[rec.Host]++ |
| } |
| + if cfg.Departures != nil { |
| + h, ok := departureInstance(rec, bodies[key].body) |
| + departureRecords = append(departureRecords, h) |
| + departureInvalid = departureInvalid || !ok |
| + } |
| if !cfg.inScope(rec.Region, rec.Pool, everywhereClass(rec)) { |
| // On the hub, a fleet-placed record skipped only at the |
| // fleet boundary is the forward phase's (spec §4.3 step |
| @@ -1340,10 +1350,11 @@ func Reconcile(ctx context.Context, s release.Store, reg *registry.Registry, cfg |
| recs[rec.Host] = rec |
| } |
| } |
| - return recordScan{recs: recs, protect: protect, readFailed: readFailed, known: known, stale: stale, |
| + return recordScan{departureRecords: departureRecords, departureInvalid: departureInvalid, recs: recs, protect: protect, readFailed: readFailed, known: known, stale: stale, |
| unread: unread, failedAccts: failedAccts, partial: partial, fleet: fleet, hosts: hosts, unreadHosts: unreadHosts}, nil |
| } |
| sc, err := scan(s) |
| + cfg.Departures.family("instance", sc.departureRecords, err == nil && !sc.departureInvalid && !sc.readFailed && !sc.partial && len(sc.unread) == 0 && len(sc.protect) == 0) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/provision/recordview.go b/internal/provision/recordview.go| index 63519be87..3f092b466 100644 |
| --- a/internal/provision/recordview.go |
| +++ b/internal/provision/recordview.go |
| @@ -220,6 +220,7 @@ func (v *RecordView) poll(ctx context.Context) error { |
| // poll just failed: the watch is unknown, so a second poll could only spend |
| // another bound before the same walk. |
| func (v *RecordView) rebuildLocked(ctx context.Context, poll bool) error { |
| + sourceStarted := time.Now() |
| if poll { |
| if err := v.poll(ctx); err != nil { |
| log.Printf("provision: record view: change index unusable (%v): the walk records no generations", err) |
| @@ -257,6 +258,7 @@ func (v *RecordView) rebuildLocked(ctx context.Context, poll bool) error { |
| v.rebuildDue = len(sn.dirErrs) > 0 |
| // A walk whose ctx ended mid-way has its dead reads cached as failures: |
| // published incomplete, retried by the next Refresh. |
| + sn.SourceReadStartedAt = sourceStarted |
| v.publish(sn) |
| return ctx.Err() |
| } |
diff --git a/internal/provision/recordview_store.go b/internal/provision/recordview_store.go| index 599d96c5e..23056c588 100644 |
| --- a/internal/provision/recordview_store.go |
| +++ b/internal/provision/recordview_store.go |
| @@ -10,6 +10,7 @@ import ( |
| "slices" |
| "strings" |
| "sync" |
| + "time" |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -22,8 +23,9 @@ import ( |
| // account manifest that will not read cleanly, an app listing that failed). |
| // It is never read and changed at once: a Refresh builds a new one. |
| type ViewSnapshot struct { |
| - Epoch uint64 |
| - Complete bool |
| + SourceReadStartedAt time.Time |
| + Epoch uint64 |
| + Complete bool |
| accounts map[string]*acctEntry // sqid -> accounts/<sqid>/ |
| strays []string // keys under accounts/ outside every account scope, from the last walk |
| @@ -124,11 +126,12 @@ func (sn *ViewSnapshot) app(a, b string) *appEntry { |
| // clone copies the maps a Refresh changes; entries are shared, never mutated. |
| func (sn *ViewSnapshot) clone() *ViewSnapshot { |
| out := &ViewSnapshot{ |
| - accounts: maps.Clone(sn.accounts), |
| - strays: sn.strays, |
| - apps: make(map[string]map[string]*appEntry, len(sn.apps)), |
| - dirErrs: sn.dirErrs, |
| - walkErr: sn.walkErr, |
| + SourceReadStartedAt: sn.SourceReadStartedAt, |
| + accounts: maps.Clone(sn.accounts), |
| + strays: sn.strays, |
| + apps: make(map[string]map[string]*appEntry, len(sn.apps)), |
| + dirErrs: sn.dirErrs, |
| + walkErr: sn.walkErr, |
| } |
| for a, inner := range sn.apps { |
| out.apps[a] = maps.Clone(inner) |
| @@ -539,3 +542,10 @@ func (uncachedStore) Put(context.Context, string, []byte, string) (string, error |
| func (uncachedStore) List(context.Context, string) ([]string, error) { return nil, errUncached } |
| func (uncachedStore) ListDirs(context.Context, string) ([]string, error) { return nil, errUncached } |
| func (uncachedStore) Delete(context.Context, string) error { return errUncached } |
| + |
| +func DepartureSource(s release.Store) (time.Time, bool) { |
| + if ss, ok := s.(*snapStore); ok { |
| + return ss.sn.SourceReadStartedAt, ss.sn.Complete |
| + } |
| + return time.Time{}, false |
| +} |
diff --git a/internal/provision/sidecar_reconcile.go b/internal/provision/sidecar_reconcile.go| index 4a7c6d8d6..0fb7ccfe9 100644 |
| --- a/internal/provision/sidecar_reconcile.go |
| +++ b/internal/provision/sidecar_reconcile.go |
| @@ -202,10 +202,12 @@ func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Regis |
| // every record by exactly these rules, placement against the record and |
| // the app's sidecars manifest included (S3 change-index design §4.4). |
| type sidecarScan struct { |
| - recs map[string]SidecarRecord |
| - protect map[string]bool |
| - readFailed bool |
| - manifestFor func(acct, app string) (SidecarManifest, bool) |
| + departureRecords []DepartureHost |
| + departureInvalid bool |
| + recs map[string]SidecarRecord |
| + protect map[string]bool |
| + readFailed bool |
| + manifestFor func(acct, app string) (SidecarManifest, bool) |
| } |
| scan := func(st release.Store) (*sidecarScan, error) { |
| sc := &sidecarScan{} |
| @@ -340,6 +342,11 @@ func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Regis |
| protect[host] = true |
| continue |
| } |
| + if cfg.Departures != nil { |
| + h, ok := departureSidecar(rec, raw) |
| + sc.departureRecords = append(sc.departureRecords, h) |
| + sc.departureInvalid = sc.departureInvalid || !ok |
| + } |
| if rec.Region != cfg.Region || !poolServed(cfg.Pools, rec.Pool) { |
| continue // another agent's jurisdiction, not this pass's business |
| } |
| @@ -372,6 +379,11 @@ func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Regis |
| return sc, nil |
| } |
| sc, err := scan(s) |
| + if sc == nil { |
| + cfg.Departures.family("sidecar", nil, false) |
| + } else { |
| + cfg.Departures.family("sidecar", sc.departureRecords, err == nil && !sc.departureInvalid && !sc.readFailed && len(sc.protect) == 0) |
| + } |
| if err != nil { |
| return err |
| } |