lease: one resolver for every replica reader
Spec 2026-11-12 section 6.1/6.2, invariant G4 (Task 6). ResolveReplica reads <loc>/head.json once and binds the generation it names (the root when there is none) with a read-only, prefix-confined Litestream client; ResolveReplicaAt picks the generation current at a time from head history and refuses a time before every kept generation with ErrBeforeHistory; BindReplica binds a named generation with no head read. ReadReplicaClient is gone. Restore, HasReplica (true whenever head.json exists) and the verify restore resolve first. The box db reads resolve at the request's time and map ErrBeforeHistory to history-gone; the restore drill resolves too. The console db door switches minimally to ResolveReplica, still cached by prefix (Task 8 rekeys and binds it). A guard test parses the module's Go source and refuses every other way of building a replica client at a location, with negative fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
38 files changed,
+1,477
−104
db_e2e_test.go+4 −1dbforward_e2e_test.go+5 −1internal/console/apidb.go+9 −5internal/console/apidb_test.go+13 −11internal/console/createleftovers.go+1 −1internal/console/createleftovers_test.go+9 −2internal/console/hap2_wiring_test.go+22 −1internal/console/server.go+1 −1internal/dbdoor/plan_from.go+2 −2internal/dbreads/agent.go+7 −4internal/dbreads/dbreadstest/dbreadstest.go+45 −3internal/dbreads/fixture_test.go+3 −3internal/dbreads/pull_test.go+2 −1internal/dbreads/read.go+12 −2internal/dbreads/read_test.go+5 −4internal/dbreads/resolve_test.go+81 −0internal/host/dbreads.go+3 −3internal/host/dbreads_rootrunner_linux_test.go+4 −2internal/lease/check.go+20 −14internal/lease/endpoint.go+0 −19internal/lease/endpoint_test.go+44 −8internal/lease/lease.go+12 −14internal/lease/leasetest/filereplica.go+48 −0internal/lease/readers_guard_test.go+307 −0internal/lease/resolve.go+215 −0internal/lease/resolve_test.go+406 −0internal/lease/testdata/readerguard/README.txt+4 −0internal/lease/testdata/readerguard/alias_new_client.go.txt+9 −0internal/lease/testdata/readerguard/allowed.go.txt+20 −0internal/lease/testdata/readerguard/default_name_literal.go.txt+7 −0internal/lease/testdata/readerguard/dot_import.go.txt+5 −0internal/lease/testdata/readerguard/from_url.go.txt+13 −0internal/lease/testdata/readerguard/lease_builder_call.go.txt+21 −0internal/lease/testdata/readerguard/lease_new_client.go.txt+9 −0internal/lease/testdata/readerguard/new_builtin.go.txt+9 −0internal/lease/testdata/readerguard/read_replica_client.go.txt+14 −0internal/ops/hibernate_verify.go+11 −2internal/ops/hibernate_verify_resolve_test.go+75 −0
diff --git a/db_e2e_test.go b/db_e2e_test.go| index 2c8d08b41..4b478d1cc 100644 |
| --- a/db_e2e_test.go |
| +++ b/db_e2e_test.go |
| @@ -1,6 +1,6 @@ |
| // End-to-end acceptance for `carlos db` (spec 2026-09-02): a REAL |
| // console.Server whose door reads a fake S3 holding a real litestream |
| -// replica, through the production replica client (lease.ReadReplicaClient |
| +// replica, through the production replica client (lease.ResolveReplica |
| // with CARLOS_S3_ENDPOINT), a device-flow login, then the real runDB verbs |
| // driven in-process. The member's whole path, with no box access and no |
| // AWS credentials of their own. TestE2ELogsThroughConsole's shape. |
| @@ -275,6 +275,9 @@ func TestE2EDBThroughConsole(t *testing.T) { |
| t.Fatal("the door never read the bucket") |
| } |
| for _, k := range fake.keys { |
| + if k == "instances/"+host+"/head.json" { |
| + continue // the resolver's one read (none here: the root layout) |
| + } |
| if !strings.HasPrefix(k, "instances/"+host+"/") || !strings.HasSuffix(k, ".ltx") { |
| t.Errorf("the door asked the bucket for %q", k) |
| } |
diff --git a/dbforward_e2e_test.go b/dbforward_e2e_test.go| index 7b54af62a..5874a50c8 100644 |
| --- a/dbforward_e2e_test.go |
| +++ b/dbforward_e2e_test.go |
| @@ -162,7 +162,11 @@ func newDBFE2E(t *testing.T, o dbfE2EOptions) *dbfE2E { |
| box := dbreadstest.Start(t, dbreadstest.Options{Store: e.store, Region: "uk", Box: "uk-1", Pub: e.pub, |
| HibernatePrefix: "instances", Worker: o.worker, |
| OpenReplica: func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) { |
| - return lease.ReadReplicaClient(ctx, "data", prefix, "us-east-1") |
| + r, err := lease.ResolveReplica(ctx, "data", prefix, "us-east-1") |
| + if err != nil { |
| + return nil, err |
| + } |
| + return r.Client, nil |
| }}) |
| ctx, cancel := context.WithCancel(context.Background()) |
| done := make(chan struct{}) |
diff --git a/internal/console/apidb.go b/internal/console/apidb.go| index ba1c94865..ed9d5aa9b 100644 |
| --- a/internal/console/apidb.go |
| +++ b/internal/console/apidb.go |
| @@ -491,8 +491,12 @@ type dbReplicaCache struct { |
| clients map[string]replicaReader |
| } |
| -// cachedReadReplica is the production dbReplica: lease.ReadReplicaClient on |
| -// the configured bucket, one per prefix. |
| +// cachedReadReplica is the production dbReplica: lease.ResolveReplica on |
| +// the configured bucket, one per prefix. The cache still holds the |
| +// generation a prefix first resolved to; keying it by generation, and |
| +// binding a door's flow to the generation it resolved, is the console |
| +// readers' own change (generations Task 8). No host has head.json until |
| +// then, so every prefix resolves to its root, as before. |
| func (s *Server) cachedReadReplica(ctx context.Context, prefix string) (replicaReader, error) { |
| c := &s.dbClients |
| c.mu.Lock() |
| @@ -500,15 +504,15 @@ func (s *Server) cachedReadReplica(ctx context.Context, prefix string) (replicaR |
| if rd, ok := c.clients[prefix]; ok { |
| return rd, nil |
| } |
| - rc, err := lease.ReadReplicaClient(ctx, s.cfg.HibernateBucket, prefix, s.cfg.HibernateRegion) |
| + r, err := lease.ResolveReplica(ctx, s.cfg.HibernateBucket, prefix, s.cfg.HibernateRegion) |
| if err != nil { |
| return nil, err |
| } |
| if c.clients == nil || len(c.clients) >= dbReplicaCacheMax { |
| c.clients = make(map[string]replicaReader, 8) |
| } |
| - c.clients[prefix] = rc |
| - return rc, nil |
| + c.clients[prefix] = r.Client |
| + return r.Client, nil |
| } |
| // The db door's stream bounds. The per-minute token budget bounds how many |
diff --git a/internal/console/apidb_test.go b/internal/console/apidb_test.go| index bf7501a20..a6a2ecb31 100644 |
| --- a/internal/console/apidb_test.go |
| +++ b/internal/console/apidb_test.go |
| @@ -20,7 +20,6 @@ import ( |
| "github.com/aws/smithy-go" |
| lsfile "github.com/benbjohnson/litestream/file" |
| - lss3 "github.com/benbjohnson/litestream/s3" |
| "github.com/superfly/ltx" |
| "github.com/carlosframework/platform/internal/dbdoor" |
| @@ -498,29 +497,32 @@ func TestAPIDBGetIsAudited(t *testing.T) { |
| // One replica client per prefix: a restore's dozens of requests share one |
| // transport rather than paying a handshake each. And the production reader |
| -// carries the configured bucket and the resolved prefix, nothing a request |
| -// supplied. |
| +// is the resolver's (no head.json: the root) on the configured bucket at |
| +// the resolved prefix, nothing a request supplied. |
| func TestCachedReadReplicaIsOnePerPrefix(t *testing.T) { |
| - t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| s := &Server{} |
| - s.cfg.HibernateBucket = "data-ie" |
| - s.cfg.HibernateRegion = "eu-west-1" |
| + b := useFakeDataBucket(t, s, ltxKey("instances/a.example.com", 0)) |
| ctx := context.Background() |
| a1, err := s.cachedReadReplica(ctx, "instances/a.example.com") |
| if err != nil { |
| t.Fatal(err) |
| } |
| a2, _ := s.cachedReadReplica(ctx, "instances/a.example.com") |
| - b, _ := s.cachedReadReplica(ctx, "instances/b.example.com") |
| + bc, _ := s.cachedReadReplica(ctx, "instances/b.example.com") |
| if a1 != a2 { |
| t.Error("the same prefix built two clients") |
| } |
| - if a1 == b { |
| + if a1 == bc { |
| t.Error("two prefixes shared one client") |
| } |
| - c, ok := a1.(*lss3.ReplicaClient) |
| - if !ok || c.Bucket != "data-ie" || c.Path != "instances/a.example.com" || c.Region != "eu-west-1" { |
| - t.Fatalf("client = %#v, want the configured bucket, region and the resolved prefix", a1) |
| + if found, err := anyLTXFile(ctx, a1, 0); err != nil || !found { |
| + t.Fatalf("a's client lists %v, %v; want a's level-0 file", found, err) |
| + } |
| + if found, err := anyLTXFile(ctx, bc, 0); err != nil || found { |
| + t.Fatalf("b's client lists %v, %v; want nothing", found, err) |
| + } |
| + if got := b.listed(); len(got) != 2 || got[0] != "instances/a.example.com/0000/" || got[1] != "instances/b.example.com/0000/" { |
| + t.Fatalf("listed %q, want each prefix's own level 0", got) |
| } |
| } |
diff --git a/internal/console/createleftovers.go b/internal/console/createleftovers.go| index 7e89d3ec3..108fc6294 100644 |
| --- a/internal/console/createleftovers.go |
| +++ b/internal/console/createleftovers.go |
| @@ -58,7 +58,7 @@ func (s *Server) leftoverCheckApplies(region, pool string) bool { |
| // as "empty": the caller refuses on uncertainty. |
| // |
| // The listing goes through s.dbReplica, the db door's cached |
| -// lease.ReadReplicaClient seam, so the reader here and the writer on the box |
| +// lease.ResolveReplica seam, so the reader here and the writer on the box |
| // cannot disagree about the bucket's endpoint, region or layout. |
| // |
| // Neither prefix may end in "/". litestream's S3 client lists |
diff --git a/internal/console/createleftovers_test.go b/internal/console/createleftovers_test.go| index 68f08c4dd..13bbe8ec6 100644 |
| --- a/internal/console/createleftovers_test.go |
| +++ b/internal/console/createleftovers_test.go |
| @@ -363,8 +363,8 @@ func TestLeftoverCheckResidency(t *testing.T) { |
| // ---- review round 1 (Astra, 6cc86d34) ----------------------------------------- |
| // fakeDataBucket is a ListObjectsV2 endpoint with real S3 prefix semantics, |
| -// for the PRODUCTION replica client (lease.ReadReplicaClient through |
| -// cachedReadReplica). The file replica the other tests use joins paths with |
| +// for the PRODUCTION replica client (lease.ResolveReplica through |
| +// cachedReadReplica), which reads head.json first and finds none. The file replica the other tests use joins paths with |
| // filepath.Join, which forgives a doubled slash that S3 does not; this is |
| // where the exact keys the box writes, and the exact prefixes the console |
| // lists, meet. |
| @@ -376,6 +376,13 @@ type fakeDataBucket struct { |
| func (b *fakeDataBucket) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| q := r.URL.Query() |
| + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/head.json") { |
| + // The replica resolver's one read: no host here has head.json. |
| + w.Header().Set("Content-Type", "application/xml") |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `<Error><Code>NoSuchKey</Code><Message>no such key</Message></Error>`) |
| + return |
| + } |
| if r.Method != http.MethodGet || q.Get("list-type") != "2" { |
| http.Error(w, "the leftover check only lists", http.StatusMethodNotAllowed) |
| return |
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go| index 6b0f352ef..a04585350 100644 |
| --- a/internal/console/hap2_wiring_test.go |
| +++ b/internal/console/hap2_wiring_test.go |
| @@ -430,17 +430,24 @@ func TestHAP2ProductionDoors(t *testing.T) { |
| if door == "begin" { |
| // The create door retains main's leftover rail before dispatch |
| // to import. The regional refusal adds no reads of its own. |
| + // Each prefix's replica is resolved first: one head.json |
| + // read (absent here: the root layout), then its levels. |
| var got, want []string |
| for _, a := range tr.all() { |
| if a.bucket != "data-test" { |
| continue |
| } |
| + if a.method == http.MethodGet && strings.HasSuffix(a.key, "/head.json") { |
| + got = append(got, "head "+a.key) |
| + continue |
| + } |
| if a.method != http.MethodGet || a.query.Get("list-type") != "2" { |
| t.Errorf("import begin data request: %+v", a) |
| } |
| got = append(got, a.query.Get("prefix")) |
| } |
| for _, prefix := range []string{"instances/", "moves/"} { |
| + want = append(want, "head "+prefix+importHost+"/head.json") |
| for level := 0; level < 10; level++ { |
| want = append(want, fmt.Sprintf("%s%s/%04x/", prefix, importHost, level)) |
| } |
| @@ -594,7 +601,7 @@ func TestHAP2RequestBudget(t *testing.T) { |
| } |
| } |
| } |
| - var got []string |
| + var got, heads []string |
| existence, dataGets, writes, beforeProof := 0, 0, 0, 0 |
| dataStarted := false |
| recordKey := provision.RecordKey("bab", "titogo", host) |
| @@ -614,6 +621,10 @@ func TestHAP2RequestBudget(t *testing.T) { |
| if a.bucket != "data-test" { |
| continue |
| } |
| + if a.method == "GET" && strings.HasSuffix(a.key, "/head.json") { |
| + heads = append(heads, a.key) // the replica resolver's one read per prefix |
| + continue |
| + } |
| if a.method != "GET" || a.query.Get("list-type") != "2" { |
| dataGets++ |
| continue |
| @@ -645,6 +656,16 @@ func TestHAP2RequestBudget(t *testing.T) { |
| if !reflect.DeepEqual(got, want) || dataGets != 0 { |
| t.Errorf("data HTTP attempts=%v + %d non-LIST; want %v", got, dataGets, want) |
| } |
| + var wantHeads []string |
| + if mode == "legacy" { |
| + wantHeads = append(wantHeads, "instances/"+host+"/head.json") |
| + } |
| + if levels > 0 { |
| + wantHeads = append(wantHeads, "moves/"+host+"/head.json") |
| + } |
| + if !reflect.DeepEqual(heads, wantHeads) { |
| + t.Errorf("head.json reads=%v, want one per resolved prefix %v", heads, wantHeads) |
| + } |
| // On refusal the reused existence read is exactly one; successful writes |
| // may reread the record under the existing writer's locks. |
| if proof && beforeProof != 1 { |
diff --git a/internal/console/server.go b/internal/console/server.go| index 48624b1e1..658a9f19d 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1230,7 +1230,7 @@ type Server struct { |
| boxCerts map[string]*x509.Certificate |
| // dbReplica opens the read side of one instance's replica for the |
| // `carlos db` door (apidb.go). NewServer points it at a small cache of |
| - // lease.ReadReplicaClient values; tests point it at a file replica. |
| + // lease.ResolveReplica clients; tests point it at a file replica. |
| dbReplica func(ctx context.Context, prefix string) (replicaReader, error) |
| // replicaHealth reads the hub's live copy table (replicaview.go). nil is |
| // the agent's private snapshot socket; tests set a fixed table. |
diff --git a/internal/dbdoor/plan_from.go b/internal/dbdoor/plan_from.go| index 92f1df000..88dfd6803 100644 |
| --- a/internal/dbdoor/plan_from.go |
| +++ b/internal/dbdoor/plan_from.go |
| @@ -15,8 +15,8 @@ import ( |
| ) |
| // ReplicaReader is the read half of a litestream replica client: the two |
| -// methods a door or a planner may hold. A *lss3.ReplicaClient from |
| -// lease.ReadReplicaClient is one; so is a file replica client. |
| +// methods a door or a planner may hold. The read-only client |
| +// lease.ResolveReplica binds is one; so is a file replica client. |
| type ReplicaReader interface { |
| LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) |
| OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) |
diff --git a/internal/dbreads/agent.go b/internal/dbreads/agent.go| index cb2345f8c..efbf01419 100644 |
| --- a/internal/dbreads/agent.go |
| +++ b/internal/dbreads/agent.go |
| @@ -16,7 +16,7 @@ import ( |
| mrand "math/rand/v2" |
| - "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -31,9 +31,12 @@ type AgentConfig struct { |
| Boot string // this agent process's id |
| Pub ed25519.PublicKey // CARLOS_RELEASE_PUBKEY |
| HibernatePrefix string // CARLOS_HIBERNATE_PREFIX |
| - // OpenReplica opens the read side of this box's own region bucket at a |
| - // prefix the agent derived (lease.ReadReplicaClient in production). |
| - OpenReplica func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) |
| + // OpenReplica resolves the replica of the instance at a prefix the |
| + // agent derived, in this box's own region bucket, as it was at at (zero |
| + // is the current one), and binds that one generation for the whole |
| + // attempt (lease.ResolveReplicaAt in production; spec 2026-11-12 §6.1, |
| + // §6.2). A time before every kept generation is lease.ErrBeforeHistory. |
| + OpenReplica func(ctx context.Context, prefix string, at time.Time) (lease.Resolved, error) |
| // DialWorker connects to carlos-dbread.socket. |
| DialWorker func(ctx context.Context) (net.Conn, error) |
| // Units counts carlos-dbread@ units active, activating or deactivating. |
diff --git a/internal/dbreads/dbreadstest/dbreadstest.go b/internal/dbreads/dbreadstest/dbreadstest.go| index 874714933..7c565e64c 100644 |
| --- a/internal/dbreads/dbreadstest/dbreadstest.go |
| +++ b/internal/dbreads/dbreadstest/dbreadstest.go |
| @@ -13,14 +13,21 @@ import ( |
| "crypto/sha256" |
| "encoding/hex" |
| "encoding/json" |
| + "io" |
| + "log/slog" |
| "net" |
| "sync/atomic" |
| "testing" |
| "time" |
| + "github.com/benbjohnson/litestream" |
| + "github.com/superfly/ltx" |
| + |
| "github.com/carlosframework/platform/internal/dbdoor" |
| "github.com/carlosframework/platform/internal/dbreads" |
| + "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| ) |
| type Options struct { |
| @@ -29,8 +36,10 @@ type Options struct { |
| Box string |
| Pub ed25519.PublicKey |
| HibernatePrefix string |
| - OpenReplica func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) |
| - MaxRestored int64 |
| + // OpenReplica opens a root-layout replica at prefix: the box reads it |
| + // as a resolution of the root generation, at any time. |
| + OpenReplica func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) |
| + MaxRestored int64 |
| // Worker's Scratch, Exit and Self are filled in when empty. |
| Worker dbreads.WorkerOptions |
| } |
| @@ -60,7 +69,7 @@ func Start(t testing.TB, o Options) *Box { |
| } |
| b.Agent = dbreads.NewAgent(dbreads.AgentConfig{ |
| Store: o.Store, Region: o.Region, Box: o.Box, Boot: "boot-" + o.Box, Pub: o.Pub, |
| - HibernatePrefix: o.HibernatePrefix, OpenReplica: o.OpenReplica, |
| + HibernatePrefix: o.HibernatePrefix, OpenReplica: rootResolver(o.OpenReplica), |
| DialWorker: b.dial, Units: b.units, |
| Free: func() (uint64, uint64, error) { return 100 << 30, 200 << 30, nil }, |
| MaxRestored: o.MaxRestored, Jitter: func() time.Duration { return 0 }, Logf: t.Logf, |
| @@ -157,3 +166,36 @@ func Answer(t testing.TB, store release.Store, id string, priv *ecdh.PrivateKey, |
| } |
| return out.Bytes(), s, r |
| } |
| + |
| +// rootResolver is open as the agent's resolver: every read binds the |
| +// root generation of the replica open returns. |
| +func rootResolver(open func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error)) func(context.Context, string, time.Time) (lease.Resolved, error) { |
| + if open == nil { |
| + return nil |
| + } |
| + return func(ctx context.Context, prefix string, _ time.Time) (lease.Resolved, error) { |
| + rd, err := open(ctx, prefix) |
| + if err != nil { |
| + return lease.Resolved{}, err |
| + } |
| + if c, ok := rd.(litestream.ReplicaClient); ok { |
| + return lease.Resolved{Generation: replicagen.Root, Client: c}, nil |
| + } |
| + return lease.Resolved{Generation: replicagen.Root, Client: readerClient{rd}}, nil |
| + } |
| +} |
| + |
| +// readerClient is a list-and-open reader as a full client; its writes |
| +// have no body. |
| +type readerClient struct{ dbdoor.ReplicaReader } |
| + |
| +func (readerClient) Type() string { return "dbreadstest" } |
| +func (readerClient) Init(context.Context) error { return nil } |
| +func (readerClient) SetLogger(*slog.Logger) {} |
| +func (readerClient) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) { |
| + return nil, lease.ErrReadOnlyReplica |
| +} |
| +func (readerClient) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { |
| + return lease.ErrReadOnlyReplica |
| +} |
| +func (readerClient) DeleteAll(context.Context) error { return lease.ErrReadOnlyReplica } |
diff --git a/internal/dbreads/fixture_test.go b/internal/dbreads/fixture_test.go| index 9f3bc3b6e..c2ec8ee2e 100644 |
| --- a/internal/dbreads/fixture_test.go |
| +++ b/internal/dbreads/fixture_test.go |
| @@ -20,8 +20,8 @@ import ( |
| lsfile "github.com/benbjohnson/litestream/file" |
| - "github.com/carlosframework/platform/internal/dbdoor" |
| "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -232,11 +232,11 @@ func (fx *fixture) agent(box string, mut ...func(*AgentConfig, *inProcWorkers)) |
| w := &inProcWorkers{t: fx.t} |
| cfg := AgentConfig{ |
| Store: fx.store, Region: "uk", Box: box, Boot: "boot-" + box, Pub: fx.rootPub, HibernatePrefix: "instances", |
| - OpenReplica: func(_ context.Context, prefix string) (dbdoor.ReplicaReader, error) { |
| + OpenReplica: func(_ context.Context, prefix string, _ time.Time) (lease.Resolved, error) { |
| if prefix != "instances/"+fxHost { |
| fx.t.Errorf("the agent asked for prefix %q", prefix) |
| } |
| - return lsfile.NewReplicaClient(fx.replica), nil |
| + return resolvedRoot(lsfile.NewReplicaClient(fx.replica)), nil |
| }, |
| Units: w.units, Free: plentyFree, Logf: fx.t.Logf, |
| Jitter: func() time.Duration { return 0 }, |
diff --git a/internal/dbreads/pull_test.go b/internal/dbreads/pull_test.go| index 421d05d1a..ea86b1d32 100644 |
| --- a/internal/dbreads/pull_test.go |
| +++ b/internal/dbreads/pull_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "github.com/carlosframework/platform/internal/dbdoor" |
| "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/lease" |
| ) |
| // sendPullPlan sends a pull header and the planned files; it returns the |
| @@ -241,7 +242,7 @@ func TestPullTooLargeAndNoChunkBeforeCheckB(t *testing.T) { |
| hook := &stageHook{ReplicaReader: lsfile.NewReplicaClient(fx2.replica), stage: "after the last byte", |
| lastSpan: dbdoor.Span(last.MinTXID, last.MaxTXID), change: func() { r := fx2.record(); r.Region = "ie"; fx2.putRecord(r) }} |
| b, w := fx2.agent("uk-1", func(c *AgentConfig, _ *inProcWorkers) { |
| - c.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return hook, nil } |
| + c.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) { return resolvedRoot(hook), nil } |
| }) |
| req2 := fx2.pullRequest("") |
| fx2.submit(req2) |
diff --git a/internal/dbreads/read.go b/internal/dbreads/read.go| index b3aafa8ce..a397358bb 100644 |
| --- a/internal/dbreads/read.go |
| +++ b/internal/dbreads/read.go |
| @@ -15,6 +15,7 @@ import ( |
| "github.com/carlosframework/platform/internal/activator" |
| "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/lease" |
| ) |
| // serve runs one read this agent owns, inside the owner's deadline, and |
| @@ -163,11 +164,20 @@ func (a *Agent) attempt(ctx context.Context, req Request, pub *ecdh.PublicKey, a |
| if code != "" { |
| return refuse(code) |
| } |
| - rd, err := a.cfg.OpenReplica(pctx, activator.HibernatePrefix(a.cfg.HibernatePrefix, rec.Host)) |
| - if err != nil { |
| + // One resolution per attempt: its plan and every download read the |
| + // generation it bound. A retry is a fresh attempt, and resolves again. |
| + res, err := a.cfg.OpenReplica(pctx, activator.HibernatePrefix(a.cfg.HibernatePrefix, rec.Host), at) |
| + var gone *lease.BeforeHistoryError |
| + switch { |
| + case errors.As(err, &gone): |
| + return failB(CodeHistoryGone, Summary{Oldest: gone.Oldest}) |
| + case errors.Is(err, lease.ErrBeforeHistory): |
| + return failB(CodeHistoryGone, Summary{}) |
| + case err != nil: |
| a.logf("dbreads: %s: open the replica: %v", req.ID, err) |
| return fail(CodeInterrupted, Summary{}) |
| } |
| + var rd dbdoor.ReplicaReader = res.Client |
| plan, err := dbdoor.PlanFrom(pctx, rd, at) |
| var before *dbdoor.BeforeHistoryError |
| switch { |
diff --git a/internal/dbreads/read_test.go b/internal/dbreads/read_test.go| index e6c7b8b60..c3820d535 100644 |
| --- a/internal/dbreads/read_test.go |
| +++ b/internal/dbreads/read_test.go |
| @@ -21,6 +21,7 @@ import ( |
| "github.com/superfly/ltx" |
| "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -82,7 +83,7 @@ func TestReadRePlansOnceThenSaysChangedTwice(t *testing.T) { |
| fx := newFixture(t, 2) |
| v := &vanishing{ReplicaReader: lsfile.NewReplicaClient(fx.replica), times: c.times} |
| a, _ := fx.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) { |
| - cfg.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return v, nil } |
| + cfg.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) { return resolvedRoot(v), nil } |
| }) |
| req := fx.request("SELECT count(*) FROM t", "") |
| _, _, r := serveOne(t, a, fx, req) |
| @@ -106,7 +107,7 @@ func TestRetryWaitsForTheFirstWorkerToStop(t *testing.T) { |
| fx := newFixture(t, 2) |
| v := &vanishing{ReplicaReader: lsfile.NewReplicaClient(fx.replica), times: 1} |
| a, w := fx.agent("uk-1", func(c *AgentConfig, w *inProcWorkers) { |
| - c.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return v, nil } |
| + c.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) { return resolvedRoot(v), nil } |
| c.Free = func() (uint64, uint64, error) { return 12 << 30, 20 << 30, nil } |
| w.linger = 300 * time.Millisecond |
| }) |
| @@ -215,7 +216,7 @@ func TestRecordChangeAtEveryStageWritesNoChunk(t *testing.T) { |
| hook := &stageHook{ReplicaReader: lsfile.NewReplicaClient(fx.replica), stage: stage, |
| lastSpan: dbdoor.Span(last.MinTXID, last.MaxTXID), change: func() { c.change(fx) }} |
| a, _ := fx.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) { |
| - cfg.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return hook, nil } |
| + cfg.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) { return resolvedRoot(hook), nil } |
| }) |
| req := fx.request("SELECT count(*) FROM t", "") |
| if stage == "before the pick" { |
| @@ -471,7 +472,7 @@ func TestReplicaDetailWaitsForCheckB(t *testing.T) { |
| rd = &vanishThenChange{ReplicaReader: &vanishing{ReplicaReader: lsfile.NewReplicaClient(fx.replica), times: c.vanish}, at: 2, change: func() { recreate(fx) }} |
| } |
| a, _ := fx.agent("uk-1", func(cfg *AgentConfig, w *inProcWorkers) { |
| - cfg.OpenReplica = func(context.Context, string) (dbdoor.ReplicaReader, error) { return rd, nil } |
| + cfg.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) { return resolvedRoot(rd), nil } |
| if c.mut != nil { |
| c.mut(cfg, w) |
| } |
diff --git a/internal/dbreads/resolve_test.go b/internal/dbreads/resolve_test.go| new file mode 100644 |
| index 000000000..025c8eba2 |
| --- /dev/null |
| +++ b/internal/dbreads/resolve_test.go |
| @@ -0,0 +1,81 @@ |
| +package dbreads |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "log/slog" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +// readerClient makes a test's list-and-open reader a full client for a |
| +// lease.Resolved; its writes have no body. |
| +type readerClient struct{ dbdoor.ReplicaReader } |
| + |
| +func (readerClient) Type() string { return "dbreads-test" } |
| +func (readerClient) Init(context.Context) error { return nil } |
| +func (readerClient) SetLogger(*slog.Logger) {} |
| +func (readerClient) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) { |
| + return nil, lease.ErrReadOnlyReplica |
| +} |
| +func (readerClient) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { |
| + return lease.ErrReadOnlyReplica |
| +} |
| +func (readerClient) DeleteAll(context.Context) error { return lease.ErrReadOnlyReplica } |
| + |
| +// resolvedRoot is a root-layout resolution over rd. |
| +func resolvedRoot(rd dbdoor.ReplicaReader) lease.Resolved { |
| + if c, ok := rd.(litestream.ReplicaClient); ok { |
| + return lease.Resolved{Generation: replicagen.Root, Client: c} |
| + } |
| + return lease.Resolved{Generation: replicagen.Root, Client: readerClient{rd}} |
| +} |
| + |
| +// Spec §6.2: the read resolves the generation at the request's own time, |
| +// and a time before every generation the replica keeps is the reader's |
| +// history-gone ending, naming the oldest point. |
| +func TestDBReadsAtResolvesHistory(t *testing.T) { |
| + t.Parallel() |
| + fx := newFixture(t, 2) |
| + at := time.Now().Add(time.Hour).UTC().Truncate(time.Second) |
| + var mu sync.Mutex |
| + var asked []time.Time |
| + a, _ := fx.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) { |
| + cfg.OpenReplica = func(_ context.Context, prefix string, at time.Time) (lease.Resolved, error) { |
| + mu.Lock() |
| + asked = append(asked, at) |
| + mu.Unlock() |
| + return resolvedRoot(lsfile.NewReplicaClient(fx.replica)), nil |
| + } |
| + }) |
| + _, _, r := serveOne(t, a, fx, fx.request("SELECT count(*) AS n FROM t", at.Format(time.RFC3339))) |
| + if r.State != StateDone { |
| + t.Fatalf("result %+v", r) |
| + } |
| + mu.Lock() |
| + if len(asked) != 1 || !asked[0].Equal(at) { |
| + t.Fatalf("the opener was asked for %v, want the request's time %s once", asked, at) |
| + } |
| + mu.Unlock() |
| + |
| + oldest := time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC) |
| + fx2 := newFixture(t, 2) |
| + b, _ := fx2.agent("uk-1", func(cfg *AgentConfig, _ *inProcWorkers) { |
| + cfg.OpenReplica = func(context.Context, string, time.Time) (lease.Resolved, error) { |
| + return lease.Resolved{}, &lease.BeforeHistoryError{Oldest: oldest} |
| + } |
| + }) |
| + _, s, r := serveOne(t, b, fx2, fx2.request("SELECT 1", oldest.Add(-time.Hour).Format(time.RFC3339))) |
| + if r.State != StateFailed || r.Code != CodeHistoryGone || !s.Oldest.Equal(oldest) { |
| + t.Fatalf("before history: result %+v summary %+v, want history-gone naming %s", r, s, oldest) |
| + } |
| +} |
diff --git a/internal/host/dbreads.go b/internal/host/dbreads.go| index e9ee113ca..4068fc1c5 100644 |
| --- a/internal/host/dbreads.go |
| +++ b/internal/host/dbreads.go |
| @@ -11,9 +11,9 @@ import ( |
| "strconv" |
| "strings" |
| "sync/atomic" |
| + "time" |
| "github.com/carlosframework/platform/internal/activator" |
| - "github.com/carlosframework/platform/internal/dbdoor" |
| "github.com/carlosframework/platform/internal/dbreads" |
| "github.com/carlosframework/platform/internal/hostwrite" |
| "github.com/carlosframework/platform/internal/lease" |
| @@ -151,8 +151,8 @@ func armDBReads(hib activator.Config) { |
| a := dbreads.NewAgent(dbreads.AgentConfig{ |
| Store: store, Region: env.region, Box: BoxLabel(), Boot: newBootID(), Pub: env.pub, |
| HibernatePrefix: hib.Prefix, |
| - OpenReplica: func(ctx context.Context, prefix string) (dbdoor.ReplicaReader, error) { |
| - return lease.ReadReplicaClient(ctx, hib.Bucket, prefix, hib.Region) |
| + OpenReplica: func(ctx context.Context, prefix string, at time.Time) (lease.Resolved, error) { |
| + return lease.ResolveReplicaAt(ctx, hib.Bucket, prefix, hib.Region, at) |
| }, |
| DialWorker: dialDBReadWorker, Units: dbReadUnits, Free: varTmpFree, |
| MaxRestored: env.maxRestored, MaxPull: env.maxPull, Logf: log.Printf, Draining: dbReadsDraining.Load, |
diff --git a/internal/host/dbreads_rootrunner_linux_test.go b/internal/host/dbreads_rootrunner_linux_test.go| index f6dd18cc5..1f7d2a11c 100644 |
| --- a/internal/host/dbreads_rootrunner_linux_test.go |
| +++ b/internal/host/dbreads_rootrunner_linux_test.go |
| @@ -33,8 +33,10 @@ import ( |
| "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| "github.com/carlosframework/platform/internal/dbreads" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| + "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| ) |
| const ( |
| @@ -623,8 +625,8 @@ func TestRootDBReadPayload(t *testing.T) { |
| a := dbreads.NewAgent(dbreads.AgentConfig{ |
| Store: store, Region: "uk", Box: "runner", Boot: newBootID(), Pub: ed25519.PublicKey(pubRaw), |
| HibernatePrefix: "instances", |
| - OpenReplica: func(_ context.Context, prefix string) (dbdoor.ReplicaReader, error) { |
| - return lsfile.NewReplicaClient(filepath.Join(dir, "replica", prefix)), nil |
| + OpenReplica: func(_ context.Context, prefix string, _ time.Time) (lease.Resolved, error) { |
| + return lease.Resolved{Generation: replicagen.Root, Client: lsfile.NewReplicaClient(filepath.Join(dir, "replica", prefix))}, nil |
| }, |
| DialWorker: dialDBReadWorker, Units: dbReadUnits, Free: varTmpFree, Logf: t.Logf, |
| }) |
diff --git a/internal/lease/check.go b/internal/lease/check.go| index 4d9ca8bb1..46c6205bb 100644 |
| --- a/internal/lease/check.go |
| +++ b/internal/lease/check.go |
| @@ -31,14 +31,15 @@ var restoreForVerify = func(ctx context.Context, out, bucket, prefix, region str |
| // verifyReplicaClient is the replica client a verify restore reads, behind |
| // a package var so tests can hand it a litestream file replica and still |
| -// run the real pinned restore, check and sweep. Built as Restore builds its |
| -// own: the same region resolution, the same endpoint override. |
| +// run the real pinned restore, check and sweep. Resolved as Restore |
| +// resolves its own (ResolveReplica): the generation head.json names, or |
| +// the root when there is none. |
| var verifyReplicaClient = func(ctx context.Context, bucket, prefix, region string) (litestream.ReplicaClient, error) { |
| - region, err := resolveRegion(ctx, region) |
| + r, err := ResolveReplica(ctx, bucket, prefix, region) |
| if err != nil { |
| return nil, err |
| } |
| - return newReplicaClient(bucket, prefix, region) |
| + return r.Client, nil |
| } |
| // restoreRecorded is restoreFrom for a verify restore, which must tell the |
| @@ -216,7 +217,9 @@ func VerifyReplica(ctx context.Context, bucket, prefix, region, dir string) (uin |
| return VerifyReplicaAt(ctx, bucket, prefix, region, dir, 0) |
| } |
| -// VerifyReplicaAt restores s3://bucket/prefix exactly through transaction |
| +// VerifyReplicaAt restores the replica of the host at s3://bucket/prefix |
| +// (the generation its head.json names, or the root without one: |
| +// ResolveReplica) exactly through transaction |
| // txid (zero is the newest copy) into a throwaway file under dir and proves |
| // it opens clean, then deletes it. Pinning is what lets a drill that planned |
| // a restore record the position it actually tested. With no target it |
| @@ -398,20 +401,23 @@ func ChangeCounter(path string) (uint32, error) { |
| return binary.BigEndian.Uint32(header[24:28]), nil |
| } |
| -// HasReplica reports whether s3://bucket/prefix holds any LTX file at any |
| -// level: the seed fallback's "has this host a replica of its own" (seeded |
| -// instances spec §3.4 step 1). A listing error is returned, never read as |
| -// "no replica". |
| +// HasReplica reports whether the host at s3://bucket/prefix has a replica |
| +// of its own: the seed fallback's question (seeded instances spec §3.4 |
| +// step 1). A host with head.json has one, whatever its current generation |
| +// holds (spec 2026-11-12 §6.1): an empty first generation is a host that |
| +// has started, and an empty later one is a fault to report, never a host |
| +// to seed over. Without head.json, the root layout decides: any LTX file |
| +// at any level. A head or listing error is returned, never read as "no |
| +// replica". |
| func HasReplica(ctx context.Context, bucket, prefix, region string) (bool, error) { |
| - region, err := resolveRegion(ctx, region) |
| + r, err := ResolveReplica(ctx, bucket, prefix, region) |
| if err != nil { |
| return false, err |
| } |
| - client, err := newReplicaClient(bucket, prefix, region) |
| - if err != nil { |
| - return false, err |
| + if r.HeadFound { |
| + return true, nil |
| } |
| - return hasReplicaIn(ctx, client) |
| + return hasReplicaIn(ctx, r.Client) |
| } |
| // ltxLister is the one replica-client method HasReplica needs. |
diff --git a/internal/lease/endpoint.go b/internal/lease/endpoint.go| index 25e624713..b23a530eb 100644 |
| --- a/internal/lease/endpoint.go |
| +++ b/internal/lease/endpoint.go |
| @@ -151,25 +151,6 @@ func newReplicaClientForUID(bucket, prefix, region string, euid int, offcloud fu |
| return c, nil |
| } |
| -// ReadReplicaClient is newReplicaClient for READERS outside this package — |
| -// the console's db door (spec 2026-09-02 §6). Identical construction on |
| -// purpose, region resolution included (Restore's resolveRegion): a second |
| -// hand-rolled client is how the endpoint override, the path-style flag and |
| -// the signing region drift apart between the writer and the reader of the |
| -// same bucket. |
| -// |
| -// It returns the same type the writer uses, so nothing here can enforce |
| -// read-only by construction; that guarantee lives in internal/dbdoor's |
| -// client, which has no write methods at all, and in the door only ever |
| -// calling LTXFiles and OpenLTXFile on what this returns. |
| -func ReadReplicaClient(ctx context.Context, bucket, prefix, region string) (*lss3.ReplicaClient, error) { |
| - region, err := resolveRegion(ctx, region) |
| - if err != nil { |
| - return nil, err |
| - } |
| - return newReplicaClient(bucket, prefix, region) |
| -} |
| - |
| // NewFilesStore is the hibernate bucket as a release.Store for a host's |
| // published files (<hibernate prefix>/files/0/): the one builder every |
| // files reader and writer uses, so the files sit beside lock.json and the |
diff --git a/internal/lease/endpoint_test.go b/internal/lease/endpoint_test.go| index 294dad169..a91ec6147 100644 |
| --- a/internal/lease/endpoint_test.go |
| +++ b/internal/lease/endpoint_test.go |
| @@ -288,10 +288,18 @@ func TestRestoreCreatesTheOutputPathsParentDirectory(t *testing.T) { |
| fakeCreds(t) |
| // Every listing this exercises, the v0.3.x/LTX format comparison and |
| // the LTX restore plan itself, is a ListObjectsV2 call; answering all |
| - // of them with an empty bucket makes Restore take the "no replica" |
| - // path, the one every fresh nested row actually takes on its first wake. |
| + // of them with an empty bucket (and the resolver's head.json read as |
| + // absent) makes Restore take the "no replica" path, the one every fresh |
| + // nested row actually takes on its first wake. |
| srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| w.Header().Set("Content-Type", "application/xml") |
| + if strings.TrimPrefix(r.URL.Path, "/test-bucket/") != "" && r.URL.Path != "/test-bucket" { |
| + // An object read: the resolver's head.json, which this |
| + // host has never had. |
| + w.WriteHeader(http.StatusNotFound) |
| + fmt.Fprint(w, `<Error><Code>NoSuchKey</Code><Message>no such key</Message></Error>`) |
| + return |
| + } |
| fmt.Fprint(w, `<?xml version="1.0" encoding="UTF-8"?> |
| <ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>b</Name><KeyCount>0</KeyCount><IsTruncated>false</IsTruncated></ListBucketResult>`) |
| })) |
| @@ -316,17 +324,32 @@ func TestRestoreCreatesTheOutputPathsParentDirectory(t *testing.T) { |
| } |
| } |
| -// ReadReplicaClient is the db door's reader (spec 2026-09-02 §6). It must |
| +// boundS3 is the litestream S3 client under a resolved root binding. |
| +func boundS3(t *testing.T, r Resolved) *lss3.ReplicaClient { |
| + t.Helper() |
| + ro, ok := r.Client.(readOnlyReplicaV3) |
| + if !ok { |
| + t.Fatalf("client %T, want the root's read-only client", r.Client) |
| + } |
| + c, ok := ro.v3.(*lss3.ReplicaClient) |
| + if !ok { |
| + t.Fatalf("inner client %T", ro.v3) |
| + } |
| + return c |
| +} |
| + |
| +// A resolved replica is the db door's reader (spec 2026-09-02 §6). It must |
| // carry the coordinates it was given and sign for the region lease.Restore |
| // would: an explicit region wins, and an empty one falls to the same chain |
| // resolution the writer uses — the endpoint override's non-AWS default when |
| -// nothing else answers. |
| -func TestReadReplicaClientCarriesBucketPrefixRegion(t *testing.T) { |
| +// nothing else answers. BindReplica builds it without a head read. |
| +func TestBindReplicaCarriesBucketPrefixRegion(t *testing.T) { |
| fakeCreds(t) |
| - c, err := ReadReplicaClient(context.Background(), "data-bucket", "instances/a.example.com", "eu-west-1") |
| + r, err := BindReplica(context.Background(), "data-bucket", "instances/a.example.com", "eu-west-1", "@root") |
| if err != nil { |
| t.Fatal(err) |
| } |
| + c := boundS3(t, r) |
| if c.Bucket != "data-bucket" { |
| t.Errorf("Bucket = %q, want data-bucket", c.Bucket) |
| } |
| @@ -336,15 +359,28 @@ func TestReadReplicaClientCarriesBucketPrefixRegion(t *testing.T) { |
| if c.Region != "eu-west-1" { |
| t.Errorf("Region = %q, want eu-west-1", c.Region) |
| } |
| + g, err := BindReplica(context.Background(), "data-bucket", "instances/a.example.com", "eu-west-1", "g-00000000000000000042") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ro, ok := g.Client.(readOnlyReplica) // a generation never reads v0.3 backups |
| + if !ok { |
| + t.Fatalf("generation client %T, want the read-only client without v0.3", g.Client) |
| + } |
| + gc, ok := ro.c.(*lss3.ReplicaClient) |
| + if !ok || gc.Path != "instances/a.example.com/g-00000000000000000042" { |
| + t.Errorf("generation client %#v, want Path instances/a.example.com/g-00000000000000000042", g.Client) |
| + } |
| } |
| -func TestReadReplicaClientResolvesAnEmptyRegionLikeRestore(t *testing.T) { |
| +func TestBindReplicaResolvesAnEmptyRegionLikeRestore(t *testing.T) { |
| fakeCreds(t) |
| t.Setenv("CARLOS_S3_ENDPOINT", "http://127.0.0.1:1") |
| - c, err := ReadReplicaClient(context.Background(), "data-bucket", "instances/a.example.com", "") |
| + r, err := BindReplica(context.Background(), "data-bucket", "instances/a.example.com", "", "@root") |
| if err != nil { |
| t.Fatal(err) |
| } |
| + c := boundS3(t, r) |
| if c.Region != lss3.DefaultRegion { |
| t.Errorf("Region = %q, want litestream's non-AWS default %q (the writer's resolution)", c.Region, lss3.DefaultRegion) |
| } |
diff --git a/internal/lease/lease.go b/internal/lease/lease.go| index 71a0d0705..c6c111841 100644 |
| --- a/internal/lease/lease.go |
| +++ b/internal/lease/lease.go |
| @@ -981,20 +981,18 @@ func SetShutdownSyncTimeoutForTest(d time.Duration) (restore func()) { |
| // Restore pulls the newest replicated state of s3://bucket/prefix into |
| // dbPath via litestream's restore API — the cold-wake path when the local DB |
| -// is missing. Returns restored=false with a nil error when the prefix holds |
| -// no backup at all (a brand-new instance that has never replicated boots |
| -// fresh instead). The caller must hold the prefix's lease: restoring outside |
| -// it could resurrect a stale copy that later shadows the true holder's newer |
| -// state. |
| +// is missing. prefix is the instance's location: the replica is the |
| +// generation its head.json names, or the root layout when it has none |
| +// (ResolveReplica, spec 2026-11-12 §6.1). Returns restored=false with a |
| +// nil error when that replica holds no backup at all (a brand-new instance |
| +// that has never replicated boots fresh instead). The caller must hold the |
| +// prefix's lease: restoring outside it could resurrect a stale copy that |
| +// later shadows the true holder's newer state. |
| func Restore(ctx context.Context, dbPath, bucket, prefix, region string) (bool, error) { |
| - // Resolved the same way the leaser's client resolves it — a restore that |
| - // signed for a different region than the lease guarding it would be a |
| - // silent split against a store that checks. |
| - region, err := resolveRegion(ctx, region) |
| - if err != nil { |
| - return false, err |
| - } |
| - client, err := newReplicaClient(bucket, prefix, region) |
| + // The resolver signs for the region the leaser's client resolves — a |
| + // restore that signed for a different region than the lease guarding it |
| + // would be a silent split against a store that checks. |
| + r, err := ResolveReplica(ctx, bucket, prefix, region) |
| if err != nil { |
| return false, err |
| } |
| @@ -1008,5 +1006,5 @@ func Restore(ctx context.Context, dbPath, bucket, prefix, region string) (bool, |
| return false, fmt.Errorf("create %s: %w", filepath.Dir(dbPath), err) |
| } |
| - return restoreFrom(ctx, client, dbPath, 0) |
| + return restoreFrom(ctx, r.Client, dbPath, 0) |
| } |
diff --git a/internal/lease/leasetest/filereplica.go b/internal/lease/leasetest/filereplica.go| new file mode 100644 |
| index 000000000..5b5349082 |
| --- /dev/null |
| +++ b/internal/lease/leasetest/filereplica.go |
| @@ -0,0 +1,48 @@ |
| +package leasetest |
| + |
| +import ( |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + |
| + "github.com/superfly/ltx" |
| +) |
| + |
| +// PutFileReplica copies a litestream file replica (dir/ltx/<level>/<file>, |
| +// the layout litestream's file client writes) into bucket under prefix, in |
| +// the layout litestream's S3 client reads: prefix<level as %04x>/<file>. |
| +// prefix is slash-terminated, as replicagen.Prefix returns it. It returns |
| +// the keys it wrote, sorted. |
| +func (f *VersionedBucket) PutFileReplica(bucket, prefix, dir string) ([]string, error) { |
| + levels, err := os.ReadDir(filepath.Join(dir, "ltx")) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var keys []string |
| + for _, lv := range levels { |
| + level, err := strconv.Atoi(lv.Name()) |
| + if err != nil || !lv.IsDir() { |
| + continue |
| + } |
| + files, err := os.ReadDir(filepath.Join(dir, "ltx", lv.Name())) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, e := range files { |
| + if _, _, err := ltx.ParseFilename(e.Name()); err != nil { |
| + continue |
| + } |
| + body, err := os.ReadFile(filepath.Join(dir, "ltx", lv.Name(), e.Name())) |
| + if err != nil { |
| + return nil, err |
| + } |
| + key := fmt.Sprintf("%s%04x/%s", prefix, level, e.Name()) |
| + f.Put(bucket, key, body) |
| + keys = append(keys, key) |
| + } |
| + } |
| + sort.Strings(keys) |
| + return keys, nil |
| +} |
diff --git a/internal/lease/readers_guard_test.go b/internal/lease/readers_guard_test.go| new file mode 100644 |
| index 000000000..40384883a |
| --- /dev/null |
| +++ b/internal/lease/readers_guard_test.go |
| @@ -0,0 +1,307 @@ |
| +package lease_test |
| + |
| +import ( |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "io/fs" |
| + "os" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +// G4 (spec 2026-11-12 region HA storage generations, §2 and §6.1): every |
| +// reader finds a replica through head.json, by one function, and binds the |
| +// generation it resolved. Once a host has head.json its replica is under |
| +// <loc>/g-<N>/, so a Litestream client built at <loc> directly reads the |
| +// root, a frozen predecessor. This guard parses the module's non-test Go |
| +// source and refuses every way of building such a client outside the |
| +// lease package's own builders. |
| + |
| +const ( |
| + lsS3Path = "github.com/benbjohnson/litestream/s3" |
| + lsPath = "github.com/benbjohnson/litestream" |
| + leasePath = "github.com/carlosframework/platform/internal/lease" |
| + leaseDir = "internal/lease" |
| + endpointGo = "internal/lease/endpoint.go" |
| + builderFunc = "newReplicaClient" |
| +) |
| + |
| +// guardAllowedFiles may call newReplicaClient anywhere: the resolver, and |
| +// the take that starts a generation. |
| +var guardAllowedFiles = map[string]bool{ |
| + "internal/lease/resolve.go": true, |
| + "internal/lease/gentake.go": true, |
| +} |
| + |
| +// guardAllowedFuncs are the writer's builders: the held lease's store and |
| +// its two bindings. |
| +var guardAllowedFuncs = map[string]bool{ |
| + "Held.newStore": true, |
| + "Held.BindGeneration": true, |
| + "Held.BindRoot": true, |
| +} |
| + |
| +// readerGuardFindings reports every prohibited construction in f, whose |
| +// module-relative path is rel. |
| +func readerGuardFindings(fset *token.FileSet, f *ast.File, rel string) []string { |
| + var out []string |
| + report := func(n ast.Node, what string) { |
| + out = append(out, fset.Position(n.Pos()).String()+": "+what) |
| + } |
| + s3Names, lsNames, leaseNames := map[string]bool{}, map[string]bool{}, map[string]bool{} |
| + for _, imp := range f.Imports { |
| + p, err := strconv.Unquote(imp.Path.Value) |
| + if err != nil { |
| + continue |
| + } |
| + var name string |
| + if imp.Name != nil { |
| + name = imp.Name.Name |
| + } |
| + switch p { |
| + case lsS3Path: |
| + if name == "." { |
| + report(imp, "dot import of litestream/s3") |
| + continue |
| + } |
| + if name == "" { |
| + name = "s3" |
| + } |
| + s3Names[name] = true |
| + case lsPath: |
| + if name == "." { |
| + report(imp, "dot import of litestream") |
| + continue |
| + } |
| + if name == "" { |
| + name = "litestream" |
| + } |
| + lsNames[name] = true |
| + case leasePath: |
| + if name == "." { |
| + report(imp, "dot import of lease") |
| + continue |
| + } |
| + if name == "" { |
| + name = "lease" |
| + } |
| + leaseNames[name] = true |
| + } |
| + } |
| + inLease := filepath.ToSlash(filepath.Dir(rel)) == leaseDir && f.Name.Name == "lease" |
| + |
| + // sel reports whether n is pkg.name for one of names. |
| + sel := func(n ast.Node, names map[string]bool, name string) bool { |
| + s, ok := n.(*ast.SelectorExpr) |
| + if !ok || s.Sel.Name != name { |
| + return false |
| + } |
| + id, ok := s.X.(*ast.Ident) |
| + return ok && names[id.Name] |
| + } |
| + isReplicaClientType := func(n ast.Expr) bool { |
| + if st, ok := n.(*ast.StarExpr); ok { |
| + n = st.X |
| + } |
| + return sel(n, s3Names, "ReplicaClient") |
| + } |
| + |
| + check := func(scope string, root ast.Node) { |
| + ast.Inspect(root, func(n ast.Node) bool { |
| + switch n := n.(type) { |
| + case *ast.SelectorExpr: |
| + switch { |
| + case sel(n, s3Names, "NewReplicaClient") && rel != endpointGo: |
| + report(n, "litestream/s3 NewReplicaClient outside "+endpointGo) |
| + case sel(n, s3Names, "NewReplicaClientFromURL"): |
| + report(n, "litestream/s3 NewReplicaClientFromURL") |
| + case sel(n, lsNames, "NewReplicaClientFromURL"): |
| + report(n, "litestream NewReplicaClientFromURL") |
| + case sel(n, leaseNames, "ReadReplicaClient"): |
| + report(n, "lease.ReadReplicaClient") |
| + } |
| + case *ast.CompositeLit: |
| + if n.Type != nil && isReplicaClientType(n.Type) { |
| + report(n, "a litestream/s3 ReplicaClient literal") |
| + } |
| + case *ast.CallExpr: |
| + if id, ok := n.Fun.(*ast.Ident); ok && id.Name == "new" && len(n.Args) == 1 && isReplicaClientType(n.Args[0]) { |
| + report(n, "new(litestream/s3 ReplicaClient)") |
| + } |
| + case *ast.Ident: |
| + if !inLease || guardAllowedFiles[rel] { |
| + return true |
| + } |
| + switch n.Name { |
| + case builderFunc: |
| + if !guardAllowedFuncs[scope] { |
| + report(n, builderFunc+" in "+scope) |
| + } |
| + case builderFunc + "ForUID": |
| + if scope != "endpoint.newReplicaClient" { |
| + report(n, builderFunc+"ForUID in "+scope) |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + } |
| + |
| + base := strings.TrimSuffix(filepath.Base(rel), ".go") |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok { |
| + // A package-level declaration: its scope is the name it |
| + // declares (a var holding a func literal is a reader too). |
| + gd, _ := d.(*ast.GenDecl) |
| + if gd == nil { |
| + continue |
| + } |
| + for _, spec := range gd.Specs { |
| + scope := base + ".<package scope>" |
| + if vs, ok := spec.(*ast.ValueSpec); ok && len(vs.Names) > 0 { |
| + scope = vs.Names[0].Name |
| + } |
| + check(scope, spec) |
| + } |
| + continue |
| + } |
| + scope := fd.Name.Name |
| + if fd.Recv != nil && len(fd.Recv.List) == 1 { |
| + t := fd.Recv.List[0].Type |
| + if st, ok := t.(*ast.StarExpr); ok { |
| + t = st.X |
| + } |
| + if id, ok := t.(*ast.Ident); ok { |
| + scope = id.Name + "." + scope |
| + } |
| + } else if rel == endpointGo { |
| + scope = "endpoint." + scope |
| + } |
| + // The declaration's own name is not a use. |
| + if fd.Recv != nil { |
| + check(scope, fd.Recv) |
| + } |
| + check(scope, fd.Type) |
| + if fd.Body != nil { |
| + check(scope, fd.Body) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// moduleRoot is the directory holding go.mod, two levels above this |
| +// package. |
| +func moduleRoot(t *testing.T) string { |
| + t.Helper() |
| + root, err := filepath.Abs(filepath.Join("..", "..")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Stat(filepath.Join(root, "go.mod")); err != nil { |
| + t.Fatalf("module root %s: %v", root, err) |
| + } |
| + return root |
| +} |
| + |
| +func TestNoReaderBuildsAClientAtTheLocation(t *testing.T) { |
| + root := moduleRoot(t) |
| + fset := token.NewFileSet() |
| + var findings []string |
| + parsed := 0 |
| + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { |
| + if err != nil { |
| + return err |
| + } |
| + name := d.Name() |
| + if d.IsDir() { |
| + if p == root { |
| + return nil |
| + } |
| + if name == "testdata" || name == "vendor" || name == "node_modules" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") { |
| + return filepath.SkipDir |
| + } |
| + if _, err := os.Stat(filepath.Join(p, "go.mod")); err == nil { |
| + return filepath.SkipDir // another module |
| + } |
| + return nil |
| + } |
| + if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { |
| + return nil |
| + } |
| + rel, err := filepath.Rel(root, p) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := parser.ParseFile(fset, p, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + return err |
| + } |
| + parsed++ |
| + findings = append(findings, readerGuardFindings(fset, f, filepath.ToSlash(rel))...) |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if parsed < 500 { |
| + t.Fatalf("parsed only %d files; the walk is not reaching the module", parsed) |
| + } |
| + if len(findings) > 0 { |
| + sort.Strings(findings) |
| + t.Fatalf("replica clients built outside the resolver (G4):\n%s", strings.Join(findings, "\n")) |
| + } |
| +} |
| + |
| +// The guard must catch each prohibited form: one fixture per form, never |
| +// compiled (testdata, .go.txt), each parsed as if it sat at the path the |
| +// table names. The allowed fixture must pass. |
| +func TestReaderGuardCatchesEachForm(t *testing.T) { |
| + cases := []struct { |
| + fixture, as string |
| + want []string // substrings, one per expected finding |
| + }{ |
| + {"alias_new_client.go.txt", "internal/console/x.go", []string{"NewReplicaClient outside"}}, |
| + {"default_name_literal.go.txt", "internal/host/x.go", []string{"ReplicaClient literal", "ReplicaClient literal"}}, |
| + {"new_builtin.go.txt", "internal/ops/x.go", []string{"new(litestream/s3 ReplicaClient)"}}, |
| + {"from_url.go.txt", "internal/dbreads/x.go", []string{"s3 NewReplicaClientFromURL", "litestream NewReplicaClientFromURL"}}, |
| + {"read_replica_client.go.txt", "internal/ops/x.go", []string{"lease.ReadReplicaClient", "lease.ReadReplicaClient"}}, |
| + {"dot_import.go.txt", "internal/host/x.go", []string{"dot import of litestream/s3"}}, |
| + {"lease_builder_call.go.txt", "internal/lease/check.go", []string{"newReplicaClient in HasReplica", "newReplicaClient in verifyReplicaClient", "newReplicaClientForUID in Restore"}}, |
| + {"lease_new_client.go.txt", "internal/lease/lease.go", []string{"NewReplicaClient outside"}}, |
| + {"allowed.go.txt", "internal/lease/claimgeneration.go", nil}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.fixture, func(t *testing.T) { |
| + src, err := os.ReadFile(filepath.Join("testdata", "readerguard", c.fixture)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fset := token.NewFileSet() |
| + f, err := parser.ParseFile(fset, c.fixture, src, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + got := readerGuardFindings(fset, f, c.as) |
| + if len(got) != len(c.want) { |
| + t.Fatalf("findings %q, want %d matching %q", got, len(c.want), c.want) |
| + } |
| + sort.Strings(got) |
| + used := make([]bool, len(got)) |
| + next: |
| + for _, w := range c.want { |
| + for i, g := range got { |
| + if !used[i] && strings.Contains(g, w) { |
| + used[i] = true |
| + continue next |
| + } |
| + } |
| + t.Fatalf("no finding matches %q in %q", w, got) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/lease/resolve.go b/internal/lease/resolve.go| new file mode 100644 |
| index 000000000..81453c072 |
| --- /dev/null |
| +++ b/internal/lease/resolve.go |
| @@ -0,0 +1,215 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +// The one resolver every replica reader goes through (spec 2026-11-12 |
| +// region HA storage generations, §6.1, invariant G4). It reads |
| +// `<loc>/head.json` once and binds the generation it names, so a read |
| +// lists, downloads and retries in that generation alone; with no head |
| +// the replica is the root layout, as before generations. A guard test |
| +// (readers_guard_test.go) holds every reader to it. |
| + |
| +// ErrReadOnlyReplica is every write a resolved replica client is asked |
| +// for: readers never write a replica. |
| +var ErrReadOnlyReplica = errors.New("lease: a resolved replica client is read-only") |
| + |
| +// ErrBeforeHistory is a point-in-time read older than every generation |
| +// head.json still keeps (spec §6.2). The error carrying it is a |
| +// *BeforeHistoryError. |
| +var ErrBeforeHistory = errors.New("lease: the time is before every generation the replica keeps") |
| + |
| +// BeforeHistoryError is ErrBeforeHistory with the earliest time a kept |
| +// generation covers. |
| +type BeforeHistoryError struct{ Oldest time.Time } |
| + |
| +func (e *BeforeHistoryError) Error() string { |
| + return fmt.Sprintf("%v (the oldest kept generation starts at %s)", ErrBeforeHistory, e.Oldest.UTC().Format(time.RFC3339)) |
| +} |
| + |
| +func (e *BeforeHistoryError) Is(target error) bool { return target == ErrBeforeHistory } |
| + |
| +// Resolved is one reader's binding: the generation it reads and a |
| +// read-only Litestream client confined to that generation's prefix. |
| +// Head is the head.json the resolution read, when HeadFound; a |
| +// BindReplica reads none. |
| +type Resolved struct { |
| + Generation string |
| + Client litestream.ReplicaClient |
| + Head Head |
| + HeadFound bool |
| +} |
| + |
| +// ResolveReplica binds the current generation of s3://bucket/loc: the one |
| +// head.json names, or the root when there is no head.json. loc carries |
| +// no trailing slash. One GET of head.json; a head that cannot be read or |
| +// does not decode is an error, never the root. |
| +func ResolveReplica(ctx context.Context, bucket, loc, region string) (Resolved, error) { |
| + return ResolveReplicaAt(ctx, bucket, loc, region, time.Time{}) |
| +} |
| + |
| +// ResolveReplicaAt binds the generation that was current at at (spec |
| +// §6.2): the current one when at is zero or at or after its |
| +// created_by.at; otherwise the history entry with created_at <= at < |
| +// ended_at. A time older than every kept generation is a |
| +// *BeforeHistoryError; a time no entry covers that is not older than |
| +// all of them (a gap in history) is refused as an error too. With no |
| +// head.json the root, whatever the time. |
| +func ResolveReplicaAt(ctx context.Context, bucket, loc, region string, at time.Time) (Resolved, error) { |
| + region, err := resolveRegion(ctx, region) |
| + if err != nil { |
| + return Resolved{}, err |
| + } |
| + st, err := NewFilesStore(ctx, bucket, region) |
| + if err != nil { |
| + return Resolved{}, err |
| + } |
| + h, _, found, err := ReadHead(ctx, st, loc) |
| + if err != nil { |
| + return Resolved{}, err |
| + } |
| + gen := replicagen.Root |
| + if found { |
| + if gen, err = generationAt(h, at); err != nil { |
| + return Resolved{}, fmt.Errorf("%s: %w", loc, err) |
| + } |
| + } |
| + client, err := readReplicaClient(bucket, loc, region, gen) |
| + if err != nil { |
| + return Resolved{}, err |
| + } |
| + return Resolved{Generation: gen, Client: client, Head: h, HeadFound: found}, nil |
| +} |
| + |
| +// BindReplica binds generation of s3://bucket/loc without reading |
| +// head.json: a reader whose flow spans requests carries the generation |
| +// it resolved and binds it again for each one. generation must be |
| +// replicagen.Valid (the root or a head.json name). |
| +func BindReplica(ctx context.Context, bucket, loc, region, generation string) (Resolved, error) { |
| + if !replicagen.Valid(generation) { |
| + return Resolved{}, fmt.Errorf("lease: bind %s: %q is not a generation name", loc, generation) |
| + } |
| + region, err := resolveRegion(ctx, region) |
| + if err != nil { |
| + return Resolved{}, err |
| + } |
| + client, err := readReplicaClient(bucket, loc, region, generation) |
| + if err != nil { |
| + return Resolved{}, err |
| + } |
| + return Resolved{Generation: generation, Client: client}, nil |
| +} |
| + |
| +// generationAt is §6.2's choice of generation for a read at at. |
| +func generationAt(h Head, at time.Time) (string, error) { |
| + if at.IsZero() || !at.Before(h.CreatedBy.At) { |
| + return h.Generation, nil |
| + } |
| + oldest := h.CreatedBy.At |
| + for _, e := range h.History { |
| + if !at.Before(e.CreatedAt) && at.Before(e.EndedAt) { |
| + return e.Generation, nil |
| + } |
| + if e.CreatedAt.Before(oldest) { |
| + oldest = e.CreatedAt |
| + } |
| + } |
| + if at.Before(oldest) { |
| + return "", &BeforeHistoryError{Oldest: oldest} |
| + } |
| + return "", fmt.Errorf("lease: head.json names no generation current at %s", at.UTC().Format(time.RFC3339Nano)) |
| +} |
| + |
| +// readReplicaClient is the read-only client for generation of loc, built |
| +// as the writer's is (newReplicaClient: endpoint override, path style, |
| +// the region already resolved). Its Path is replicagen.ClientPath, so |
| +// every listing and download stays under the generation's prefix. |
| +func readReplicaClient(bucket, loc, region, generation string) (litestream.ReplicaClient, error) { |
| + if loc == "" { |
| + return nil, errors.New("lease: a replica location is empty") |
| + } |
| + c, err := newReplicaClient(bucket, replicagen.ClientPath(loc, generation), region) |
| + if err != nil { |
| + return nil, err |
| + } |
| + ro := readOnlyReplica{c: c} |
| + // Only the root can hold Litestream v0.3 backups (<loc>/generations/): |
| + // a generation is a copy of LTX files. Keep the v0.3 restore path the |
| + // root layout has always had, and nothing more. |
| + if generation == replicagen.Root { |
| + return readOnlyReplicaV3{readOnlyReplica: ro, v3: c}, nil |
| + } |
| + return ro, nil |
| +} |
| + |
| +// readOnlyReplica forwards a replica client's reads and refuses its |
| +// writes. It does not implement litestream.ReplicaClientV3. |
| +type readOnlyReplica struct{ c litestream.ReplicaClient } |
| + |
| +func (r readOnlyReplica) Type() string { return r.c.Type() } |
| +func (r readOnlyReplica) Init(ctx context.Context) error { return r.c.Init(ctx) } |
| +func (r readOnlyReplica) SetLogger(l *slog.Logger) { r.c.SetLogger(l) } |
| + |
| +func (r readOnlyReplica) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) { |
| + return r.c.LTXFiles(ctx, level, seek, useMetadata) |
| +} |
| + |
| +func (r readOnlyReplica) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) { |
| + return r.c.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size) |
| +} |
| + |
| +func (r readOnlyReplica) WriteLTXFile(_ context.Context, _ int, _, _ ltx.TXID, rd io.Reader) (*ltx.FileInfo, error) { |
| + if pipe, ok := rd.(*io.PipeReader); ok { |
| + pipe.Close() // never leave a writer blocked on a refused upload |
| + } |
| + return nil, ErrReadOnlyReplica |
| +} |
| + |
| +func (r readOnlyReplica) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { |
| + return ErrReadOnlyReplica |
| +} |
| + |
| +func (r readOnlyReplica) DeleteAll(context.Context) error { return ErrReadOnlyReplica } |
| + |
| +// readOnlyReplicaV3 is readOnlyReplica for the root layout, which also |
| +// reads Litestream v0.3 backups: every v0.3 method is a read. |
| +type readOnlyReplicaV3 struct { |
| + readOnlyReplica |
| + v3 litestream.ReplicaClientV3 |
| +} |
| + |
| +func (r readOnlyReplicaV3) GenerationsV3(ctx context.Context) ([]string, error) { |
| + return r.v3.GenerationsV3(ctx) |
| +} |
| + |
| +func (r readOnlyReplicaV3) SnapshotsV3(ctx context.Context, generation string) ([]litestream.SnapshotInfoV3, error) { |
| + return r.v3.SnapshotsV3(ctx, generation) |
| +} |
| + |
| +func (r readOnlyReplicaV3) WALSegmentsV3(ctx context.Context, generation string) ([]litestream.WALSegmentInfoV3, error) { |
| + return r.v3.WALSegmentsV3(ctx, generation) |
| +} |
| + |
| +func (r readOnlyReplicaV3) OpenSnapshotV3(ctx context.Context, generation string, index int) (io.ReadCloser, error) { |
| + return r.v3.OpenSnapshotV3(ctx, generation, index) |
| +} |
| + |
| +func (r readOnlyReplicaV3) OpenWALSegmentV3(ctx context.Context, generation string, index int, offset int64) (io.ReadCloser, error) { |
| + return r.v3.OpenWALSegmentV3(ctx, generation, index, offset) |
| +} |
| + |
| +var ( |
| + _ litestream.ReplicaClient = readOnlyReplica{} |
| + _ litestream.ReplicaClientV3 = readOnlyReplicaV3{} |
| +) |
diff --git a/internal/lease/resolve_test.go b/internal/lease/resolve_test.go| new file mode 100644 |
| index 000000000..c9a6b55ff |
| --- /dev/null |
| +++ b/internal/lease/resolve_test.go |
| @@ -0,0 +1,406 @@ |
| +package lease_test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/benbjohnson/litestream" |
| + "github.com/superfly/ltx" |
| + |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +const ( |
| + rvBucket = "data" |
| + rvLoc = "instances/shop.example.com" |
| + rvRegion = "us-east-1" |
| +) |
| + |
| +// rvFixture is a data bucket behind leasetest's S3, reached the way |
| +// production reaches it (CARLOS_S3_ENDPOINT), with every request logged. |
| +type rvFixture struct { |
| + m *leasetest.VersionedBucket |
| + mu sync.Mutex |
| + reqs []string // "METHOD key" |
| +} |
| + |
| +func newRVFixture(t *testing.T) *rvFixture { |
| + t.Helper() |
| + fx := &rvFixture{m: leasetest.NewVersionedBucket()} |
| + fx.m.AddBucket(rvBucket) |
| + handler, _ := leasetest.NewS3Server(fx.m) |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + key := strings.TrimPrefix(strings.TrimPrefix(r.URL.Path, "/"+rvBucket), "/") |
| + if key == "" { |
| + key = "?prefix=" + r.URL.Query().Get("prefix") |
| + } |
| + fx.mu.Lock() |
| + fx.reqs = append(fx.reqs, r.Method+" "+key) |
| + fx.mu.Unlock() |
| + handler.ServeHTTP(w, r) |
| + })) |
| + t.Cleanup(srv.Close) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("CARLOS_S3_ENDPOINT", srv.URL) |
| + return fx |
| +} |
| + |
| +func (fx *rvFixture) requests() []string { |
| + fx.mu.Lock() |
| + defer fx.mu.Unlock() |
| + return append([]string(nil), fx.reqs...) |
| +} |
| + |
| +// replica writes a real litestream replica of batches*10 rows into gen. |
| +func (fx *rvFixture) replica(t *testing.T, loc, gen string, batches int) { |
| + t.Helper() |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, batches) |
| + if _, err := fx.m.PutFileReplica(rvBucket, replicagen.Prefix(loc, gen), dir); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// file writes one LTX key (a stand-in body: listing only) into gen. |
| +func (fx *rvFixture) file(loc, gen string, level int, min, max uint64) { |
| + key := fmt.Sprintf("%s%04x/%s", replicagen.Prefix(loc, gen), level, ltx.FormatFilename(ltx.TXID(min), ltx.TXID(max))) |
| + fx.m.Put(rvBucket, key, []byte("ltx "+key)) |
| +} |
| + |
| +func (fx *rvFixture) head(t *testing.T, loc string, h lease.Head) { |
| + t.Helper() |
| + if h.History == nil { |
| + h.History = []lease.HeadHistory{} |
| + } |
| + body, err := json.Marshal(h) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fx.m.Put(rvBucket, loc+"/head.json", body) |
| +} |
| + |
| +// listed is every LTX file c lists, as "L<level>[min..max]". |
| +func listed(t *testing.T, c litestream.ReplicaClient) []string { |
| + t.Helper() |
| + var out []string |
| + for level := 0; level <= litestream.SnapshotLevel; level++ { |
| + itr, err := c.LTXFiles(context.Background(), level, 0, false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for itr.Next() { |
| + f := itr.Item() |
| + out = append(out, fmt.Sprintf("L%d[%d..%d]", f.Level, f.MinTXID, f.MaxTXID)) |
| + } |
| + if err := itr.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func newestTXID(t *testing.T, c litestream.ReplicaClient) uint64 { |
| + t.Helper() |
| + p, err := dbdoor.PlanFrom(context.Background(), c, time.Time{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return p.TXID |
| +} |
| + |
| +func TestResolveReplicaNoHeadIsRoot(t *testing.T) { |
| + fx := newRVFixture(t) |
| + fx.replica(t, rvLoc, replicagen.Root, 2) |
| + fx.file(rvLoc, replicagen.Name(9), 0, 99, 99) // a stray generation no head names |
| + |
| + r, err := lease.ResolveReplica(context.Background(), rvBucket, rvLoc, rvRegion) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.Generation != replicagen.Root || r.HeadFound { |
| + t.Fatalf("resolved %q found=%v, want the root and no head", r.Generation, r.HeadFound) |
| + } |
| + got := listed(t, r.Client) |
| + if len(got) == 0 { |
| + t.Fatal("the root client lists nothing") |
| + } |
| + for _, f := range got { |
| + if strings.Contains(f, "[99..99]") { |
| + t.Fatalf("the root client listed a generation's file: %v", got) |
| + } |
| + } |
| +} |
| + |
| +func TestResolveReplicaFollowsHead(t *testing.T) { |
| + fx := newRVFixture(t) |
| + gen := replicagen.Name(42) |
| + fx.replica(t, rvLoc, replicagen.Root, 1) |
| + fx.replica(t, rvLoc, gen, 3) |
| + at := time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC) |
| + fx.head(t, rvLoc, lease.Head{V: 1, Generation: gen, StartTXID: 1, Predecessor: replicagen.Root, |
| + CreatedBy: lease.HeadCreator{LockGeneration: 42, Box: "box-a", At: at}}) |
| + |
| + ctx := context.Background() |
| + r, err := lease.ResolveReplica(ctx, rvBucket, rvLoc, rvRegion) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.Generation != gen || !r.HeadFound || r.Head.Generation != gen || !r.Head.CreatedBy.At.Equal(at) { |
| + t.Fatalf("resolved %q found=%v head=%+v, want %s from head.json", r.Generation, r.HeadFound, r.Head, gen) |
| + } |
| + root, err := lease.BindReplica(ctx, rvBucket, rvLoc, rvRegion, replicagen.Root) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The generation's replica has three batches, the root's one: the |
| + // resolved client plans the generation's newest position. |
| + if got, rootGot := newestTXID(t, r.Client), newestTXID(t, root.Client); got <= rootGot { |
| + t.Fatalf("resolved client ends at %d, the root at %d; want the generation's later position", got, rootGot) |
| + } |
| + |
| + // Exactly one head read per resolution, and only head.json and the |
| + // generation's own prefix are ever asked for. |
| + heads := 0 |
| + for _, req := range fx.requests() { |
| + if req == "GET "+rvLoc+"/head.json" { |
| + heads++ |
| + } |
| + } |
| + if heads != 1 { |
| + t.Fatalf("%d head.json reads for one resolution and one bind; requests %v", heads, fx.requests()) |
| + } |
| + |
| + // A head that does not decode is an error, never the root. |
| + fx.m.Put(rvBucket, rvLoc+"/head.json", []byte(`{"v":1,"generation":"g-42"}`)) |
| + if _, err := lease.ResolveReplica(ctx, rvBucket, rvLoc, rvRegion); err == nil { |
| + t.Fatal("an invalid head.json resolved") |
| + } |
| +} |
| + |
| +func TestBindReplicaReadsNoHeadAndRefusesBadNames(t *testing.T) { |
| + fx := newRVFixture(t) |
| + gen := replicagen.Name(7) |
| + fx.file(rvLoc, gen, 0, 5, 5) |
| + ctx := context.Background() |
| + r, err := lease.BindReplica(ctx, rvBucket, rvLoc, rvRegion, gen) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.Generation != gen || r.HeadFound { |
| + t.Fatalf("bound %q found=%v", r.Generation, r.HeadFound) |
| + } |
| + if got := listed(t, r.Client); len(got) != 1 || got[0] != "L0[5..5]" { |
| + t.Fatalf("bound client lists %v", got) |
| + } |
| + for _, req := range fx.requests() { |
| + if strings.HasSuffix(req, "head.json") { |
| + t.Fatalf("a bind read head.json: %v", fx.requests()) |
| + } |
| + } |
| + for _, bad := range []string{"", "g-7", "../x", "g-00000000000000000007/", "@root/"} { |
| + if _, err := lease.BindReplica(ctx, rvBucket, rvLoc, rvRegion, bad); err == nil { |
| + t.Errorf("BindReplica(%q) bound", bad) |
| + } |
| + } |
| +} |
| + |
| +func TestResolveReplicaIsReadOnly(t *testing.T) { |
| + fx := newRVFixture(t) |
| + gen := replicagen.Name(3) |
| + fx.file(rvLoc, gen, 0, 1, 1) |
| + fx.head(t, rvLoc, lease.Head{V: 1, Generation: gen}) |
| + ctx := context.Background() |
| + for name, resolve := range map[string]func() (lease.Resolved, error){ |
| + "generation": func() (lease.Resolved, error) { return lease.ResolveReplica(ctx, rvBucket, rvLoc, rvRegion) }, |
| + "root": func() (lease.Resolved, error) { |
| + return lease.BindReplica(ctx, rvBucket, rvLoc, rvRegion, replicagen.Root) |
| + }, |
| + } { |
| + r, err := resolve() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := r.Client.WriteLTXFile(ctx, 0, 2, 2, bytes.NewReader([]byte("x"))); !errors.Is(err, lease.ErrReadOnlyReplica) { |
| + t.Errorf("%s: WriteLTXFile = %v, want ErrReadOnlyReplica", name, err) |
| + } |
| + if err := r.Client.DeleteLTXFiles(ctx, []*ltx.FileInfo{{Level: 0, MinTXID: 1, MaxTXID: 1}}); !errors.Is(err, lease.ErrReadOnlyReplica) { |
| + t.Errorf("%s: DeleteLTXFiles = %v, want ErrReadOnlyReplica", name, err) |
| + } |
| + if err := r.Client.DeleteAll(ctx); !errors.Is(err, lease.ErrReadOnlyReplica) { |
| + t.Errorf("%s: DeleteAll = %v, want ErrReadOnlyReplica", name, err) |
| + } |
| + } |
| + for _, req := range fx.requests() { |
| + if !strings.HasPrefix(req, "GET ") { |
| + t.Fatalf("a read-only client sent %q", req) |
| + } |
| + } |
| +} |
| + |
| +// Spec §6.2: a time inside an earlier generation's tenure reads that |
| +// generation alone, a late file its holder wrote after the successor's |
| +// copy included; a time at or after the current generation's creation |
| +// reads the current one; a time before every kept generation is refused. |
| +func TestResolveReplicaAtAcrossABoundary(t *testing.T) { |
| + fx := newRVFixture(t) |
| + g1, g2 := replicagen.Name(1), replicagen.Name(2) |
| + t1 := time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC) |
| + t2 := time.Date(2026, 11, 11, 9, 0, 0, 0, time.UTC) |
| + fx.file(rvLoc, g1, 9, 1, 10) |
| + fx.file(rvLoc, g1, 0, 11, 11) |
| + fx.file(rvLoc, g2, 9, 1, 10) // g-2's copy ends at g-1's L0 TXID 11 |
| + fx.file(rvLoc, g2, 0, 11, 11) |
| + fx.file(rvLoc, g2, 0, 12, 12) |
| + fx.file(rvLoc, g1, 0, 12, 12) // g-1's holder, late, after g-2's copy |
| + fx.head(t, rvLoc, lease.Head{V: 1, Generation: g2, StartTXID: 11, Predecessor: g1, |
| + CreatedBy: lease.HeadCreator{LockGeneration: 2, At: t2}, |
| + History: []lease.HeadHistory{{Generation: g1, StartTXID: 0, CreatedAt: t1, EndedAt: t2}}}) |
| + ctx := context.Background() |
| + |
| + inG1, err := lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, t2.Add(-time.Minute)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if inG1.Generation != g1 || !inG1.HeadFound { |
| + t.Fatalf("at inside g-1's tenure resolved %q", inG1.Generation) |
| + } |
| + if got := strings.Join(listed(t, inG1.Client), " "); got != "L0[11..11] L0[12..12] L9[1..10]" { |
| + t.Fatalf("g-1 lists %s, want its own files and the late L0", got) |
| + } |
| + if r, err := lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, t1); err != nil || r.Generation != g1 { |
| + t.Fatalf("at g-1's creation resolved %q, %v", r.Generation, err) |
| + } |
| + for name, at := range map[string]time.Time{"at the switch": t2, "after it": t2.Add(time.Hour), "zero (current)": {}} { |
| + r, err := lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, at) |
| + if err != nil || r.Generation != g2 { |
| + t.Fatalf("%s: resolved %q, %v; want %s", name, r.Generation, err, g2) |
| + } |
| + if got := strings.Join(listed(t, r.Client), " "); got != "L0[11..11] L0[12..12] L9[1..10]" { |
| + t.Fatalf("%s: g-2 lists %s", name, got) |
| + } |
| + } |
| + _, err = lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, t1.Add(-time.Second)) |
| + var before *lease.BeforeHistoryError |
| + if !errors.Is(err, lease.ErrBeforeHistory) || !errors.As(err, &before) || !before.Oldest.Equal(t1) { |
| + t.Fatalf("before every generation = %v, want ErrBeforeHistory naming %s", err, t1) |
| + } |
| + |
| + // A gap between an entry's end and the current generation's creation |
| + // is refused, not guessed (and is not "before history"). |
| + fx.head(t, rvLoc, lease.Head{V: 1, Generation: g2, Predecessor: g1, |
| + CreatedBy: lease.HeadCreator{LockGeneration: 2, At: t2}, |
| + History: []lease.HeadHistory{{Generation: g1, CreatedAt: t1, EndedAt: t2.Add(-time.Hour)}}}) |
| + if _, err := lease.ResolveReplicaAt(ctx, rvBucket, rvLoc, rvRegion, t2.Add(-time.Minute)); err == nil || errors.Is(err, lease.ErrBeforeHistory) { |
| + t.Fatalf("a time in a gap = %v, want a refusal that is not ErrBeforeHistory", err) |
| + } |
| + |
| + // No head: the root, whatever the time. |
| + other := "instances/other.example.com" |
| + fx.file(other, replicagen.Root, 0, 1, 1) |
| + if r, err := lease.ResolveReplicaAt(ctx, rvBucket, other, rvRegion, t1); err != nil || r.Generation != replicagen.Root || r.HeadFound { |
| + t.Fatalf("no head at a time resolved %q found=%v, %v", r.Generation, r.HeadFound, err) |
| + } |
| +} |
| + |
| +// Seed placement (spec §6.1): a host with head.json has a replica, |
| +// whatever its generation holds; without one, the root decides. |
| +func TestHasReplicaSeesAGenerationsHost(t *testing.T) { |
| + fx := newRVFixture(t) |
| + ctx := context.Background() |
| + cases := []struct { |
| + name string |
| + set func(loc string) |
| + want bool |
| + }{ |
| + {"empty first generation", func(loc string) { |
| + fx.head(t, loc, lease.Head{V: 1, Generation: replicagen.Name(1)}) |
| + }, true}, |
| + {"unexpectedly empty later generation", func(loc string) { |
| + fx.head(t, loc, lease.Head{V: 1, Generation: replicagen.Name(5), StartTXID: 40, Predecessor: replicagen.Name(4)}) |
| + }, true}, |
| + {"generation with data, empty root", func(loc string) { |
| + fx.file(loc, replicagen.Name(6), 9, 1, 40) |
| + fx.head(t, loc, lease.Head{V: 1, Generation: replicagen.Name(6), StartTXID: 40, Predecessor: replicagen.Root}) |
| + }, true}, |
| + {"no head, empty root", func(string) {}, false}, |
| + {"no head, stray generation files only", func(loc string) { fx.file(loc, replicagen.Name(8), 0, 1, 1) }, false}, |
| + {"no head, root snapshot", func(loc string) { fx.file(loc, replicagen.Root, 9, 1, 7) }, true}, |
| + } |
| + for i, c := range cases { |
| + loc := fmt.Sprintf("instances/h%d.example.com", i) |
| + c.set(loc) |
| + got, err := lease.HasReplica(ctx, rvBucket, loc, rvRegion) |
| + if err != nil || got != c.want { |
| + t.Errorf("%s: HasReplica = %v, %v; want %v", c.name, got, err, c.want) |
| + } |
| + } |
| +} |
| + |
| +func rowCount(t *testing.T, path string) int { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", "file:"+path+"?mode=ro") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer db.Close() |
| + var n int |
| + if err := db.QueryRow("SELECT count(*) FROM t").Scan(&n); err != nil { |
| + t.Fatal(err) |
| + } |
| + return n |
| +} |
| + |
| +// The wake restore reads the generation head.json names; a host without |
| +// one restores from the root, as today. |
| +func TestRestoreFollowsHead(t *testing.T) { |
| + fx := newRVFixture(t) |
| + gen := replicagen.Name(42) |
| + fx.replica(t, rvLoc, replicagen.Root, 1) // 10 rows: the predecessor |
| + fx.replica(t, rvLoc, gen, 3) // 30 rows: the current generation |
| + fx.head(t, rvLoc, lease.Head{V: 1, Generation: gen, StartTXID: 1, Predecessor: replicagen.Root}) |
| + plain := "instances/plain.example.com" |
| + fx.replica(t, plain, replicagen.Root, 2) |
| + ctx := context.Background() |
| + |
| + out := filepath.Join(t.TempDir(), "ha", "shop.db") |
| + restored, err := lease.Restore(ctx, out, rvBucket, rvLoc, rvRegion) |
| + if err != nil || !restored { |
| + t.Fatalf("restore = %v, %v", restored, err) |
| + } |
| + if n := rowCount(t, out); n != 30 { |
| + t.Fatalf("restored %d rows, want the generation's 30", n) |
| + } |
| + out = filepath.Join(t.TempDir(), "plain", "plain.db") |
| + restored, err = lease.Restore(ctx, out, rvBucket, plain, rvRegion) |
| + if err != nil || !restored { |
| + t.Fatalf("root restore = %v, %v", restored, err) |
| + } |
| + if n := rowCount(t, out); n != 20 { |
| + t.Fatalf("root restore has %d rows, want 20", n) |
| + } |
| + for _, req := range fx.requests() { |
| + if !strings.HasPrefix(req, "GET ") { |
| + t.Fatalf("a restore sent %q", req) |
| + } |
| + } |
| +} |
diff --git a/internal/lease/testdata/readerguard/README.txt b/internal/lease/testdata/readerguard/README.txt| new file mode 100644 |
| index 000000000..13eeedb3d |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/README.txt |
| @@ -0,0 +1,4 @@ |
| +Negative fixtures for TestReaderGuardCatchesEachForm (readers_guard_test.go). |
| +Each .go.txt is one prohibited way of building a Litestream replica client |
| +at a location directly (spec 2026-11-12 G4); allowed.go.txt is the writer's |
| +permitted builders. They are .go.txt under testdata so they never compile. |
diff --git a/internal/lease/testdata/readerguard/alias_new_client.go.txt b/internal/lease/testdata/readerguard/alias_new_client.go.txt| new file mode 100644 |
| index 000000000..e1d691870 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/alias_new_client.go.txt |
| @@ -0,0 +1,9 @@ |
| +package console |
| + |
| +import ls "github.com/benbjohnson/litestream/s3" |
| + |
| +func reader(bucket, loc string) *ls.ReplicaClient { |
| + c := ls.NewReplicaClient() |
| + c.Bucket, c.Path = bucket, loc |
| + return c |
| +} |
diff --git a/internal/lease/testdata/readerguard/allowed.go.txt b/internal/lease/testdata/readerguard/allowed.go.txt| new file mode 100644 |
| index 000000000..75ff47b43 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/allowed.go.txt |
| @@ -0,0 +1,20 @@ |
| +package lease |
| + |
| +import lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| +func (h *Held) BindGeneration(prefix string) error { |
| + _, err := newReplicaClient(h.bucket, prefix, h.region) |
| + return err |
| +} |
| + |
| +func (h *Held) BindRoot() error { |
| + _, err := newReplicaClient(h.bucket, h.base, h.region) |
| + return err |
| +} |
| + |
| +func (h *Held) newStore() error { |
| + _, err := newReplicaClient(h.bucket, h.base, h.region) |
| + return err |
| +} |
| + |
| +func leaser() (*lss3.Leaser, *lss3.Leaser) { return lss3.NewLeaser(), &lss3.Leaser{} } |
diff --git a/internal/lease/testdata/readerguard/default_name_literal.go.txt b/internal/lease/testdata/readerguard/default_name_literal.go.txt| new file mode 100644 |
| index 000000000..d5bc40c71 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/default_name_literal.go.txt |
| @@ -0,0 +1,7 @@ |
| +package host |
| + |
| +import "github.com/benbjohnson/litestream/s3" |
| + |
| +func reader(bucket, loc string) (*s3.ReplicaClient, s3.ReplicaClient) { |
| + return &s3.ReplicaClient{Bucket: bucket, Path: loc}, s3.ReplicaClient{} |
| +} |
diff --git a/internal/lease/testdata/readerguard/dot_import.go.txt b/internal/lease/testdata/readerguard/dot_import.go.txt| new file mode 100644 |
| index 000000000..467738428 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/dot_import.go.txt |
| @@ -0,0 +1,5 @@ |
| +package host |
| + |
| +import . "github.com/benbjohnson/litestream/s3" |
| + |
| +func reader() *ReplicaClient { return NewReplicaClient() } |
diff --git a/internal/lease/testdata/readerguard/from_url.go.txt b/internal/lease/testdata/readerguard/from_url.go.txt| new file mode 100644 |
| index 000000000..61e36c1df |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/from_url.go.txt |
| @@ -0,0 +1,13 @@ |
| +package dbreads |
| + |
| +import ( |
| + "github.com/benbjohnson/litestream" |
| + lss3 "github.com/benbjohnson/litestream/s3" |
| +) |
| + |
| +func reader(loc string) (litestream.ReplicaClient, error) { |
| + if c, err := litestream.NewReplicaClientFromURL("s3://data/" + loc); err == nil { |
| + return c, nil |
| + } |
| + return lss3.NewReplicaClientFromURL("s3", "data", "/"+loc, nil, nil) |
| +} |
diff --git a/internal/lease/testdata/readerguard/lease_builder_call.go.txt b/internal/lease/testdata/readerguard/lease_builder_call.go.txt| new file mode 100644 |
| index 000000000..4db2fb9a9 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/lease_builder_call.go.txt |
| @@ -0,0 +1,21 @@ |
| +package lease |
| + |
| +import ( |
| + "context" |
| + |
| + "github.com/benbjohnson/litestream" |
| +) |
| + |
| +var verifyReplicaClient = func(ctx context.Context, bucket, prefix, region string) (litestream.ReplicaClient, error) { |
| + return newReplicaClient(bucket, prefix, region) |
| +} |
| + |
| +func HasReplica(ctx context.Context, bucket, prefix, region string) (bool, error) { |
| + _, err := newReplicaClient(bucket, prefix, region) |
| + return false, err |
| +} |
| + |
| +func Restore(ctx context.Context, dbPath, bucket, prefix, region string) (bool, error) { |
| + _, err := newReplicaClientForUID(bucket, prefix, region, 0, nil) |
| + return false, err |
| +} |
diff --git a/internal/lease/testdata/readerguard/lease_new_client.go.txt b/internal/lease/testdata/readerguard/lease_new_client.go.txt| new file mode 100644 |
| index 000000000..08a29cf76 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/lease_new_client.go.txt |
| @@ -0,0 +1,9 @@ |
| +package lease |
| + |
| +import lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| +func restoreClient(bucket, prefix string) *lss3.ReplicaClient { |
| + c := lss3.NewReplicaClient() |
| + c.Bucket, c.Path = bucket, prefix |
| + return c |
| +} |
diff --git a/internal/lease/testdata/readerguard/new_builtin.go.txt b/internal/lease/testdata/readerguard/new_builtin.go.txt| new file mode 100644 |
| index 000000000..425446077 |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/new_builtin.go.txt |
| @@ -0,0 +1,9 @@ |
| +package ops |
| + |
| +import lss3 "github.com/benbjohnson/litestream/s3" |
| + |
| +func reader(bucket, loc string) *lss3.ReplicaClient { |
| + c := new(lss3.ReplicaClient) |
| + c.Bucket, c.Path = bucket, loc |
| + return c |
| +} |
diff --git a/internal/lease/testdata/readerguard/read_replica_client.go.txt b/internal/lease/testdata/readerguard/read_replica_client.go.txt| new file mode 100644 |
| index 000000000..cb44642bf |
| --- /dev/null |
| +++ b/internal/lease/testdata/readerguard/read_replica_client.go.txt |
| @@ -0,0 +1,14 @@ |
| +package ops |
| + |
| +import ( |
| + "context" |
| + |
| + l "github.com/carlosframework/platform/internal/lease" |
| +) |
| + |
| +var open = l.ReadReplicaClient |
| + |
| +func reader(ctx context.Context, bucket, loc string) error { |
| + _, err := l.ReadReplicaClient(ctx, bucket, loc, "") |
| + return err |
| +} |
diff --git a/internal/ops/hibernate_verify.go b/internal/ops/hibernate_verify.go| index e6fb77162..97aa99332 100644 |
| --- a/internal/ops/hibernate_verify.go |
| +++ b/internal/ops/hibernate_verify.go |
| @@ -136,8 +136,16 @@ const assignmentMaxAge = 15 * time.Minute |
| // The seams the tests drive; production points them at the hibernate |
| // bucket and the box's own disk. |
| var ( |
| + // openReplica resolves the host's replica (lease.ResolveReplica: the |
| + // generation its head.json names, or the root without one) and hands |
| + // back that one generation's reader, so a drill plans and restores |
| + // inside it alone (spec 2026-11-12 §6.1, G4). |
| openReplica = func(ctx context.Context, bucket, prefix, region string) (dbdoor.ReplicaReader, error) { |
| - return lease.ReadReplicaClient(ctx, bucket, prefix, region) |
| + r, err := lease.ResolveReplica(ctx, bucket, prefix, region) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return r.Client, nil |
| } |
| // verifyAt restores the planned position through the planner's own |
| // listing (member backups 2a, R2): it holds a reader that can only list |
| @@ -736,7 +744,8 @@ func storageError(err error) bool { |
| // plan plans the newest copy and returns the listing it planned from, the |
| // only reader the restore is given: each level is listed once per attempt, |
| // and a file compacted away since answers os.ErrNotExist, which plans |
| -// again. |
| +// again. Each attempt resolves the replica once (openReplica), so its plan |
| +// and restore read one generation. |
| func (d Drill) plan(ctx context.Context, prefix string) (dbdoor.RestorePlan, dbdoor.ReplicaReader, error) { |
| rd, err := openReplica(ctx, d.Cfg.Bucket, prefix, d.Cfg.Region) |
| if err != nil { |
diff --git a/internal/ops/hibernate_verify_resolve_test.go b/internal/ops/hibernate_verify_resolve_test.go| new file mode 100644 |
| index 000000000..d255e3c09 |
| --- /dev/null |
| +++ b/internal/ops/hibernate_verify_resolve_test.go |
| @@ -0,0 +1,75 @@ |
| +package ops |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + |
| + "github.com/carlosframework/platform/internal/activator" |
| + "github.com/carlosframework/platform/internal/dbdoor" |
| + "github.com/carlosframework/platform/internal/dbdoor/dbdoortest" |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/lease/leasetest" |
| + "github.com/carlosframework/platform/internal/replicagen" |
| +) |
| + |
| +// The restore drill reads through the resolver (spec §6.1): on a host with |
| +// head.json it plans the current generation, never the root its |
| +// predecessor left. The production opener runs against leasetest's S3. |
| +func TestDrillResolvesHead(t *testing.T) { |
| + const bucket, loc = "data", "hib/shop.example.com" |
| + m := leasetest.NewVersionedBucket() |
| + m.AddBucket(bucket) |
| + handler, _ := leasetest.NewS3Server(m) |
| + srv := httptest.NewServer(handler) |
| + t.Cleanup(srv.Close) |
| + t.Setenv("AWS_ACCESS_KEY_ID", "test-key") |
| + t.Setenv("AWS_SECRET_ACCESS_KEY", "test-secret") |
| + t.Setenv("AWS_SESSION_TOKEN", "") |
| + t.Setenv("AWS_EC2_METADATA_DISABLED", "true") |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(t.TempDir(), "absent")) |
| + t.Setenv("CARLOS_S3_ENDPOINT", srv.URL) |
| + |
| + gen := replicagen.Name(42) |
| + put := func(name string, batches int) string { |
| + dir := t.TempDir() |
| + dbdoortest.Replicate(t, dir, batches) |
| + if _, err := m.PutFileReplica(bucket, replicagen.Prefix(loc, name), dir); err != nil { |
| + t.Fatal(err) |
| + } |
| + return dir |
| + } |
| + rootDir := put(replicagen.Root, 1) |
| + genDir := put(gen, 3) |
| + body, _ := json.Marshal(lease.Head{V: 1, Generation: gen, StartTXID: 1, Predecessor: replicagen.Root, |
| + CreatedBy: lease.HeadCreator{LockGeneration: 42, At: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)}, |
| + History: []lease.HeadHistory{}}) |
| + m.Put(bucket, loc+"/head.json", body) |
| + |
| + ctx := context.Background() |
| + want, err := dbdoor.PlanFrom(ctx, lsfile.NewReplicaClient(genDir), time.Time{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rootPlan, err := dbdoor.PlanFrom(ctx, lsfile.NewReplicaClient(rootDir), time.Time{}) |
| + if err != nil || rootPlan.TXID >= want.TXID { |
| + t.Fatalf("fixture: root plan %d, generation plan %d, %v", rootPlan.TXID, want.TXID, err) |
| + } |
| + d := Drill{Cfg: &activator.Config{Bucket: bucket, Region: "us-east-1"}} |
| + plan, listed, err := d.plan(ctx, loc) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if plan.TXID != want.TXID || plan.Files != want.Files { |
| + t.Fatalf("drill planned %d (%d files), want the generation's %d (%d files)", plan.TXID, plan.Files, want.TXID, want.Files) |
| + } |
| + if _, err := lease.VerifyReaderAt(ctx, listed, loc, t.TempDir(), plan.TXID); err != nil { |
| + t.Fatalf("the drill's restore of the generation: %v", err) |
| + } |
| +} |