| new file mode 100644 |
| index 000000000..1fb967802 |
| --- /dev/null |
| +++ b/internal/lease/ltxtruncate_test.go |
| @@ -0,0 +1,253 @@ |
| +package lease |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/binary" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "math/rand" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "github.com/benbjohnson/litestream" |
| + lsfile "github.com/benbjohnson/litestream/file" |
| + "github.com/superfly/ltx" |
| + _ "modernc.org/sqlite" |
| +) |
| + |
| +// replicatedLTX is one LTX file a real litestream replication wrote. |
| +type replicatedLTX struct { |
| + info *ltx.FileInfo |
| + path string |
| + data []byte |
| + pages int |
| +} |
| + |
| +// multiPageReplica replicates a database through litestream to a file |
| +// replica in two syncs, each writing rows that do not compress away, and |
| +// returns the replica directory and its level-0 files in TXID order. Both |
| +// the snapshot and the file after it span several pages. |
| +func multiPageReplica(t *testing.T) (string, []replicatedLTX) { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "source.db") |
| + writer, err := sql.Open("sqlite", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { writer.Close() }) |
| + if _, err := writer.Exec(`PRAGMA journal_mode=WAL`); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := writer.Exec(`CREATE TABLE t (id INTEGER PRIMARY KEY, body TEXT)`); err != nil { |
| + t.Fatal(err) |
| + } |
| + rng := rand.New(rand.NewSource(1443)) |
| + insert := func(n int) { |
| + for i := 0; i < n; i++ { |
| + body := make([]byte, 400) |
| + rng.Read(body) |
| + if _, err := writer.Exec(`INSERT INTO t (body) VALUES (?)`, fmt.Sprintf("%x", body)); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + } |
| + insert(12) |
| + |
| + replica := t.TempDir() |
| + client := lsfile.NewReplicaClient(replica) |
| + db := litestream.NewDB(path) |
| + db.MonitorInterval = 0 |
| + db.Replica = litestream.NewReplicaWithClient(db, client) |
| + db.Replica.MonitorEnabled = false |
| + if err := db.Open(); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { _ = db.Close(context.Background()) }) |
| + if err := db.SyncAndWait(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + insert(12) |
| + if err := db.SyncAndWait(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + itr, err := client.LTXFiles(context.Background(), 0, 0, false) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer itr.Close() |
| + var files []replicatedLTX |
| + for itr.Next() { |
| + info := itr.Item() |
| + p := client.LTXFilePath(0, info.MinTXID, info.MaxTXID) |
| + data, err := os.ReadFile(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dec := ltx.NewDecoder(bytes.NewReader(data)) |
| + if err := dec.Verify(); err != nil { |
| + t.Fatalf("fixture: %s does not verify whole: %v", p, err) |
| + } |
| + files = append(files, replicatedLTX{info: info, path: p, data: data, pages: dec.PageN()}) |
| + } |
| + if err := itr.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(files) < 2 { |
| + t.Fatalf("fixture: %d level-0 files, want at least 2", len(files)) |
| + } |
| + last, prev := files[len(files)-1], files[len(files)-2] |
| + if prev.pages < 3 || last.pages < 3 { |
| + t.Fatalf("fixture: the last two files hold %d and %d pages, want at least 3 each", prev.pages, last.pages) |
| + } |
| + return replica, files |
| +} |
| + |
| +// decodeAll runs one prefix through the Decoder as a restore of a single |
| +// file would (Verify: header, every page, page index, trailer), turning a |
| +// panic into a test failure that names the cut. |
| +func decodeAll(t *testing.T, what string, r io.Reader) (err error) { |
| + t.Helper() |
| + defer func() { |
| + if p := recover(); p != nil { |
| + t.Fatalf("%s: decoder panicked: %v", what, p) |
| + } |
| + }() |
| + return ltx.NewDecoder(r).Verify() |
| +} |
| + |
| +// compactAll runs inputs through ltx.NewCompactor and Compact as |
| +// litestream's restore does (replica.go), turning a panic into a test |
| +// failure that names the cut. |
| +func compactAll(t *testing.T, what string, inputs ...io.Reader) (err error) { |
| + t.Helper() |
| + defer func() { |
| + if p := recover(); p != nil { |
| + t.Fatalf("%s: compactor panicked: %v", what, p) |
| + } |
| + }() |
| + c, err := ltx.NewCompactor(io.Discard, inputs) |
| + if err != nil { |
| + return err |
| + } |
| + c.HeaderFlags = ltx.HeaderFlagNoChecksum |
| + return c.Compact(context.Background()) |
| +} |
| + |
| +// An LTX file cut anywhere is a file that ended early, and says so: |
| +// io.ErrUnexpectedEOF in the chain, from the decoder and from the |
| +// compactor, alone and beside a whole second input. It never panics (a |
| +// cut in the 8 bytes after the page block's terminator used to panic |
| +// Decoder.Close, inside the restore's compactor goroutine) and never |
| +// passes (a cut at a page boundary used to read as the end of the pages). |
| +func TestTruncatedLTXNeverPanicsOrPasses(t *testing.T) { |
| + _, files := multiPageReplica(t) |
| + prev, last := files[len(files)-2], files[len(files)-1] |
| + if !ltx.IsContiguous(prev.info.MaxTXID, last.info.MinTXID, last.info.MaxTXID) { |
| + t.Fatalf("fixture: %s then %s are not contiguous", prev.path, last.path) |
| + } |
| + |
| + // The whole files pass every path: the sweep below fails for the cut, |
| + // not for the fixture. |
| + if err := compactAll(t, "whole", bytes.NewReader(prev.data), bytes.NewReader(last.data)); err != nil { |
| + t.Fatalf("compacting the whole files: %v", err) |
| + } |
| + |
| + for _, f := range []replicatedLTX{prev, last} { |
| + for cut := 0; cut < len(f.data); cut++ { |
| + short := f.data[:cut] |
| + what := fmt.Sprintf("txids %s-%s cut to %d of %d bytes", f.info.MinTXID, f.info.MaxTXID, cut, len(f.data)) |
| + if err := decodeAll(t, what, bytes.NewReader(short)); !errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Fatalf("%s: decode = %v, want io.ErrUnexpectedEOF", what, err) |
| + } |
| + if err := compactAll(t, what, bytes.NewReader(short)); !errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Fatalf("%s: compact alone = %v, want io.ErrUnexpectedEOF", what, err) |
| + } |
| + inputs := []io.Reader{bytes.NewReader(prev.data), bytes.NewReader(short)} |
| + if f.path == prev.path { |
| + inputs = []io.Reader{bytes.NewReader(short), bytes.NewReader(last.data)} |
| + } |
| + if err := compactAll(t, what, inputs...); !errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Fatalf("%s: compact beside a whole file = %v, want io.ErrUnexpectedEOF", what, err) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// failingReader gives n bytes of data and then err, never io.EOF: a |
| +// transfer that broke. |
| +type failingReader struct { |
| + data []byte |
| + err error |
| +} |
| + |
| +func (r *failingReader) Read(p []byte) (int, error) { |
| + if len(r.data) == 0 { |
| + return 0, r.err |
| + } |
| + n := copy(p, r.data) |
| + r.data = r.data[n:] |
| + return n, nil |
| +} |
| + |
| +// A read that fails partway through a file keeps its own error: the |
| +// decoder names an early end only when the input itself ended, so a broken |
| +// transfer is never mistaken for a short file, wherever it breaks. |
| +func TestLTXReadErrorIsKept(t *testing.T) { |
| + _, files := multiPageReplica(t) |
| + f := files[len(files)-1] |
| + reset := errors.New("connection reset by peer") |
| + for cut := 0; cut < len(f.data); cut++ { |
| + what := fmt.Sprintf("read failing after %d of %d bytes", cut, len(f.data)) |
| + err := decodeAll(t, what, &failingReader{data: f.data[:cut], err: reset}) |
| + if !errors.Is(err, reset) || errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Fatalf("%s: decode = %v, want the read's own error and no io.ErrUnexpectedEOF", what, err) |
| + } |
| + err = compactAll(t, what, &failingReader{data: f.data[:cut], err: reset}) |
| + if !errors.Is(err, reset) || errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Fatalf("%s: compact = %v, want the read's own error and no io.ErrUnexpectedEOF", what, err) |
| + } |
| + } |
| +} |
| + |
| +// pageBlockEnd is the offset just past an LTX file's page block: the file |
| +// ends with the page index, its 8-byte size, and the trailer. |
| +func pageBlockEnd(t *testing.T, data []byte) int { |
| + t.Helper() |
| + tail := len(data) - ltx.TrailerSize - 8 |
| + if tail < ltx.HeaderSize { |
| + t.Fatalf("fixture: %d bytes is too short to be an LTX file", len(data)) |
| + } |
| + return tail - int(binary.BigEndian.Uint64(data[tail:tail+8])) |
| +} |
| + |
| +// A replica whose newest file was cut just past its page block (the cut |
| +// that panicked Decoder.Close inside litestream's compactor goroutine, |
| +// taking down the agent on a wake, the console on a seed, or the drill) |
| +// fails the real pinned verify restore with an error naming the early |
| +// end, and leaves nothing behind. |
| +func TestTruncatedReplicaFileRestoreFailsWithoutPanic(t *testing.T) { |
| + replica, files := multiPageReplica(t) |
| + last := files[len(files)-1] |
| + cut := pageBlockEnd(t, last.data) + 4 |
| + if err := os.WriteFile(last.path, last.data[:cut], 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + dir := t.TempDir() |
| + _, err := VerifyClientAt(context.Background(), lsfile.NewReplicaClient(replica), "hib/x.example.com", dir, uint64(last.info.MaxTXID)) |
| + if err == nil { |
| + t.Fatal("a restore through a truncated file passed") |
| + } |
| + if !errors.Is(err, io.ErrUnexpectedEOF) { |
| + t.Fatalf("restore = %v, want io.ErrUnexpectedEOF in the chain", err) |
| + } |
| + if errors.Is(err, ErrCheckFailed) { |
| + t.Fatalf("restore = %v: a short file is not a failed check", err) |
| + } |
| + assertEmptyDir(t, dir) |
| +} |