| 1 | package lease |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/benbjohnson/litestream" |
| 13 | lsfile "github.com/benbjohnson/litestream/file" |
| 14 | ) |
| 15 | |
| 16 | func TestGenerationRefusedSnapshotReleasesWAL(t *testing.T) { |
| 17 | path := filepath.Join(t.TempDir(), "source.db") |
| 18 | seedDB(t, path) |
| 19 | db := litestream.NewDB(path) |
| 20 | db.MonitorInterval = 0 |
| 21 | db.Replica = litestream.NewReplicaWithClient(db, lsfile.NewReplicaClient(t.TempDir())) |
| 22 | db.Replica.MonitorEnabled = false |
| 23 | if err := db.Open(); err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | t.Cleanup(func() { db.Close(context.Background()) }) |
| 27 | if err := db.SyncAndWait(t.Context()); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | countWAL := func() int { |
| 31 | t.Helper() |
| 32 | fds, err := os.ReadDir("/proc/self/fd") |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | count := 0 |
| 37 | for _, fd := range fds { |
| 38 | name, err := os.Readlink(filepath.Join("/proc/self/fd", fd.Name())) |
| 39 | if err == nil && name == path+"-wal" { |
| 40 | count++ |
| 41 | } |
| 42 | } |
| 43 | return count |
| 44 | } |
| 45 | baseline := countWAL() |
| 46 | pos, reader, err := db.SnapshotReader(t.Context()) |
| 47 | if err != nil { |
| 48 | t.Fatal(err) |
| 49 | } |
| 50 | pipe := reader.(*io.PipeReader) |
| 51 | t.Cleanup(func() { pipe.Close() }) |
| 52 | deadline := time.Now().Add(time.Second) |
| 53 | for countWAL() == baseline && time.Now().Before(deadline) { |
| 54 | time.Sleep(time.Millisecond) |
| 55 | } |
| 56 | if countWAL() <= baseline { |
| 57 | t.Fatal("snapshot did not hold its WAL descriptor") |
| 58 | } |
| 59 | client := &generationClient{client: db.Replica.Client, check: func(context.Context) error { return ErrLost }} |
| 60 | if _, err := client.WriteLTXFile(t.Context(), litestream.SnapshotLevel, 1, pos.TXID, reader); !errors.Is(err, ErrLost) { |
| 61 | t.Fatal(err) |
| 62 | } |
| 63 | deadline = time.Now().Add(time.Second) |
| 64 | for countWAL() > baseline && time.Now().Before(deadline) { |
| 65 | time.Sleep(time.Millisecond) |
| 66 | } |
| 67 | if got := countWAL(); got != baseline { |
| 68 | t.Fatalf("refused snapshot retained WAL descriptors: got %d, want %d", got, baseline) |
| 69 | } |
| 70 | } |
| 71 | |