carlos / platform Public

db forward task 6: dbdoor ListLevel, PlanFrom and RestoreLocal; the console door lists through ListLevel

RestorePlan gains a slice (Planned), so it is no longer comparable with
!=; plan_test.go's two struct comparisons use reflect.DeepEqual, with no
change to what they assert.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e2f137c8b45cb57dca9659c88d09b900a4767237 parent 6939470
5 files changed, +343 −27
  • internal/console/apidb.go +3 −23
  • internal/dbdoor/plan.go +17 −2
  • internal/dbdoor/plan_from.go +166 −0
  • internal/dbdoor/plan_from_test.go +154 −0
  • internal/dbdoor/plan_test.go +3 −2
diff --git a/internal/console/apidb.go b/internal/console/apidb.go
index f1121beee..fbb0e78b8 100644
--- a/internal/console/apidb.go
+++ b/internal/console/apidb.go
@@ -21,7 +21,6 @@ import (
"log"
"net/http"
"os"
- "sort"
"strconv"
"sync"
"time"
@@ -327,29 +326,10 @@ func (s *Server) handleAPIDBList(w http.ResponseWriter, r *http.Request) {
// by MinTXID, with an empty level as an empty list. The db door and the
// console's own in-process door (replicaDoer, for --from) both list
// through it, so a seeded copy restores from the listing carlos db pull
-// reads.
+// reads. The body moved to dbdoor.ListLevel so the box's planner lists
+// through it too (db region forward spec §6).
func listReplicaLevel(ctx context.Context, rd replicaReader, level int) (dbdoor.ListResponse, error) {
- itr, err := rd.LTXFiles(ctx, level, 0, false)
- if err != nil {
- return dbdoor.ListResponse{}, err
- }
- out := dbdoor.ListResponse{Files: []dbdoor.LTXFile{}}
- for itr.Next() {
- f := itr.Item()
- out.Files = append(out.Files, dbdoor.LTXFile{
- Level: level, MinTXID: uint64(f.MinTXID), MaxTXID: uint64(f.MaxTXID),
- Size: f.Size, CreatedAt: f.CreatedAt,
- })
- }
- err = itr.Err()
- if cerr := itr.Close(); err == nil {
- err = cerr
- }
- if err != nil {
- return dbdoor.ListResponse{}, err
- }
- sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].MinTXID < out.Files[j].MinTXID })
- return out, nil
+ return dbdoor.ListLevel(ctx, rd, level)
}
// handleAPIDBGet streams one LTX file by coordinate. The bytes pass through
diff --git a/internal/dbdoor/plan.go b/internal/dbdoor/plan.go
index 826a24c63..a57279e8a 100644
--- a/internal/dbdoor/plan.go
+++ b/internal/dbdoor/plan.go
@@ -28,6 +28,12 @@ type RestorePlan struct {
// when the request is at or past the latest transaction, which
// litestream would otherwise refuse as not available.
Target uint64
+ // Planned is the plan's files in restore order (box side: what the
+ // worker is sent, db region forward spec §8.2).
+ Planned []LTXFile
+ // At is the last planned file's header time: the time of the copy's
+ // newest transaction, as RestoreAsOf's Restored.At reports it.
+ At time.Time
}
// PlanRestore plans a restore to target (0: latest) through c and reads the
@@ -57,11 +63,19 @@ func PlanRestore(ctx context.Context, c *Client, target uint64) (RestorePlan, er
case len(infos) == 0:
return RestorePlan{}, ErrNothingReplicated
}
- p := RestorePlan{Target: target}
+ return finishPlan(ctx, c, infos, target)
+}
+
+// finishPlan sums the plan, records its files, and reads and bounds the
+// last planned file's header: the size check's one decode (db region
+// forward spec §8.1). PlanRestore and PlanFrom both end here, so both read
+// and check the last file's header the same way.
+func finishPlan(ctx context.Context, c litestream.ReplicaClient, infos []*ltx.FileInfo, target uint64) (RestorePlan, error) {
+ p := RestorePlan{Target: target, Files: len(infos)}
for _, f := range infos {
p.LTXBytes += f.Size
+ p.Planned = append(p.Planned, LTXFile{Level: f.Level, MinTXID: uint64(f.MinTXID), MaxTXID: uint64(f.MaxTXID), Size: f.Size, CreatedAt: f.CreatedAt})
}
- p.Files = len(infos)
last := infos[len(infos)-1]
p.TXID = uint64(last.MaxTXID)
rc, err := c.OpenLTXFile(ctx, last.Level, last.MinTXID, last.MaxTXID, 0, ltx.HeaderSize)
@@ -87,5 +101,6 @@ func PlanRestore(ctx context.Context, c *Client, target uint64) (RestorePlan, er
last.Level, Span(uint64(last.MinTXID), uint64(last.MaxTXID)), h.PageSize, h.Commit, Span(uint64(h.MinTXID), uint64(h.MaxTXID)))
}
p.RestoredBytes = int64(h.Commit) * int64(h.PageSize)
+ p.At = time.UnixMilli(h.Timestamp).UTC()
return p, nil
}
diff --git a/internal/dbdoor/plan_from.go b/internal/dbdoor/plan_from.go
new file mode 100644
index 000000000..23b378e61
--- /dev/null
+++ b/internal/dbdoor/plan_from.go
@@ -0,0 +1,166 @@
+package dbdoor
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ "github.com/superfly/ltx"
+)
+
+// 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.
+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)
+}
+
+// ListLevel lists one level of rd in the door's wire shape, ordered by
+// MinTXID, with an empty level as an empty list, and with S3's LastModified
+// as CreatedAt (useMetadata false). The console's door and the box's planner
+// both list through it, so a forwarded --at stops at the transaction an
+// in-region one does (spec §6, T6).
+func ListLevel(ctx context.Context, rd ReplicaReader, level int) (ListResponse, error) {
+ itr, err := rd.LTXFiles(ctx, level, 0, false)
+ if err != nil {
+ return ListResponse{}, err
+ }
+ out := ListResponse{Files: []LTXFile{}}
+ for itr.Next() {
+ f := itr.Item()
+ out.Files = append(out.Files, LTXFile{
+ Level: level, MinTXID: uint64(f.MinTXID), MaxTXID: uint64(f.MaxTXID),
+ Size: f.Size, CreatedAt: f.CreatedAt,
+ })
+ }
+ err = itr.Err()
+ if cerr := itr.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return ListResponse{}, err
+ }
+ sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].MinTXID < out.Files[j].MinTXID })
+ return out, nil
+}
+
+// listing is a read-only litestream.ReplicaClient over rd that lists through
+// ListLevel. For an as-of plan it also does what the CLI's recorder does
+// over the door's listings: refuse a listing with no times (ErrNoTimes) and
+// remember the earliest file a restore could start from.
+type listing struct {
+ rd ReplicaReader
+ asOf bool
+ mu sync.Mutex
+ oldest time.Time
+}
+
+func (l *listing) Type() string { return "carlos-db-listing" }
+func (l *listing) Init(context.Context) error { return nil }
+func (l *listing) SetLogger(*slog.Logger) {}
+
+func (l *listing) LTXFiles(ctx context.Context, level int, seek ltx.TXID, _ bool) (ltx.FileIterator, error) {
+ out, err := ListLevel(ctx, l.rd, level)
+ if err != nil {
+ return nil, err
+ }
+ if l.asOf {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ for _, f := range out.Files {
+ if f.CreatedAt.IsZero() {
+ return nil, ErrNoTimes
+ }
+ if level == litestream.SnapshotLevel || f.MinTXID == 1 {
+ if l.oldest.IsZero() || f.CreatedAt.Before(l.oldest) {
+ l.oldest = f.CreatedAt
+ }
+ }
+ }
+ }
+ return fileIterator(out.Files, level, seek), nil
+}
+
+func (l *listing) OpenLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID, offset, size int64) (io.ReadCloser, error) {
+ return l.rd.OpenLTXFile(ctx, level, minTXID, maxTXID, offset, size)
+}
+
+func (l *listing) WriteLTXFile(context.Context, int, ltx.TXID, ltx.TXID, io.Reader) (*ltx.FileInfo, error) {
+ return nil, errReadOnly
+}
+
+func (l *listing) DeleteLTXFiles(context.Context, []*ltx.FileInfo) error { return errReadOnly }
+
+func (l *listing) DeleteAll(context.Context) error { return errReadOnly }
+
+var _ litestream.ReplicaClient = (*listing)(nil)
+
+// PlanFrom plans the restore RestoreAsOf would make through the door, from
+// rd directly: the newest copy when at is zero, else the copy holding every
+// file listed before at rounded down to its second. Its errors are
+// RestoreAsOf's: ErrNothingReplicated, a *BeforeHistoryError naming the
+// oldest point kept, ErrNoTimes.
+func PlanFrom(ctx context.Context, rd ReplicaReader, at time.Time) (RestorePlan, error) {
+ l := &listing{rd: rd, asOf: !at.IsZero()}
+ var ts time.Time
+ if !at.IsZero() {
+ if at.Truncate(time.Second).Before(EarliestAsOf) {
+ at = EarliestAsOf
+ }
+ ts = at.Truncate(time.Second)
+ }
+ infos, err := litestream.CalcRestorePlan(ctx, l, 0, ts, slog.Default())
+ switch {
+ case errors.Is(err, ErrNoTimes):
+ return RestorePlan{}, ErrNoTimes
+ case errors.Is(err, litestream.ErrTxNotAvailable) || errors.Is(err, litestream.ErrNoSnapshots):
+ l.mu.Lock()
+ oldest := l.oldest
+ l.mu.Unlock()
+ if !ts.IsZero() && !oldest.IsZero() {
+ if !oldest.Before(ts) {
+ return RestorePlan{}, &BeforeHistoryError{Oldest: oldest.Truncate(time.Second).Add(time.Second)}
+ }
+ return RestorePlan{}, err
+ }
+ return RestorePlan{}, ErrNothingReplicated
+ case err != nil:
+ return RestorePlan{}, err
+ case len(infos) == 0:
+ return RestorePlan{}, ErrNothingReplicated
+ }
+ return finishPlan(ctx, l, infos, 0)
+}
+
+// RestoreLocal restores the replica c holds, a litestream file replica in a
+// private directory (the db-read worker's, or the CLI's for a forwarded
+// pull), exactly to target, at out, and proves it with lease.CheckDBContext.
+// On failure nothing is left at out.
+func RestoreLocal(ctx context.Context, c litestream.ReplicaClient, out string, target uint64) error {
+ if err := restoreOnce(ctx, c, out, target, time.Time{}); err != nil {
+ removeCopy(out)
+ if cerr := ctx.Err(); cerr != nil {
+ return cerr
+ }
+ return err
+ }
+ if err := checkDB(ctx, out); err != nil {
+ removeCopy(out)
+ if cerr := ctx.Err(); cerr != nil {
+ return cerr
+ }
+ return fmt.Errorf("%w: %v", ErrCheckFailed, err)
+ }
+ if err := ctx.Err(); err != nil {
+ removeCopy(out)
+ return err
+ }
+ return nil
+}
diff --git a/internal/dbdoor/plan_from_test.go b/internal/dbdoor/plan_from_test.go
new file mode 100644
index 000000000..e0503147c
--- /dev/null
+++ b/internal/dbdoor/plan_from_test.go
@@ -0,0 +1,154 @@
+package dbdoor
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/benbjohnson/litestream"
+ lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/superfly/ltx"
+
+ "github.com/carlosframework/platform/internal/dbdoor/dbdoortest"
+)
+
+// metaSpy records every useMetadata the listing passes down: the box must
+// list LastModified as CreatedAt, exactly as the console's door does
+// (listReplicaLevel), never S3 metadata timestamps (spec §6, T6).
+type metaSpy struct {
+ ReplicaReader
+ sawMetadata bool
+}
+
+func (m *metaSpy) LTXFiles(ctx context.Context, level int, seek ltx.TXID, useMetadata bool) (ltx.FileIterator, error) {
+ if useMetadata {
+ m.sawMetadata = true
+ }
+ return m.ReplicaReader.LTXFiles(ctx, level, seek, useMetadata)
+}
+
+func TestListLevelIsTheDoorsListing(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 3)
+ spy := &metaSpy{ReplicaReader: lsfile.NewReplicaClient(dir)}
+ got, err := ListLevel(context.Background(), spy, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := collect(t, NewClient(newTestDoor(t, dir).do), 0, 0)
+ if len(got.Files) != len(want) || spy.sawMetadata {
+ t.Fatalf("ListLevel = %d files (metadata %v), the door lists %d", len(got.Files), spy.sawMetadata, len(want))
+ }
+ for i := range want {
+ f := got.Files[i]
+ if f.MinTXID != uint64(want[i].MinTXID) || f.MaxTXID != uint64(want[i].MaxTXID) || f.Size != want[i].Size || !f.CreatedAt.Equal(want[i].CreatedAt) {
+ t.Fatalf("file %d: %+v, the door lists %+v", i, f, want[i])
+ }
+ }
+ empty, err := ListLevel(context.Background(), spy, 5)
+ if err != nil || empty.Files == nil || len(empty.Files) != 0 {
+ t.Fatalf("an empty level = %+v, %v; want an empty list", empty, err)
+ }
+}
+
+// PlanFrom plans what RestoreAsOf through the door restores: the same
+// transaction, the same time, the same size, for the newest copy and as of
+// a time.
+func TestPlanFromMatchesTheDoorsRestore(t *testing.T) {
+ dir := t.TempDir()
+ src := dbdoortest.Replicate(t, dir, 2)
+ at := pause()
+ addBatch(t, src, dir, 2)
+ for _, when := range []time.Time{{}, at} {
+ plan, err := PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), when)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := RestoreAsOf(context.Background(), NewClient(newTestDoor(t, dir).do), t.TempDir(), when)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st, err := os.Stat(got.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ os.RemoveAll(got.Dir)
+ if plan.TXID != got.TXID || !plan.At.Equal(got.At) || plan.RestoredBytes != st.Size() || len(plan.Planned) != plan.Files || plan.Files == 0 {
+ t.Fatalf("as of %v: plan %+v; the door restored txid %d at %v, %d bytes", when, plan, got.TXID, got.At, st.Size())
+ }
+ }
+}
+
+func TestPlanFromBeforeHistoryNamesTheOldestPoint(t *testing.T) {
+ t.Parallel()
+ before := time.Now().Add(-time.Hour)
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 2)
+ _, err := PlanFrom(context.Background(), lsfile.NewReplicaClient(dir), before)
+ var bh *BeforeHistoryError
+ if !errors.As(err, &bh) {
+ t.Fatalf("PlanFrom before history = %v", err)
+ }
+ _, derr := RestoreAsOf(context.Background(), NewClient(newTestDoor(t, dir).do), t.TempDir(), before)
+ var dbh *BeforeHistoryError
+ if !errors.As(derr, &dbh) || !dbh.Oldest.Equal(bh.Oldest) {
+ t.Fatalf("the door says %v, the plan says %v", derr, bh.Oldest)
+ }
+}
+
+func TestPlanFromAnEmptyReplica(t *testing.T) {
+ t.Parallel()
+ _, err := PlanFrom(context.Background(), lsfile.NewReplicaClient(t.TempDir()), time.Time{})
+ if !errors.Is(err, ErrNothingReplicated) {
+ t.Fatalf("PlanFrom on nothing = %v", err)
+ }
+}
+
+// RestoreLocal restores exactly the planned files, copied into a fresh file
+// replica the way the worker writes them, to the plan's transaction.
+func TestRestoreLocalRestoresThePlan(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ dbdoortest.Replicate(t, dir, 4)
+ src := lsfile.NewReplicaClient(dir)
+ plan, err := PlanFrom(context.Background(), src, time.Time{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ root := t.TempDir()
+ for _, f := range plan.Planned {
+ rc, err := src.OpenLTXFile(context.Background(), f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID), 0, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := litestream.LTXFilePath(root, f.Level, ltx.TXID(f.MinTXID), ltx.TXID(f.MaxTXID))
+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ out, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := io.Copy(out, rc); err != nil {
+ t.Fatal(err)
+ }
+ rc.Close()
+ out.Close()
+ }
+ db := filepath.Join(t.TempDir(), "copy.db")
+ if err := RestoreLocal(context.Background(), lsfile.NewReplicaClient(root), db, plan.TXID); err != nil {
+ t.Fatal(err)
+ }
+ if rows := countRows(t, db); rows != 4*dbdoortest.Rows {
+ t.Fatalf("restored %d rows", rows)
+ }
+ st, _ := os.Stat(db)
+ if st.Size() != plan.RestoredBytes {
+ t.Fatalf("restored %d bytes, planned %d", st.Size(), plan.RestoredBytes)
+ }
+}
diff --git a/internal/dbdoor/plan_test.go b/internal/dbdoor/plan_test.go
index 151169bd2..1a94be9c3 100644
--- a/internal/dbdoor/plan_test.go
+++ b/internal/dbdoor/plan_test.go
@@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "reflect"
"strings"
"testing"
@@ -82,7 +83,7 @@ func TestPlanRestoreTargetPastTheEndPlansTheLatest(t *testing.T) {
if err != nil {
t.Fatalf("target %d: %v", target, err)
}
- if got != latest {
+ if !reflect.DeepEqual(got, latest) {
t.Fatalf("target %d planned %+v, want the latest %+v", target, got, latest)
}
}
@@ -305,7 +306,7 @@ func TestPlanRestoreRefusesAHeaderThatDoesNotDescribeItsFile(t *testing.T) {
if err == nil || errors.Is(err, ErrNothingReplicated) || errors.Is(err, ErrHistoryGone) {
t.Fatalf("plan %+v, err = %v; want the header refused as its own error", plan, err)
}
- if plan != (RestorePlan{}) {
+ if !reflect.DeepEqual(plan, RestorePlan{}) {
t.Fatalf("a refused header still planned %+v", plan)
}
})