replicagen: one generation prefix helper; lease: head.json
internal/replicagen names a replica's generations: Name(lockGen) is g-%020d, Valid is strict (@root or g- plus twenty digits), ValidClaim keeps the claim code's component checks so claim generation "42" still works, ClaimName builds g-<gen>, Prefix is the slash-terminated object prefix and ClientPath the slashless path a Litestream client takes. hostbox.GenerationPrefix, moves.ReplicaSource and genselect's prefix now delegate to replicagen.Prefix. Their outputs are pinned by literal tables captured before the fold (replicagen TestPrefixMatchesTheThreeTwins, genselect TestPrefixMatchesReplicagen); their own tests are unchanged. internal/lease/head.go is the head.json codec per spec section 3.1: ReadHead (absent is found=false; a body that is not v 1 or names an invalid generation is an error), PutHead (create-only on ifMatch "", conflicts are release.ErrCASConflict, invalid heads are refused before any write) and TrimHistory. Nothing calls them yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+638
−25
internal/genselect/prefix_fold_test.go+25 −0internal/genselect/select.go+10 −7internal/hostbox/writer.go+6 −7internal/lease/head.go+159 −0internal/lease/head_test.go+217 −0internal/moves/build.go+2 −3internal/moves/source.go+7 −8internal/replicagen/replicagen.go+78 −0internal/replicagen/replicagen_test.go+134 −0
diff --git a/internal/genselect/prefix_fold_test.go b/internal/genselect/prefix_fold_test.go| new file mode 100644 |
| index 000000000..026843fcd |
| --- /dev/null |
| +++ b/internal/genselect/prefix_fold_test.go |
| @@ -0,0 +1,25 @@ |
| +package genselect |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// TestPrefixMatchesReplicagen pins prefix's outputs, captured before it was |
| +// folded onto replicagen.Prefix, so the fold cannot change them. The same |
| +// literal table is in replicagen's TestPrefixMatchesTheThreeTwins. |
| +func TestPrefixMatchesReplicagen(t *testing.T) { |
| + for _, tc := range []struct{ location, gen, want string }{ |
| + {"instances/shop.example.com", "@root", "instances/shop.example.com/"}, |
| + {"instances/shop.example.com/", "@root", "instances/shop.example.com/"}, |
| + {"instances/shop.example.com", "42", "instances/shop.example.com/g-42/"}, |
| + {"instances/shop.example.com", "00000000000000000042", "instances/shop.example.com/g-00000000000000000042/"}, |
| + {"instances/shop.example.com/inc1", "cur", "instances/shop.example.com/inc1/g-cur/"}, |
| + {"instances/shop.example.com/inc1/", "cur", "instances/shop.example.com/inc1/g-cur/"}, |
| + } { |
| + location := strings.TrimSuffix(tc.location, "/") + "/" // requestLocation's form |
| + if got := prefix(location, tc.gen); got != tc.want { |
| + t.Errorf("prefix(%q, %q) = %q, want %q", location, tc.gen, got, tc.want) |
| + } |
| + } |
| +} |
diff --git a/internal/genselect/select.go b/internal/genselect/select.go| index 645491257..567de7f7e 100644 |
| --- a/internal/genselect/select.go |
| +++ b/internal/genselect/select.go |
| @@ -13,6 +13,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| "github.com/superfly/ltx" |
| ) |
| @@ -110,18 +111,20 @@ func component(s string) bool { |
| return s != "" && s != "." && s != ".." && !strings.ContainsAny(s, "/\\\x00") |
| } |
| -func generation(s string) bool { return component(s) && s != hostclaim.RootGeneration } |
| +func generation(s string) bool { return replicagen.ValidClaim(s) } |
| func versionID(s string) bool { return strings.TrimSpace(s) != "" && s != "null" } |
| -// prefix is a generation's prefix under location. Twins of the rule: |
| -// hostbox.GenerationPrefix and moves.ReplicaSource (whose keep is |
| -// coordinates' level-file test); the three change together. |
| +// prefix is a generation's prefix under location, which is |
| +// slash-terminated (requestLocation's form). The rule is replicagen.Prefix, |
| +// shared with hostbox.GenerationPrefix and moves.ReplicaSource (whose keep |
| +// is coordinates' level-file test). |
| func prefix(location, gen string) string { |
| - if gen == hostclaim.RootGeneration { |
| - return location |
| + name := replicagen.Root |
| + if gen != hostclaim.RootGeneration { |
| + name = replicagen.ClaimName(gen) |
| } |
| - return location + "g-" + gen + "/" |
| + return replicagen.Prefix(strings.TrimSuffix(location, "/"), name) |
| } |
| func coordinates(key, base string) (File, bool) { |
diff --git a/internal/hostbox/writer.go b/internal/hostbox/writer.go| index f6d61eebf..98ead6b2f 100644 |
| --- a/internal/hostbox/writer.go |
| +++ b/internal/hostbox/writer.go |
| @@ -2,13 +2,13 @@ package hostbox |
| import ( |
| "context" |
| - "fmt" |
| "github.com/carlosframework/platform/internal/park" |
| "strings" |
| "github.com/carlosframework/platform/internal/genselect" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| ) |
| // Writer supplies transition adapters, not stop, certificate or marker evidence. |
| @@ -74,13 +74,12 @@ func (w Writer) Published(ctx context.Context, observed hostclaim.Observed) (hos |
| return hostclaim.Update(ctx, w.Claims, observed, hostclaim.PublishGeneration(c.Op.ID, c.Op.Phase, c.Holder.Session, c.Holder.Generation, w.Region, w.NewID)) |
| } |
| -// GenerationPrefix is a holder's generation prefix. Twins of its rule: |
| -// genselect's prefix and coordinates, and moves.ReplicaSource (which also |
| -// covers the root generation); the three change together. |
| +// GenerationPrefix is a holder's generation prefix, by replicagen.Prefix |
| +// (the one rule genselect's prefix and moves.ReplicaSource also use). It |
| +// refuses the root generation and a holder with no session. |
| func GenerationPrefix(holder hostclaim.Holder) (string, error) { |
| - generation := holder.Generation |
| - if holder.Session == 0 || generation == "" || generation == hostclaim.RootGeneration || generation == "." || generation == ".." || strings.ContainsAny(generation, "/\\\x00") || holder.Location == "" { |
| + if holder.Session == 0 || !replicagen.ValidClaim(holder.Generation) || holder.Location == "" { |
| return "", ErrUnsupported |
| } |
| - return fmt.Sprintf("%s/g-%s/", strings.TrimSuffix(holder.Location, "/"), generation), nil |
| + return replicagen.Prefix(strings.TrimSuffix(holder.Location, "/"), replicagen.ClaimName(holder.Generation)), nil |
| } |
diff --git a/internal/lease/head.go b/internal/lease/head.go| new file mode 100644 |
| index 000000000..3f03c435f |
| --- /dev/null |
| +++ b/internal/lease/head.go |
| @@ -0,0 +1,159 @@ |
| +package lease |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "os" |
| + "strings" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +// HeadVersion is head.json's format version. A body of any other version is |
| +// an error, never a missing head. |
| +const HeadVersion = 1 |
| + |
| +// headName is head.json's key under a location. |
| +const headName = "head.json" |
| + |
| +// Head is `<loc>/head.json`, the pointer to a location's current replica |
| +// generation (spec 2026-11-12 region HA storage generations, §3.1). Absent |
| +// means the root layout. It holds no version ids, so a move can copy it as |
| +// it is. |
| +type Head struct { |
| + V int `json:"v"` |
| + // Generation is the current generation, always a Name: the root |
| + // generation is never written once head.json exists. |
| + Generation string `json:"generation"` |
| + CreatedBy HeadCreator `json:"created_by"` |
| + // StartTXID is the TXID the take's copy ended at; the generation's own |
| + // writes begin after it. 0 on a first wake. |
| + StartTXID uint64 `json:"start_txid"` |
| + // Predecessor is the generation the take copied from: a Name, Root |
| + // (the migration) or "" (a first wake). |
| + Predecessor string `json:"predecessor"` |
| + // History is the earlier generations still inside the restore window, |
| + // newest first (TrimHistory). |
| + History []HeadHistory `json:"history"` |
| +} |
| + |
| +// HeadCreator is the take that created Head's generation. |
| +type HeadCreator struct { |
| + LockGeneration int64 `json:"lock_generation"` |
| + Box string `json:"box"` |
| + IID string `json:"iid"` |
| + Lifetime string `json:"lifetime"` |
| + At time.Time `json:"at"` |
| +} |
| + |
| +// HeadHistory is an earlier generation and the time it stopped being |
| +// current. |
| +type HeadHistory struct { |
| + Generation string `json:"generation"` |
| + StartTXID uint64 `json:"start_txid"` |
| + CreatedAt time.Time `json:"created_at"` |
| + EndedAt time.Time `json:"ended_at"` |
| +} |
| + |
| +// validate refuses a head that is not version 1 or names a generation that |
| +// is not replicagen.Valid. |
| +func (h Head) validate() error { |
| + if h.V != HeadVersion { |
| + return fmt.Errorf("head.json: version %d, want %d", h.V, HeadVersion) |
| + } |
| + if h.Generation == replicagen.Root || !replicagen.Valid(h.Generation) { |
| + return fmt.Errorf("head.json: generation %q is not a generation name", h.Generation) |
| + } |
| + if h.Predecessor != "" && !replicagen.Valid(h.Predecessor) { |
| + return fmt.Errorf("head.json: predecessor %q is not a generation name", h.Predecessor) |
| + } |
| + for i, e := range h.History { |
| + if !replicagen.Valid(e.Generation) { |
| + return fmt.Errorf("head.json: history[%d] generation %q is not a generation name", i, e.Generation) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// headKey is loc's head.json key. loc is a location without a trailing |
| +// slash, such as instances/shop.example.com. |
| +func headKey(loc string) (string, error) { |
| + if loc == "" || strings.HasSuffix(loc, "/") { |
| + return "", fmt.Errorf("head.json: location %q: want a location without a trailing slash", loc) |
| + } |
| + return loc + "/" + headName, nil |
| +} |
| + |
| +// ReadHead reads loc's head.json with its ETag. An absent head.json is |
| +// found false and a nil error (the root layout); any other read failure, |
| +// or a body that does not decode, is not version 1 or names an invalid |
| +// generation, is an error and never reads as absent. |
| +func ReadHead(ctx context.Context, st release.Store, loc string) (h Head, etag string, found bool, err error) { |
| + key, err := headKey(loc) |
| + if err != nil { |
| + return Head{}, "", false, err |
| + } |
| + body, etag, err := st.Get(ctx, key) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return Head{}, "", false, nil |
| + } |
| + if err != nil { |
| + return Head{}, "", false, fmt.Errorf("head.json: read %s: %w", key, err) |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(body)) |
| + if err := dec.Decode(&h); err != nil { |
| + return Head{}, "", false, fmt.Errorf("head.json: decode %s: %w", key, err) |
| + } |
| + if dec.More() { |
| + return Head{}, "", false, fmt.Errorf("head.json: decode %s: data after the object", key) |
| + } |
| + if err := h.validate(); err != nil { |
| + return Head{}, "", false, fmt.Errorf("%s: %w", key, err) |
| + } |
| + return h, etag, true, nil |
| +} |
| + |
| +// PutHead writes loc's head.json and returns its new ETag. ifMatch "" is |
| +// create-only (If-None-Match: *); otherwise it replaces only the head with |
| +// that ETag. A lost race is release.ErrCASConflict. A head that is not |
| +// version 1 or names an invalid generation is refused before any write. |
| +func PutHead(ctx context.Context, st release.Store, loc string, h Head, ifMatch string) (string, error) { |
| + key, err := headKey(loc) |
| + if err != nil { |
| + return "", err |
| + } |
| + if err := h.validate(); err != nil { |
| + return "", err |
| + } |
| + if h.History == nil { |
| + h.History = []HeadHistory{} |
| + } |
| + body, err := json.Marshal(h) |
| + if err != nil { |
| + return "", fmt.Errorf("head.json: encode: %w", err) |
| + } |
| + etag, err := st.Put(ctx, key, body, ifMatch) |
| + if err != nil { |
| + return "", fmt.Errorf("head.json: write %s: %w", key, err) |
| + } |
| + return etag, nil |
| +} |
| + |
| +// TrimHistory keeps the entries of h whose EndedAt is after now-window, in |
| +// their order (newest first). It returns a new, non-nil slice and never |
| +// changes h. |
| +func TrimHistory(h []HeadHistory, now time.Time, window time.Duration) []HeadHistory { |
| + cutoff := now.Add(-window) |
| + out := make([]HeadHistory, 0, len(h)) |
| + for _, e := range h { |
| + if e.EndedAt.After(cutoff) { |
| + out = append(out, e) |
| + } |
| + } |
| + return out |
| +} |
diff --git a/internal/lease/head_test.go b/internal/lease/head_test.go| new file mode 100644 |
| index 000000000..435cf803a |
| --- /dev/null |
| +++ b/internal/lease/head_test.go |
| @@ -0,0 +1,217 @@ |
| +package lease_test |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +const headLoc = "instances/shop.example.com" |
| + |
| +func sampleHead() lease.Head { |
| + at := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) |
| + return lease.Head{ |
| + V: 1, |
| + Generation: replicagen.Name(42), |
| + CreatedBy: lease.HeadCreator{LockGeneration: 42, Box: "box-a", IID: "i-0abc", |
| + Lifetime: "inc-1", At: at}, |
| + StartTXID: 1234, |
| + Predecessor: replicagen.Name(37), |
| + History: []lease.HeadHistory{{Generation: replicagen.Name(37), StartTXID: 900, |
| + CreatedAt: at.Add(-time.Hour), EndedAt: at}}, |
| + } |
| +} |
| + |
| +func TestHeadRoundTripAndCAS(t *testing.T) { |
| + ctx := t.Context() |
| + st := release.NewDirStore(t.TempDir()) |
| + |
| + if h, etag, found, err := lease.ReadHead(ctx, st, headLoc); err != nil || found || etag != "" || !reflect.DeepEqual(h, lease.Head{}) { |
| + t.Fatalf("ReadHead(absent) = %+v, %q, %v, %v; want zero, not found, nil", h, etag, found, err) |
| + } |
| + |
| + want := sampleHead() |
| + etag, err := lease.PutHead(ctx, st, headLoc, want, "") |
| + if err != nil || etag == "" { |
| + t.Fatalf("PutHead(create) = %q, %v", etag, err) |
| + } |
| + body, _, err := st.Get(ctx, headLoc+"/head.json") |
| + if err != nil { |
| + t.Fatalf("head.json not at <loc>/head.json: %v", err) |
| + } |
| + var fields map[string]any |
| + if err := json.Unmarshal(body, &fields); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, k := range []string{"v", "generation", "created_by", "start_txid", "predecessor", "history"} { |
| + if _, ok := fields[k]; !ok { |
| + t.Errorf("head.json lacks %q: %s", k, body) |
| + } |
| + } |
| + if len(fields) != 6 { |
| + t.Errorf("head.json has %d fields, want 6: %s", len(fields), body) |
| + } |
| + cb := fields["created_by"].(map[string]any) |
| + for _, k := range []string{"lock_generation", "box", "iid", "lifetime", "at"} { |
| + if _, ok := cb[k]; !ok { |
| + t.Errorf("created_by lacks %q: %s", k, body) |
| + } |
| + } |
| + if cb["at"] != "2026-11-12T10:00:00Z" { |
| + t.Errorf("created_by.at = %v, want RFC 3339 UTC", cb["at"]) |
| + } |
| + hist := fields["history"].([]any)[0].(map[string]any) |
| + for _, k := range []string{"generation", "start_txid", "created_at", "ended_at"} { |
| + if _, ok := hist[k]; !ok { |
| + t.Errorf("history[0] lacks %q: %s", k, body) |
| + } |
| + } |
| + |
| + got, readTag, found, err := lease.ReadHead(ctx, st, headLoc) |
| + if err != nil || !found || readTag != etag || !reflect.DeepEqual(got, want) { |
| + t.Fatalf("ReadHead = %+v, %q, %v, %v; want %+v, %q", got, readTag, found, err, want, etag) |
| + } |
| + |
| + // A second create-only write loses. |
| + if _, err := lease.PutHead(ctx, st, headLoc, want, ""); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("second create-only PutHead = %v, want ErrCASConflict", err) |
| + } |
| + |
| + // A switch by If-Match succeeds once; the stale ETag then loses. |
| + next := want |
| + next.Generation, next.Predecessor = replicagen.Name(50), want.Generation |
| + next.CreatedBy.LockGeneration = 50 |
| + etag2, err := lease.PutHead(ctx, st, headLoc, next, etag) |
| + if err != nil || etag2 == etag { |
| + t.Fatalf("PutHead(If-Match) = %q, %v", etag2, err) |
| + } |
| + if _, err := lease.PutHead(ctx, st, headLoc, want, etag); !errors.Is(err, release.ErrCASConflict) { |
| + t.Fatalf("stale If-Match PutHead = %v, want ErrCASConflict", err) |
| + } |
| + if got, _, _, _ := lease.ReadHead(ctx, st, headLoc); got.Generation != next.Generation { |
| + t.Fatalf("head moved to %q, want %q", got.Generation, next.Generation) |
| + } |
| +} |
| + |
| +func TestReadHeadRefusesBadBodies(t *testing.T) { |
| + ctx := t.Context() |
| + good, err := json.Marshal(sampleHead()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + edit := func(f func(m map[string]any)) []byte { |
| + var m map[string]any |
| + if err := json.Unmarshal(good, &m); err != nil { |
| + t.Fatal(err) |
| + } |
| + f(m) |
| + b, err := json.Marshal(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return b |
| + } |
| + for name, body := range map[string][]byte{ |
| + "v2": edit(func(m map[string]any) { m["v"] = 2 }), |
| + "no v": edit(func(m map[string]any) { delete(m, "v") }), |
| + "claim generation": edit(func(m map[string]any) { m["generation"] = "g-42" }), |
| + "root generation": edit(func(m map[string]any) { m["generation"] = "@root" }), |
| + "empty generation": edit(func(m map[string]any) { m["generation"] = "" }), |
| + "traversal": edit(func(m map[string]any) { m["generation"] = "../x" }), |
| + "bad predecessor": edit(func(m map[string]any) { m["predecessor"] = "g-37" }), |
| + "bad history": edit(func(m map[string]any) { m["history"].([]any)[0].(map[string]any)["generation"] = "g-0000/" }), |
| + "not json": []byte("{"), |
| + "empty body": {}, |
| + "trailing data": append(append([]byte{}, good...), []byte(`{}`)...), |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + st := release.NewDirStore(t.TempDir()) |
| + if _, err := st.Put(ctx, headLoc+"/head.json", body, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + if h, _, found, err := lease.ReadHead(ctx, st, headLoc); err == nil { |
| + t.Fatalf("ReadHead(%s) = %+v, found %v, nil error; want an error", body, h, found) |
| + } |
| + }) |
| + } |
| + // The root generation is a valid predecessor (the migration) and an |
| + // empty one is a first wake. |
| + for _, pred := range []string{replicagen.Root, ""} { |
| + st := release.NewDirStore(t.TempDir()) |
| + h := sampleHead() |
| + h.Predecessor, h.History = pred, nil |
| + if _, err := lease.PutHead(ctx, st, headLoc, h, ""); err != nil { |
| + t.Fatalf("PutHead(predecessor %q) = %v", pred, err) |
| + } |
| + if got, _, found, err := lease.ReadHead(ctx, st, headLoc); err != nil || !found || got.Predecessor != pred { |
| + t.Fatalf("ReadHead(predecessor %q) = %+v, %v, %v", pred, got, found, err) |
| + } |
| + } |
| +} |
| + |
| +func TestPutHeadRefusesBadHeads(t *testing.T) { |
| + ctx := t.Context() |
| + st := release.NewDirStore(t.TempDir()) |
| + for name, mut := range map[string]func(h *lease.Head){ |
| + "v0": func(h *lease.Head) { h.V = 0 }, |
| + "claim generation": func(h *lease.Head) { h.Generation = "g-42" }, |
| + "root generation": func(h *lease.Head) { h.Generation = replicagen.Root }, |
| + "bad history": func(h *lease.Head) { h.History[0].Generation = "x" }, |
| + } { |
| + h := sampleHead() |
| + mut(&h) |
| + if _, err := lease.PutHead(ctx, st, headLoc, h, ""); err == nil { |
| + t.Errorf("PutHead(%s) = nil error", name) |
| + } |
| + } |
| + for _, loc := range []string{"", headLoc + "/"} { |
| + if _, err := lease.PutHead(ctx, st, loc, sampleHead(), ""); err == nil { |
| + t.Errorf("PutHead(loc %q) = nil error", loc) |
| + } |
| + if _, _, _, err := lease.ReadHead(ctx, st, loc); err == nil { |
| + t.Errorf("ReadHead(loc %q) = nil error", loc) |
| + } |
| + } |
| + if keys, err := st.List(ctx, ""); err != nil || len(keys) != 0 { |
| + t.Fatalf("refused PutHeads wrote %v (%v)", keys, err) |
| + } |
| +} |
| + |
| +func TestTrimHistoryDropsEndedOutsideWindow(t *testing.T) { |
| + now := time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) |
| + window := 7 * 24 * time.Hour |
| + entry := func(n int64, ago time.Duration) lease.HeadHistory { |
| + return lease.HeadHistory{Generation: replicagen.Name(n), EndedAt: now.Add(-ago)} |
| + } |
| + in := []lease.HeadHistory{ |
| + entry(9, time.Hour), |
| + entry(8, 6*24*time.Hour), |
| + entry(7, window-time.Second), |
| + entry(6, window), // exactly at the edge: not after now-window |
| + entry(5, 8*24*time.Hour), |
| + entry(4, 30*24*time.Hour), |
| + } |
| + orig := append([]lease.HeadHistory(nil), in...) |
| + got := lease.TrimHistory(in, now, window) |
| + var names []string |
| + for _, h := range got { |
| + names = append(names, h.Generation) |
| + } |
| + want := []string{replicagen.Name(9), replicagen.Name(8), replicagen.Name(7)} |
| + if strings.Join(names, ",") != strings.Join(want, ",") { |
| + t.Fatalf("TrimHistory = %v, want %v (newest first)", names, want) |
| + } |
| + if !reflect.DeepEqual(in, orig) { |
| + t.Fatalf("TrimHistory changed its input") |
| + } |
| + if got := lease.TrimHistory(nil, now, window); got == nil || len(got) != 0 { |
| + t.Fatalf("TrimHistory(nil) = %#v, want an empty, non-nil slice", got) |
| + } |
| +} |
diff --git a/internal/moves/build.go b/internal/moves/build.go| index 465cdb5f5..674e812cc 100644 |
| --- a/internal/moves/build.go |
| +++ b/internal/moves/build.go |
| @@ -68,9 +68,8 @@ type BuildIntent struct { |
| // GenerationPrefix is `<location>/g-<op>/`: the prepared generation a move |
| // (or a relocation) installs under a holder's location. The location is |
| -// normalised with TrimSuffix(location, "/") + "/" through ReplicaSource, |
| -// whose rule this shares with hostbox.GenerationPrefix and genselect's |
| -// prefix; the four change together (G24, I73). |
| +// normalised through ReplicaSource, whose rule is replicagen.Prefix, the |
| +// one hostbox.GenerationPrefix and genselect's prefix also use (G24, I73). |
| func GenerationPrefix(location, op string) string { |
| prefix, _ := ReplicaSource(hostclaim.Holder{Location: location, Generation: op}) |
| return prefix |
diff --git a/internal/moves/source.go b/internal/moves/source.go| index aa8cfd81b..516a044fa 100644 |
| --- a/internal/moves/source.go |
| +++ b/internal/moves/source.go |
| @@ -6,6 +6,7 @@ import ( |
| "strings" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| "github.com/superfly/ltx" |
| ) |
| @@ -23,17 +24,15 @@ import ( |
| // finding 4). A generation of "" or hostclaim.RootGeneration is the root |
| // layout: the level directories sit directly under the location. |
| // |
| -// The generation prefix rule has twins: hostbox.GenerationPrefix (which |
| -// refuses the root generation and a holder with no session, so a source |
| -// copy cannot use it) and genselect's unexported prefix and coordinates. |
| -// The three change together. |
| +// The prefix is replicagen.Prefix, the rule hostbox.GenerationPrefix |
| +// (which refuses the root generation and a holder with no session, so a |
| +// source copy cannot use it) and genselect's prefix also use. |
| func ReplicaSource(h hostclaim.Holder) (prefix string, keep func(rel string) bool) { |
| - base := strings.TrimSuffix(h.Location, "/") + "/" |
| - prefix = base |
| + name := replicagen.Root |
| if g := h.Generation; g != "" && g != hostclaim.RootGeneration { |
| - prefix = base + "g-" + g + "/" |
| + name = replicagen.ClaimName(g) |
| } |
| - return prefix, levelFile |
| + return replicagen.Prefix(strings.TrimSuffix(h.Location, "/"), name), levelFile |
| } |
| // levelFile is ReplicaSource's keep: exactly two path parts, a level |
diff --git a/internal/replicagen/replicagen.go b/internal/replicagen/replicagen.go| new file mode 100644 |
| index 000000000..a7ce33899 |
| --- /dev/null |
| +++ b/internal/replicagen/replicagen.go |
| @@ -0,0 +1,78 @@ |
| +// Package replicagen names a replica's generations and their prefixes: |
| +// the one rule for `<loc>/g-<id>/` (spec 2026-11-12 region HA storage |
| +// generations, §3). The claim code's prefixes (hostbox.GenerationPrefix, |
| +// moves.ReplicaSource, genselect's prefix) are built here too. |
| +// |
| +// Two kinds of name share the shape. A head.json generation is |
| +// Name(lockGen), `g-` and twenty digits, and only it or Root passes Valid. |
| +// A claim generation is any single path component but Root; ClaimName |
| +// builds its `g-<gen>` and ValidClaim keeps the claim code's checks. |
| +// |
| +// The package imports nothing of the claim code, so lease can use it; |
| +// Root equals hostclaim.RootGeneration (a test holds them together). |
| +package replicagen |
| + |
| +import ( |
| + "fmt" |
| + "strings" |
| +) |
| + |
| +// Root is the root generation: the level files directly under the |
| +// location, the legacy layout. It is hostclaim.RootGeneration. |
| +const Root = "@root" |
| + |
| +// Name is the generation a take with lock generation lockGen creates, |
| +// zero-padded to twenty digits so names sort as the takes did. |
| +func Name(lockGen int64) string { return fmt.Sprintf("g-%020d", lockGen) } |
| + |
| +// Valid reports whether name is Root or a Name: `g-` followed by exactly |
| +// twenty ASCII digits. head.json, the resolver and the door accept only |
| +// these. A claim name (ClaimName) is not Valid unless it happens to be one. |
| +func Valid(name string) bool { |
| + if name == Root { |
| + return true |
| + } |
| + digits, ok := strings.CutPrefix(name, "g-") |
| + if !ok || len(digits) != 20 { |
| + return false |
| + } |
| + for i := 0; i < len(digits); i++ { |
| + if digits[i] < '0' || digits[i] > '9' { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// ValidClaim reports whether gen is a usable claim generation: one |
| +// non-empty path component (not "." or "..", no "/", "\" or NUL) that is |
| +// not Root. These are the checks the claim code made before the fold. |
| +func ValidClaim(gen string) bool { |
| + return gen != "" && gen != "." && gen != ".." && gen != Root && !strings.ContainsAny(gen, "/\\\x00") |
| +} |
| + |
| +// ClaimName is a claim generation's directory name, `g-<gen>`. It does not |
| +// check gen; callers check ValidClaim first. |
| +func ClaimName(gen string) string { return "g-" + gen } |
| + |
| +// Prefix is generation name's object prefix under loc, slash-terminated: |
| +// loc+"/" for Root, loc+"/"+name+"/" otherwise. loc carries no trailing |
| +// slash; a caller holding a slash-terminated location trims it. Prefix |
| +// does not check name: callers check Valid or ValidClaim. |
| +func Prefix(loc, name string) string { |
| + if name == Root { |
| + return loc + "/" |
| + } |
| + return loc + "/" + name + "/" |
| +} |
| + |
| +// ClientPath is the Path a Litestream replica client for generation name |
| +// takes: loc for Root, loc+"/"+name otherwise, with no trailing slash, |
| +// since Litestream joins the path and a level with "/" itself. ClientPath |
| +// plus "/" is Prefix. |
| +func ClientPath(loc, name string) string { |
| + if name == Root { |
| + return loc |
| + } |
| + return loc + "/" + name |
| +} |
diff --git a/internal/replicagen/replicagen_test.go b/internal/replicagen/replicagen_test.go| new file mode 100644 |
| index 000000000..969bd3363 |
| --- /dev/null |
| +++ b/internal/replicagen/replicagen_test.go |
| @@ -0,0 +1,134 @@ |
| +package replicagen_test |
| + |
| +import ( |
| + "errors" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/hostbox" |
| + "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/moves" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +func TestNameSortsAndRoundTrips(t *testing.T) { |
| + if got := replicagen.Name(42); got != "g-00000000000000000042" { |
| + t.Fatalf("Name(42) = %q", got) |
| + } |
| + if !(replicagen.Name(9) < replicagen.Name(10)) { |
| + t.Fatalf("Name(9) = %q does not sort before Name(10) = %q", replicagen.Name(9), replicagen.Name(10)) |
| + } |
| + for _, n := range []int64{0, 1, 42, 1 << 40, 1<<63 - 1} { |
| + if name := replicagen.Name(n); !replicagen.Valid(name) { |
| + t.Errorf("Valid(Name(%d) = %q) = false", n, name) |
| + } |
| + } |
| + for name, want := range map[string]bool{ |
| + "@root": true, |
| + "g-00000000000000000042": true, |
| + "g-42": false, // a claim name is not a head.json name |
| + "g-00000000000000000042/": false, |
| + "g-0000000000000000042": false, // 19 digits |
| + "g-000000000000000000042": false, // 21 digits |
| + "g-0000000000000000004a": false, |
| + "G-00000000000000000042": false, |
| + "../x": false, |
| + "": false, |
| + "@root/": false, |
| + "00000000000000000042": false, |
| + } { |
| + if got := replicagen.Valid(name); got != want { |
| + t.Errorf("Valid(%q) = %v, want %v", name, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestValidClaimKeepsTheTwinsChecks(t *testing.T) { |
| + for gen, want := range map[string]bool{ |
| + "42": true, |
| + "cur": true, |
| + "00000000000000000042": true, |
| + "": false, |
| + hostclaim.RootGeneration: false, |
| + ".": false, |
| + "..": false, |
| + "a/b": false, |
| + "a\\b": false, |
| + "a\x00b": false, |
| + } { |
| + if got := replicagen.ValidClaim(gen); got != want { |
| + t.Errorf("ValidClaim(%q) = %v, want %v", gen, got, want) |
| + } |
| + } |
| + if got := replicagen.ClaimName("42"); got != "g-42" { |
| + t.Errorf("ClaimName(42) = %q", got) |
| + } |
| +} |
| + |
| +func TestRootIsTheClaimRoot(t *testing.T) { |
| + if replicagen.Root != hostclaim.RootGeneration { |
| + t.Fatalf("replicagen.Root = %q, hostclaim.RootGeneration = %q", replicagen.Root, hostclaim.RootGeneration) |
| + } |
| +} |
| + |
| +// twinTable is the three twins' outputs captured before the fold, as |
| +// literal strings. genselect's TestPrefixMatchesReplicagen pins the same |
| +// table against its unexported prefix. |
| +var twinTable = []struct{ location, gen, want string }{ |
| + {"instances/shop.example.com", "@root", "instances/shop.example.com/"}, |
| + {"instances/shop.example.com/", "@root", "instances/shop.example.com/"}, |
| + {"instances/shop.example.com", "42", "instances/shop.example.com/g-42/"}, |
| + {"instances/shop.example.com", "00000000000000000042", "instances/shop.example.com/g-00000000000000000042/"}, |
| + {"instances/shop.example.com/inc1", "cur", "instances/shop.example.com/inc1/g-cur/"}, |
| + {"instances/shop.example.com/inc1/", "cur", "instances/shop.example.com/inc1/g-cur/"}, |
| +} |
| + |
| +func TestPrefixMatchesTheThreeTwins(t *testing.T) { |
| + for _, tc := range twinTable { |
| + loc := strings.TrimSuffix(tc.location, "/") |
| + name := replicagen.Root |
| + if tc.gen != hostclaim.RootGeneration { |
| + name = replicagen.ClaimName(tc.gen) |
| + } |
| + if got := replicagen.Prefix(loc, name); got != tc.want { |
| + t.Errorf("Prefix(%q, %q) = %q, want %q", loc, name, got, tc.want) |
| + } |
| + h := hostclaim.Holder{Location: tc.location, Generation: tc.gen, Session: 1} |
| + if got, _ := moves.ReplicaSource(h); got != tc.want { |
| + t.Errorf("moves.ReplicaSource(%q, %q) = %q, want %q", tc.location, tc.gen, got, tc.want) |
| + } |
| + got, err := hostbox.GenerationPrefix(h) |
| + if tc.gen == hostclaim.RootGeneration { |
| + if !errors.Is(err, hostbox.ErrUnsupported) { |
| + t.Errorf("hostbox.GenerationPrefix(%q, root) = %q, %v; want ErrUnsupported", tc.location, got, err) |
| + } |
| + continue |
| + } |
| + if err != nil || got != tc.want { |
| + t.Errorf("hostbox.GenerationPrefix(%q, %q) = %q, %v; want %q", tc.location, tc.gen, got, err, tc.want) |
| + } |
| + } |
| + // moves reads an empty generation as the root. |
| + if got, _ := moves.ReplicaSource(hostclaim.Holder{Location: "instances/shop.example.com"}); got != "instances/shop.example.com/" { |
| + t.Errorf("moves.ReplicaSource(no generation) = %q", got) |
| + } |
| + if got := replicagen.Prefix("instances/shop.example.com", replicagen.Name(42)); got != "instances/shop.example.com/g-00000000000000000042/" { |
| + t.Errorf("Prefix(Name(42)) = %q", got) |
| + } |
| +} |
| + |
| +func TestClientPathHasNoTrailingSlash(t *testing.T) { |
| + loc := "instances/shop.example.com" |
| + if got := replicagen.ClientPath(loc, replicagen.Root); got != loc { |
| + t.Errorf("ClientPath(root) = %q, want %q", got, loc) |
| + } |
| + if got := replicagen.ClientPath(loc, replicagen.Name(42)); got != loc+"/g-00000000000000000042" { |
| + t.Errorf("ClientPath(Name(42)) = %q", got) |
| + } |
| + // Litestream joins ClientPath and a level with "/": the result is Prefix. |
| + for _, name := range []string{replicagen.Root, replicagen.Name(7)} { |
| + if got, want := replicagen.ClientPath(loc, name)+"/", replicagen.Prefix(loc, name); got != want { |
| + t.Errorf("ClientPath(%q)+/ = %q, Prefix = %q", name, got, want) |
| + } |
| + } |
| +} |