forked from benbjohnson/litestream
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore_test.go
More file actions
484 lines (409 loc) · 13.5 KB
/
Copy pathstore_test.go
File metadata and controls
484 lines (409 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package litestream_test
import (
"errors"
"fmt"
"path/filepath"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/benbjohnson/litestream"
"github.com/benbjohnson/litestream/file"
"github.com/benbjohnson/litestream/internal/testingutil"
)
func TestStore_CompactDB(t *testing.T) {
t.Run("L1", func(t *testing.T) {
db0, sqldb0 := testingutil.MustOpenDBs(t)
defer testingutil.MustCloseDBs(t, db0, sqldb0)
db1, sqldb1 := testingutil.MustOpenDBs(t)
defer testingutil.MustCloseDBs(t, db1, sqldb1)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1, Interval: 1 * time.Second},
{Level: 2, Interval: 500 * time.Millisecond},
}
s := litestream.NewStore([]*litestream.DB{db0, db1}, levels)
s.CompactionMonitorEnabled = false
if err := s.Open(t.Context()); err != nil {
t.Fatal(err)
}
defer s.Close(t.Context())
if _, err := sqldb0.ExecContext(t.Context(), `CREATE TABLE t (id INT);`); err != nil {
t.Fatal(err)
}
if _, err := sqldb0.ExecContext(t.Context(), `INSERT INTO t (id) VALUES (100)`); err != nil {
t.Fatal(err)
} else if err := db0.Sync(t.Context()); err != nil {
t.Fatal(err)
} else if err := db0.Replica.Sync(t.Context()); err != nil {
t.Fatal(err)
}
_, err := s.CompactDB(t.Context(), db0, levels[1])
require.NoError(t, err)
// Re-compacting immediately should return an error indicating compaction
// cannot proceed. This may be ErrCompactionTooEarly (detected timing conflict)
// or ErrNoCompaction (no new files to compact). Both are valid outcomes
// depending on whether we crossed a second boundary during the first compaction
// (PrevCompactionAt truncates to seconds, causing edge cases at boundaries).
_, err = s.CompactDB(t.Context(), db0, levels[1])
require.True(t,
errors.Is(err, litestream.ErrCompactionTooEarly) || errors.Is(err, litestream.ErrNoCompaction),
"expected ErrCompactionTooEarly or ErrNoCompaction, got: %v", err)
// Re-compacting after the interval should show that there is nothing to compact.
time.Sleep(levels[1].Interval)
_, err = s.CompactDB(t.Context(), db0, levels[1])
require.ErrorIs(t, err, litestream.ErrNoCompaction)
})
t.Run("Snapshot", func(t *testing.T) {
db0, sqldb0 := testingutil.MustOpenDBs(t)
defer testingutil.MustCloseDBs(t, db0, sqldb0)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1, Interval: 100 * time.Millisecond},
{Level: 2, Interval: 500 * time.Millisecond},
}
s := litestream.NewStore([]*litestream.DB{db0}, levels)
s.CompactionMonitorEnabled = false
if err := s.Open(t.Context()); err != nil {
t.Fatal(err)
}
defer s.Close(t.Context())
if _, err := sqldb0.ExecContext(t.Context(), `CREATE TABLE t (id INT);`); err != nil {
t.Fatal(err)
}
if _, err := sqldb0.ExecContext(t.Context(), `INSERT INTO t (id) VALUES (100)`); err != nil {
t.Fatal(err)
} else if err := db0.Sync(t.Context()); err != nil {
t.Fatal(err)
} else if err := db0.Replica.Sync(t.Context()); err != nil {
t.Fatal(err)
}
if _, err := s.CompactDB(t.Context(), db0, s.SnapshotLevel()); err != nil {
t.Fatal(err)
}
// Re-compacting immediately should return an error that there's nothing to compact.
if _, err := s.CompactDB(t.Context(), db0, s.SnapshotLevel()); !errors.Is(err, litestream.ErrCompactionTooEarly) {
t.Fatalf("unexpected error: %s", err)
}
})
// Regression test for GitHub issue #877: level 9 compaction fails with
// "page size not initialized yet" error when attempted before DB initialization.
t.Run("DBNotReady", func(t *testing.T) {
db0 := testingutil.MustOpenDB(t)
defer testingutil.MustCloseDB(t, db0)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1, Interval: 100 * time.Millisecond},
}
s := litestream.NewStore([]*litestream.DB{db0}, levels)
s.CompactionMonitorEnabled = false
if err := s.Open(t.Context()); err != nil {
t.Fatal(err)
}
defer s.Close(t.Context())
// Attempt snapshot before DB is initialized (page size not set).
// This reproduces the timing issue where level 9 compaction fires
// immediately at startup before db.Sync() has been called.
if _, err := s.CompactDB(t.Context(), db0, s.SnapshotLevel()); !errors.Is(err, litestream.ErrDBNotReady) {
t.Fatalf("expected ErrDBNotReady, got: %v", err)
}
})
}
func TestStore_Integration(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test in short mode")
}
const factor = 1
db := testingutil.NewDB(t, filepath.Join(t.TempDir(), "db"))
db.MonitorInterval = factor * 100 * time.Millisecond
db.Replica = litestream.NewReplica(db)
db.Replica.Client = file.NewReplicaClient(t.TempDir())
if err := db.Open(); err != nil {
t.Fatal(err)
}
sqldb := testingutil.MustOpenSQLDB(t, db.Path())
defer testingutil.MustCloseSQLDB(t, sqldb)
store := litestream.NewStore([]*litestream.DB{db}, litestream.CompactionLevels{
{Level: 0},
{Level: 1, Interval: factor * 200 * time.Millisecond},
{Level: 2, Interval: factor * 500 * time.Millisecond},
})
store.SnapshotInterval = factor * 1 * time.Second
if err := store.Open(t.Context()); err != nil {
t.Fatal(err)
}
defer store.Close(t.Context())
// Create initial table
if _, err := sqldb.ExecContext(t.Context(), `CREATE TABLE t (id INTEGER PRIMARY KEY, val TEXT);`); err != nil {
t.Fatal(err)
}
// Run test for a fixed duration.
done := make(chan struct{})
time.AfterFunc(10*time.Second, func() { close(done) })
// Channel for insert errors
insertErr := make(chan error, 1)
// WaitGroup to ensure insert goroutine completes before cleanup
var wg sync.WaitGroup
// Wait for insert goroutine to finish before cleanup & surface any errors.
defer func() {
wg.Wait()
select {
case err := <-insertErr:
t.Fatalf("insert error during test: %v", err)
default:
// No insert errors
}
}()
// Start goroutine to continuously insert records
wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(factor * 10 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-t.Context().Done():
return
case <-done:
return
case <-ticker.C:
if _, err := sqldb.ExecContext(t.Context(), `INSERT INTO t (val) VALUES (?);`, time.Now().String()); err != nil {
// Check if we're shutting down
select {
case <-done:
// Expected during shutdown, just exit
return
default:
// Real error, send it
select {
case insertErr <- err:
default:
}
return
}
}
}
}
}()
// Periodically snapshot, restore and validate
ticker := time.NewTicker(factor * 500 * time.Millisecond)
defer ticker.Stop()
for i := 0; ; i++ {
select {
case <-t.Context().Done():
return
case <-done:
return
case <-ticker.C:
// Restore database to a temporary location.
outputPath := filepath.Join(t.TempDir(), fmt.Sprintf("restore-%d.db", i))
if err := db.Replica.Restore(t.Context(), litestream.RestoreOptions{
OutputPath: outputPath,
}); err != nil {
t.Fatal(err)
}
func() {
restoreDB := testingutil.MustOpenSQLDB(t, outputPath)
defer testingutil.MustCloseSQLDB(t, restoreDB)
var result string
if err := restoreDB.QueryRowContext(t.Context(), `PRAGMA integrity_check;`).Scan(&result); err != nil {
t.Fatal(err)
} else if result != "ok" {
t.Fatalf("integrity check failed: %s", result)
}
var count int
if err := restoreDB.QueryRowContext(t.Context(), `SELECT COUNT(*) FROM t`).Scan(&count); err != nil {
t.Fatal(err)
} else if count == 0 {
t.Fatal("no records found in restored database")
}
t.Logf("restored database: %d records", count)
}()
}
}
}
// TestStore_SnapshotInterval_Default ensures that the default snapshot interval
// is preserved when not explicitly set (regression test for issue #689).
func TestStore_SnapshotInterval_Default(t *testing.T) {
// Create a store with no databases and no levels
store := litestream.NewStore(nil, nil)
// Verify default snapshot interval is set
if store.SnapshotInterval != litestream.DefaultSnapshotInterval {
t.Errorf("expected default snapshot interval of %v, got %v",
litestream.DefaultSnapshotInterval, store.SnapshotInterval)
}
// Verify default is 24 hours
if store.SnapshotInterval != 24*time.Hour {
t.Errorf("expected default snapshot interval of 24h, got %v",
store.SnapshotInterval)
}
}
func TestStore_Validate(t *testing.T) {
t.Run("AllLevelsValid", func(t *testing.T) {
client := file.NewReplicaClient(t.TempDir())
db := &litestream.DB{}
db.Replica = litestream.NewReplicaWithClient(db, client)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1},
}
store := litestream.NewStore([]*litestream.DB{db}, levels)
// Create contiguous files at L0
createTestLTXFile(t, client, 0, 1, 1)
createTestLTXFile(t, client, 0, 2, 2)
// Create contiguous files at L1
createTestLTXFile(t, client, 1, 1, 2)
result, err := store.Validate(t.Context())
if err != nil {
t.Fatal(err)
}
if !result.Valid {
t.Errorf("expected valid result, got errors: %v", result.Errors)
}
})
t.Run("ErrorAtMultipleLevels", func(t *testing.T) {
client := file.NewReplicaClient(t.TempDir())
db := &litestream.DB{}
db.Replica = litestream.NewReplicaWithClient(db, client)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1},
}
store := litestream.NewStore([]*litestream.DB{db}, levels)
// Create files with gap at L0
createTestLTXFile(t, client, 0, 1, 1)
createTestLTXFile(t, client, 0, 5, 5) // gap at 2-4
// Create files with overlap at L1
createTestLTXFile(t, client, 1, 1, 5)
createTestLTXFile(t, client, 1, 3, 7) // overlap
result, err := store.Validate(t.Context())
if err != nil {
t.Fatal(err)
}
if result.Valid {
t.Error("expected invalid result")
}
if len(result.Errors) != 2 {
t.Errorf("expected 2 errors, got %d", len(result.Errors))
}
})
t.Run("NilReplica", func(t *testing.T) {
// DB with nil replica should be skipped
db := &litestream.DB{}
// db.Replica is nil
levels := litestream.CompactionLevels{
{Level: 0},
}
store := litestream.NewStore([]*litestream.DB{db}, levels)
result, err := store.Validate(t.Context())
if err != nil {
t.Fatal(err)
}
if !result.Valid {
t.Errorf("expected valid result for nil replica, got errors: %v", result.Errors)
}
})
t.Run("MultipleDBs", func(t *testing.T) {
client1 := file.NewReplicaClient(t.TempDir())
client2 := file.NewReplicaClient(t.TempDir())
db1 := &litestream.DB{}
db1.Replica = litestream.NewReplicaWithClient(db1, client1)
db2 := &litestream.DB{}
db2.Replica = litestream.NewReplicaWithClient(db2, client2)
levels := litestream.CompactionLevels{
{Level: 0},
}
store := litestream.NewStore([]*litestream.DB{db1, db2}, levels)
// db1: valid
createTestLTXFile(t, client1, 0, 1, 1)
createTestLTXFile(t, client1, 0, 2, 2)
// db2: gap error
createTestLTXFile(t, client2, 0, 1, 1)
createTestLTXFile(t, client2, 0, 5, 5)
result, err := store.Validate(t.Context())
if err != nil {
t.Fatal(err)
}
if result.Valid {
t.Error("expected invalid result")
}
if len(result.Errors) != 1 {
t.Errorf("expected 1 error from db2, got %d", len(result.Errors))
}
})
}
func TestStore_ValidationMonitor(t *testing.T) {
t.Run("RunsPeriodically", func(t *testing.T) {
db, sqldb := testingutil.MustOpenDBs(t)
defer testingutil.MustCloseDBs(t, db, sqldb)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1, Interval: time.Hour},
}
store := litestream.NewStore([]*litestream.DB{db}, levels)
store.CompactionMonitorEnabled = false
store.ValidationInterval = 50 * time.Millisecond
if err := store.Open(t.Context()); err != nil {
t.Fatal(err)
}
// Wait for at least one validation cycle
time.Sleep(100 * time.Millisecond)
if err := store.Close(t.Context()); err != nil {
t.Fatal(err)
}
})
t.Run("DisabledByDefault", func(t *testing.T) {
levels := litestream.CompactionLevels{
{Level: 0},
}
store := litestream.NewStore(nil, levels)
store.CompactionMonitorEnabled = false
// ValidationInterval should be zero by default
if store.ValidationInterval != 0 {
t.Errorf("expected ValidationInterval=0, got %v", store.ValidationInterval)
}
// Open should succeed without starting validation monitor
if err := store.Open(t.Context()); err != nil {
t.Fatal(err)
}
if err := store.Close(t.Context()); err != nil {
t.Fatal(err)
}
})
}
func TestStore_SetRetentionEnabled(t *testing.T) {
db0, sqldb0 := testingutil.MustOpenDBs(t)
defer testingutil.MustCloseDBs(t, db0, sqldb0)
db1, sqldb1 := testingutil.MustOpenDBs(t)
defer testingutil.MustCloseDBs(t, db1, sqldb1)
levels := litestream.CompactionLevels{
{Level: 0},
{Level: 1, Interval: time.Hour},
}
store := litestream.NewStore([]*litestream.DB{db0, db1}, levels)
store.CompactionMonitorEnabled = false
// Initially should be true (retention enabled by default).
if !store.RetentionEnabled {
t.Fatal("expected RetentionEnabled=true initially")
}
// Set to false and verify propagation to all DBs.
store.SetRetentionEnabled(false)
if store.RetentionEnabled {
t.Fatal("expected store.RetentionEnabled=false")
}
for _, db := range store.DBs() {
if db.RetentionEnabled {
t.Fatalf("expected db.RetentionEnabled=false for %s", db.Path())
}
}
// Set back to true.
store.SetRetentionEnabled(true)
if !store.RetentionEnabled {
t.Fatal("expected store.RetentionEnabled=true after reset")
}
for _, db := range store.DBs() {
if !db.RetentionEnabled {
t.Fatalf("expected db.RetentionEnabled=true for %s after reset", db.Path())
}
}
}