-
Notifications
You must be signed in to change notification settings - Fork 347
Expand file tree
/
Copy pathdb.go
More file actions
2489 lines (2129 loc) · 77.9 KB
/
db.go
File metadata and controls
2489 lines (2129 loc) · 77.9 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package litestream
import (
"bytes"
"context"
"database/sql"
"encoding/binary"
"errors"
"fmt"
"hash/crc64"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/superfly/ltx"
"modernc.org/sqlite"
"github.com/benbjohnson/litestream/internal"
)
// Default DB settings.
const (
DefaultMonitorInterval = 1 * time.Second
DefaultCheckpointInterval = 1 * time.Minute
DefaultBusyTimeout = 1 * time.Second
DefaultMinCheckpointPageN = 1000
DefaultTruncatePageN = 121359 // ~500MB with 4KB page size
DefaultShutdownSyncTimeout = 30 * time.Second
DefaultShutdownSyncInterval = 500 * time.Millisecond
// Sync error backoff configuration.
// When sync errors occur repeatedly (e.g., disk full), backoff doubles each time.
DefaultSyncBackoffMax = 5 * time.Minute // Maximum backoff between retries
SyncErrorLogInterval = 30 * time.Second // Rate-limit repeated error logging
)
// DB represents a managed instance of a SQLite database in the file system.
//
// Checkpoint Strategy:
// Litestream uses a progressive 3-tier checkpoint approach to balance WAL size
// management with write availability:
//
// 1. MinCheckpointPageN (PASSIVE): Non-blocking checkpoint at ~1k pages (~4MB).
// Attempts checkpoint but allows concurrent readers/writers.
//
// 2. CheckpointInterval (PASSIVE): Time-based non-blocking checkpoint.
// Ensures regular checkpointing even with low write volume.
//
// 3. TruncatePageN (TRUNCATE): Blocking checkpoint at ~121k pages (~500MB).
// Emergency brake for runaway WAL growth. Can block writes while waiting
// for long-lived read transactions. Configurable/disableable.
//
// The RESTART checkpoint mode was permanently removed due to production issues
// with indefinite write blocking (issue #724). All checkpoints now use either
// PASSIVE (non-blocking) or TRUNCATE (emergency only) modes.
type DB struct {
mu sync.RWMutex
path string // part to database
metaPath string // Path to the database metadata.
db *sql.DB // target database
f *os.File // long-running db file descriptor
rtx *sql.Tx // long running read transaction
pageSize int // page size, in bytes
notify chan struct{} // closes on WAL change
chkMu sync.RWMutex // checkpoint lock
opened bool // true if Open() was called and Close() not yet called
// syncedSinceCheckpoint tracks whether any data has been synced since
// the last checkpoint. Used to prevent time-based checkpoints from
// triggering when there are no actual database changes, which would
// otherwise create unnecessary LTX files. See issue #896.
syncedSinceCheckpoint bool
// syncedToWALEnd tracks whether the last successful sync reached the
// exact end of the WAL file. When true, a subsequent WAL truncation
// (from checkpoint) is expected and should NOT trigger a full snapshot.
// This prevents issue #927 where every checkpoint triggers unnecessary
// full snapshots because verify() sees the old LTX position exceeds
// the new (truncated) WAL size.
syncedToWALEnd bool
// lastSyncedWALOffset tracks the logical end of the WAL content after
// the last successful sync. This is the WALOffset + WALSize from the
// last LTX file. Used for checkpoint threshold decisions instead of
// file size, which may include stale frames with old salt values after
// a checkpoint. This prevents issue #997 where PASSIVE checkpoints
// trigger a feedback loop because stale file size exceeds threshold.
lastSyncedWALOffset int64
// forceNextSnapshot forces the next verify() call to return
// snapshotting=true. Set by checkpoint() when the WAL restarts during
// checkpointing, which indicates external writes may have been
// auto-checkpointed to the DB while the read lock was released.
// Those pages would not be in the new WAL or any LTX file, so a full
// snapshot is needed to ensure complete coverage.
forceNextSnapshot bool
// last file info for each level
maxLTXFileInfos struct {
sync.Mutex
m map[int]*ltx.FileInfo
}
fileInfo os.FileInfo // db info cached during init
dirInfo os.FileInfo // parent dir info cached during init
ctx context.Context
cancel func()
wg sync.WaitGroup
Done <-chan struct{}
// Metrics
dbSizeGauge prometheus.Gauge
walSizeGauge prometheus.Gauge
totalWALBytesCounter prometheus.Counter
txIDGauge prometheus.Gauge
syncNCounter prometheus.Counter
syncErrorNCounter prometheus.Counter
syncSecondsCounter prometheus.Counter
checkpointNCounterVec *prometheus.CounterVec
checkpointErrorNCounterVec *prometheus.CounterVec
checkpointSecondsCounterVec *prometheus.CounterVec
// Minimum threshold of WAL size, in pages, before a passive checkpoint.
// A passive checkpoint will attempt a checkpoint but fail if there are
// active transactions occurring at the same time.
//
// Uses PASSIVE checkpoint mode (non-blocking). Keeps WAL size manageable
// for faster restores. Default: 1000 pages (~4MB with 4KB page size).
MinCheckpointPageN int
// Threshold of WAL size, in pages, before a forced truncation checkpoint.
// A forced truncation checkpoint will block new transactions and wait for
// existing transactions to finish before issuing a checkpoint and
// truncating the WAL.
//
// Uses TRUNCATE checkpoint mode (blocking). Prevents unbounded WAL growth
// from long-lived read transactions. Default: 121359 pages (~500MB with 4KB
// page size). Set to 0 to disable forced truncation (use with caution as
// WAL can grow unbounded if read transactions prevent checkpointing).
TruncatePageN int
// Time between automatic checkpoints in the WAL. This is done to allow
// more fine-grained WAL files so that restores can be performed with
// better precision.
//
// Uses PASSIVE checkpoint mode (non-blocking). Default: 1 minute.
// Set to 0 to disable time-based checkpoints.
CheckpointInterval time.Duration
// Frequency at which to perform db sync.
MonitorInterval time.Duration
// The timeout to wait for EBUSY from SQLite.
BusyTimeout time.Duration
// Minimum time to retain L0 files after they have been compacted into L1.
L0Retention time.Duration
// VerifyCompaction enables post-compaction TXID consistency verification.
// When enabled, verifies that files at the destination level have
// contiguous TXID ranges after each compaction.
VerifyCompaction bool
// RetentionEnabled controls whether Litestream actively deletes old files
// during retention enforcement. When false, cloud provider lifecycle
// policies handle retention instead. Local file cleanup still occurs.
RetentionEnabled bool
// Remote replica for the database.
// Must be set before calling Open().
Replica *Replica
// Compactor handles shared compaction logic.
// Created in NewDB with nil client; client set once in Open() from Replica.Client.
compactor *Compactor
// Shutdown sync retry settings.
// ShutdownSyncTimeout is the total time to retry syncing on shutdown.
// ShutdownSyncInterval is the time between retry attempts.
ShutdownSyncTimeout time.Duration
ShutdownSyncInterval time.Duration
// lastSuccessfulSyncAt tracks when replication last succeeded.
// Used by heartbeat monitoring to determine if a ping should be sent.
lastSuccessfulSyncMu sync.RWMutex
lastSuccessfulSyncAt time.Time
// Where to send log messages, defaults to global slog with database epath.
Logger *slog.Logger
}
// NewDB returns a new instance of DB for a given path.
func NewDB(path string) *DB {
dir, file := filepath.Split(path)
db := &DB{
path: path,
metaPath: filepath.Join(dir, "."+file+MetaDirSuffix),
notify: make(chan struct{}),
MinCheckpointPageN: DefaultMinCheckpointPageN,
TruncatePageN: DefaultTruncatePageN,
CheckpointInterval: DefaultCheckpointInterval,
MonitorInterval: DefaultMonitorInterval,
BusyTimeout: DefaultBusyTimeout,
L0Retention: DefaultL0Retention,
RetentionEnabled: true,
ShutdownSyncTimeout: DefaultShutdownSyncTimeout,
ShutdownSyncInterval: DefaultShutdownSyncInterval,
Logger: slog.With("db", filepath.Base(path)),
}
db.maxLTXFileInfos.m = make(map[int]*ltx.FileInfo)
db.dbSizeGauge = dbSizeGaugeVec.WithLabelValues(db.path)
db.walSizeGauge = walSizeGaugeVec.WithLabelValues(db.path)
db.totalWALBytesCounter = totalWALBytesCounterVec.WithLabelValues(db.path)
db.txIDGauge = txIDIndexGaugeVec.WithLabelValues(db.path)
db.syncNCounter = syncNCounterVec.WithLabelValues(db.path)
db.syncErrorNCounter = syncErrorNCounterVec.WithLabelValues(db.path)
db.syncSecondsCounter = syncSecondsCounterVec.WithLabelValues(db.path)
db.checkpointNCounterVec = checkpointNCounterVec.MustCurryWith(prometheus.Labels{"db": db.path})
db.checkpointErrorNCounterVec = checkpointErrorNCounterVec.MustCurryWith(prometheus.Labels{"db": db.path})
db.checkpointSecondsCounterVec = checkpointSecondsCounterVec.MustCurryWith(prometheus.Labels{"db": db.path})
db.ctx, db.cancel = context.WithCancel(context.Background())
// Initialize compactor with nil client (set once in Open() from Replica.Client).
db.compactor = NewCompactor(nil, db.Logger)
db.compactor.LocalFileOpener = db.openLocalLTXFile
db.compactor.LocalFileDeleter = db.deleteLocalLTXFile
db.compactor.CompactionVerifyErrorCounter = compactionVerifyErrorCounterVec.WithLabelValues(db.path)
db.compactor.CacheGetter = func(level int) (*ltx.FileInfo, bool) {
db.maxLTXFileInfos.Lock()
defer db.maxLTXFileInfos.Unlock()
info, ok := db.maxLTXFileInfos.m[level]
return info, ok
}
db.compactor.CacheSetter = func(level int, info *ltx.FileInfo) {
db.maxLTXFileInfos.Lock()
defer db.maxLTXFileInfos.Unlock()
db.maxLTXFileInfos.m[level] = info
}
return db
}
// SQLDB returns a reference to the underlying sql.DB connection.
func (db *DB) SQLDB() *sql.DB {
return db.db
}
// Path returns the path to the database.
func (db *DB) Path() string {
return db.path
}
// IsOpen returns true if the database has been opened.
func (db *DB) IsOpen() bool {
db.mu.RLock()
defer db.mu.RUnlock()
return db.opened
}
// WALPath returns the path to the database's WAL file.
func (db *DB) WALPath() string {
return db.path + "-wal"
}
func (db *DB) shmPath() string {
return db.path + "-shm"
}
// MetaPath returns the path to the database metadata.
func (db *DB) MetaPath() string {
return db.metaPath
}
// SetMetaPath sets the path to database metadata.
func (db *DB) SetMetaPath(path string) {
db.metaPath = path
}
// LTXDir returns path of the root LTX directory.
func (db *DB) LTXDir() string {
return filepath.Join(db.metaPath, "ltx")
}
// ResetLocalState removes local LTX files, forcing a fresh snapshot on next sync.
// This is useful for recovering from corrupted or missing LTX files.
// The database file itself is not modified.
func (db *DB) ResetLocalState(ctx context.Context) error {
db.Logger.Info("resetting local litestream state",
"meta_path", db.metaPath,
"ltx_dir", db.LTXDir())
// Remove all LTX files
if err := os.RemoveAll(db.LTXDir()); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("remove ltx directory: %w", err)
}
// Clear cached LTX file info
db.maxLTXFileInfos.Lock()
db.maxLTXFileInfos.m = make(map[int]*ltx.FileInfo)
db.maxLTXFileInfos.Unlock()
db.Logger.Info("local state reset complete, next sync will create fresh snapshot")
return nil
}
// LTXLevelDir returns path of the given LTX compaction level.
// Panics if level is negative.
func (db *DB) LTXLevelDir(level int) string {
return filepath.Join(db.LTXDir(), strconv.Itoa(level))
}
// LTXPath returns the local path of a single LTX file.
// Panics if level or either txn ID is negative.
func (db *DB) LTXPath(level int, minTXID, maxTXID ltx.TXID) string {
assert(level >= 0, "level cannot be negative")
return filepath.Join(db.LTXLevelDir(level), ltx.FormatFilename(minTXID, maxTXID))
}
// openLocalLTXFile opens a local LTX file for reading.
// Used by the Compactor to prefer local files over remote.
func (db *DB) openLocalLTXFile(level int, minTXID, maxTXID ltx.TXID) (io.ReadCloser, error) {
return os.Open(db.LTXPath(level, minTXID, maxTXID))
}
// deleteLocalLTXFile deletes a local LTX file.
// Used by the Compactor for retention enforcement.
func (db *DB) deleteLocalLTXFile(level int, minTXID, maxTXID ltx.TXID) error {
path := db.LTXPath(level, minTXID, maxTXID)
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
// MaxLTX returns the last LTX file written to level 0.
func (db *DB) MaxLTX() (minTXID, maxTXID ltx.TXID, err error) {
ents, err := os.ReadDir(db.LTXLevelDir(0))
if os.IsNotExist(err) {
return 0, 0, nil // no LTX files written
} else if err != nil {
return 0, 0, err
}
// Find highest txn ID.
for _, ent := range ents {
if min, max, err := ltx.ParseFilename(ent.Name()); err != nil {
continue // invalid LTX filename
} else if max > maxTXID {
minTXID, maxTXID = min, max
}
}
return minTXID, maxTXID, nil
}
// FileInfo returns the cached file stats for the database file when it was initialized.
func (db *DB) FileInfo() os.FileInfo {
return db.fileInfo
}
// DirInfo returns the cached file stats for the parent directory of the database file when it was initialized.
func (db *DB) DirInfo() os.FileInfo {
return db.dirInfo
}
// Pos returns the current replication position of the database.
func (db *DB) Pos() (ltx.Pos, error) {
minTXID, maxTXID, err := db.MaxLTX()
if err != nil {
return ltx.Pos{}, err
} else if minTXID == 0 {
return ltx.Pos{}, nil // no replication yet
}
f, err := os.Open(db.LTXPath(0, minTXID, maxTXID))
if err != nil {
return ltx.Pos{}, err
}
defer func() { _ = f.Close() }()
dec := ltx.NewDecoder(f)
if err := dec.Verify(); err != nil {
return ltx.Pos{}, fmt.Errorf("ltx verification failed: %w", err)
}
return dec.PostApplyPos(), nil
}
// Notify returns a channel that closes when the shadow WAL changes.
func (db *DB) Notify() <-chan struct{} {
db.mu.RLock()
defer db.mu.RUnlock()
return db.notify
}
// PageSize returns the page size of the underlying database.
// Only valid after database exists & Init() has successfully run.
func (db *DB) PageSize() int {
db.mu.RLock()
defer db.mu.RUnlock()
return db.pageSize
}
// RecordSuccessfulSync marks the current time as a successful sync.
// Used by heartbeat monitoring to determine if a ping should be sent.
func (db *DB) RecordSuccessfulSync() {
db.lastSuccessfulSyncMu.Lock()
defer db.lastSuccessfulSyncMu.Unlock()
db.lastSuccessfulSyncAt = time.Now()
}
// LastSuccessfulSyncAt returns the time of the last successful sync.
func (db *DB) LastSuccessfulSyncAt() time.Time {
db.lastSuccessfulSyncMu.RLock()
defer db.lastSuccessfulSyncMu.RUnlock()
return db.lastSuccessfulSyncAt
}
// SyncStatus represents the current replication state of the database.
type SyncStatus struct {
LocalTXID ltx.TXID
RemoteTXID ltx.TXID
InSync bool
}
// SyncStatus returns the current replication status of the database, comparing
// the local transaction position against the remote replica position. The remote
// position is queried from the replica storage, so this method may perform I/O.
func (db *DB) SyncStatus(ctx context.Context) (SyncStatus, error) {
if db.Replica == nil {
return SyncStatus{}, fmt.Errorf("no replica configured")
}
localPos, err := db.Pos()
if err != nil {
return SyncStatus{}, fmt.Errorf("local position: %w", err)
}
remotePos, err := db.Replica.calcPos(ctx)
if err != nil {
return SyncStatus{}, fmt.Errorf("remote position: %w", err)
}
return SyncStatus{
LocalTXID: localPos.TXID,
RemoteTXID: remotePos.TXID,
InSync: localPos.TXID > 0 && localPos.TXID == remotePos.TXID,
}, nil
}
// SyncAndWait performs a full sync: WAL to LTX files, then LTX files to remote
// replica. Blocks until both stages complete.
func (db *DB) SyncAndWait(ctx context.Context) error {
if db.Replica == nil {
return fmt.Errorf("no replica configured")
}
if err := db.Sync(ctx); err != nil {
return fmt.Errorf("db sync: %w", err)
}
if err := db.Replica.Sync(ctx); err != nil {
return fmt.Errorf("replica sync: %w", err)
}
return nil
}
// EnsureExists restores the database from the configured replica if the local
// database file does not exist. If no backup is available, it returns nil and
// a fresh database will be created on Open(). Must be called before Open().
func (db *DB) EnsureExists(ctx context.Context) error {
if db.Replica == nil {
return fmt.Errorf("no replica configured")
}
if db.Replica.Client == nil {
return fmt.Errorf("no replica client configured")
}
if _, err := os.Stat(db.Path()); err == nil {
return nil
} else if !os.IsNotExist(err) {
return fmt.Errorf("stat database: %w", err)
}
if dir := filepath.Dir(db.Path()); dir != "." {
if err := os.MkdirAll(dir, 0o750); err != nil {
return fmt.Errorf("create parent directory: %w", err)
}
}
opt := NewRestoreOptions()
opt.OutputPath = db.Path()
if err := db.Replica.Restore(ctx, opt); err != nil {
if errors.Is(err, ErrTxNotAvailable) || errors.Is(err, ErrNoSnapshots) {
db.Logger.Debug("no backup found, will create fresh database")
return nil
}
return fmt.Errorf("restore from backup: %w", err)
}
db.Logger.Info("database restored from backup", "path", db.Path())
return nil
}
// Open initializes the background monitoring goroutine.
func (db *DB) Open() (err error) {
db.mu.Lock()
if db.opened {
db.mu.Unlock()
return nil // already open
}
// Recreate context for fresh start (handles reopen after close)
db.ctx, db.cancel = context.WithCancel(context.Background())
db.mu.Unlock()
// Validate fields on database.
if db.Replica == nil {
return fmt.Errorf("replica required before opening database")
}
if db.Replica.Client == nil {
return fmt.Errorf("replica client required before opening database")
}
if db.MinCheckpointPageN <= 0 {
return fmt.Errorf("minimum checkpoint page count required")
}
// Clear old temporary files that my have been left from a crash.
if err := removeTmpFiles(db.metaPath); err != nil {
return fmt.Errorf("cannot remove tmp files: %w", err)
}
// Set the compactor client once before starting any goroutines.
db.compactor.VerifyCompaction = db.VerifyCompaction
db.compactor.RetentionEnabled = db.RetentionEnabled
db.compactor.client = db.Replica.Client
// Start monitoring SQLite database in a separate goroutine.
if db.MonitorInterval > 0 {
db.wg.Add(1)
go func() { defer db.wg.Done(); db.monitor() }()
}
// Mark as opened only after successful initialization.
db.mu.Lock()
db.opened = true
db.mu.Unlock()
return nil
}
// Close flushes outstanding WAL writes to replicas, releases the read lock,
// and closes the database. If Done is set, closing it interrupts the shutdown
// sync retry loop and cancels any in-flight sync attempt.
func (db *DB) Close(ctx context.Context) (err error) {
db.cancel()
db.wg.Wait()
// Perform a final db sync, if initialized.
if db.db != nil {
if e := db.Sync(ctx); e != nil {
err = e
}
}
// Ensure replicas perform a final sync and stop replicating.
if db.Replica != nil {
if db.db != nil {
if e := db.syncReplicaWithRetry(ctx); e != nil && err == nil {
err = e
}
}
db.Replica.Stop(true)
}
// Release the read lock to allow other applications to handle checkpointing.
if db.rtx != nil {
if e := db.releaseReadLock(); e != nil && err == nil {
err = e
}
}
if db.db != nil {
if e := db.db.Close(); e != nil && err == nil {
err = e
}
db.db = nil
}
if db.f != nil {
if e := db.f.Close(); e != nil && err == nil {
err = e
}
db.f = nil
}
db.mu.Lock()
db.opened = false
db.rtx = nil
db.mu.Unlock()
return err
}
// syncReplicaWithRetry attempts to sync the replica with retry logic for shutdown.
// It retries until success, timeout, or context cancellation. If db.Done is non-nil,
// closing it cancels any in-flight sync attempt and exits the retry loop.
// If ShutdownSyncTimeout is 0, it performs a single sync attempt without retries.
func (db *DB) syncReplicaWithRetry(ctx context.Context) error {
if db.Replica == nil {
return nil
}
timeout := db.ShutdownSyncTimeout
interval := db.ShutdownSyncInterval
// If timeout is zero, just try once (no retry)
if timeout == 0 {
return db.Replica.Sync(ctx)
}
// Use default interval if not set
if interval == 0 {
interval = DefaultShutdownSyncInterval
}
// Create deadline context for total retry duration.
deadlineCtx, deadlineCancel := context.WithTimeout(ctx, timeout)
defer deadlineCancel()
// If db.Done is set, derive a context that cancels when done is closed
// so that in-flight Replica.Sync calls are interrupted immediately.
syncCtx := deadlineCtx
if db.Done != nil {
var syncCancel context.CancelFunc
syncCtx, syncCancel = context.WithCancel(deadlineCtx)
go func() {
select {
case <-db.Done:
syncCancel()
case <-deadlineCtx.Done():
syncCancel()
}
}()
}
var lastErr error
attempt := 0
startTime := time.Now()
for {
// Check if done is already closed before attempting sync
if db.Done != nil {
select {
case <-db.Done:
db.Logger.Warn("shutdown sync skipped, interrupted by signal",
"attempts", attempt,
"duration", time.Since(startTime))
return fmt.Errorf("after %d attempts: %w", attempt, ErrShutdownInterrupted)
default:
}
}
attempt++
// Try sync
if err := db.Replica.Sync(syncCtx); err == nil {
if attempt > 1 {
db.Logger.Info("shutdown sync succeeded after retry",
"attempts", attempt,
"duration", time.Since(startTime))
}
return nil
} else {
lastErr = err
}
// Check if we should stop retrying (done signal or timeout)
select {
case <-deadlineCtx.Done():
db.Logger.Error("shutdown sync failed after timeout",
"attempts", attempt,
"duration", time.Since(startTime),
"error", lastErr)
return fmt.Errorf("shutdown sync timeout after %d attempts: %w", attempt, lastErr)
case <-db.Done:
db.Logger.Warn("shutdown sync interrupted by signal",
"attempts", attempt,
"duration", time.Since(startTime),
"error", lastErr)
return fmt.Errorf("after %d attempts: %w", attempt, ErrShutdownInterrupted)
default:
}
// Log retry with hint about second signal if interruptible
if db.Done != nil {
db.Logger.Warn("shutdown sync failed, retrying (press Ctrl+C again to skip)",
"attempts", attempt,
"error", lastErr,
"elapsed", time.Since(startTime),
"remaining", time.Until(startTime.Add(timeout)))
} else {
db.Logger.Warn("shutdown sync failed, retrying",
"attempts", attempt,
"error", lastErr,
"elapsed", time.Since(startTime),
"remaining", time.Until(startTime.Add(timeout)))
}
// Wait before retry, but also listen for done signal
select {
case <-time.After(interval):
case <-deadlineCtx.Done():
return fmt.Errorf("shutdown sync timeout after %d attempts: %w", attempt, lastErr)
case <-db.Done:
db.Logger.Warn("shutdown sync interrupted by signal",
"attempts", attempt,
"duration", time.Since(startTime))
return fmt.Errorf("after %d attempts: %w", attempt, ErrShutdownInterrupted)
}
}
}
// setPersistWAL sets the PERSIST_WAL file control on the database connection.
// This prevents SQLite from removing the WAL file when connections close.
func (db *DB) setPersistWAL(ctx context.Context) error {
conn, err := db.db.Conn(ctx)
if err != nil {
return fmt.Errorf("get connection: %w", err)
}
defer conn.Close()
return conn.Raw(func(driverConn interface{}) error {
fc, ok := driverConn.(sqlite.FileControl)
if !ok {
return fmt.Errorf("driver does not implement FileControl")
}
_, err := fc.FileControlPersistWAL("main", 1)
if err != nil {
return fmt.Errorf("FileControlPersistWAL: %w", err)
}
return nil
})
}
// init initializes the connection to the database.
// Skipped if already initialized or if the database file does not exist.
func (db *DB) init(ctx context.Context) (err error) {
// Exit if already initialized.
if db.db != nil {
return nil
}
// Exit if no database file exists.
fi, err := os.Stat(db.path)
if os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
db.fileInfo = fi
// Obtain permissions for parent directory.
if fi, err = os.Stat(filepath.Dir(db.path)); err != nil {
return err
}
db.dirInfo = fi
dsn := fmt.Sprintf("file:%s?_pragma=busy_timeout(%d)&_pragma=wal_autocheckpoint(0)",
db.path, db.BusyTimeout.Milliseconds())
if db.db, err = sql.Open("sqlite", dsn); err != nil {
return err
}
// Set PERSIST_WAL to prevent WAL file removal when database connections close.
if err := db.setPersistWAL(ctx); err != nil {
return fmt.Errorf("set PERSIST_WAL: %w", err)
}
// Open long-running database file descriptor. Required for non-OFD locks.
if db.f, err = os.Open(db.path); err != nil {
return fmt.Errorf("open db file descriptor: %w", err)
}
// Ensure database is closed if init fails.
// Initialization can retry on next sync.
defer func() {
if err != nil {
_ = db.releaseReadLock()
db.db.Close()
db.f.Close()
db.db, db.f = nil, nil
}
}()
// Enable WAL and ensure it is set. New mode should be returned on success:
// https://www.sqlite.org/pragma.html#pragma_journal_mode
var mode string
if err := db.db.QueryRowContext(ctx, `PRAGMA journal_mode = wal;`).Scan(&mode); err != nil {
return err
} else if mode != "wal" {
return fmt.Errorf("enable wal failed, mode=%q", mode)
}
// Create a table to force writes to the WAL when empty.
// There should only ever be one row with id=1.
if _, err := db.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS _litestream_seq (id INTEGER PRIMARY KEY, seq INTEGER);`); err != nil {
return fmt.Errorf("create _litestream_seq table: %w", err)
}
// Create a lock table to force write locks during sync.
// The sync write transaction always rolls back so no data should be in this table.
if _, err := db.db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS _litestream_lock (id INTEGER);`); err != nil {
return fmt.Errorf("create _litestream_lock table: %w", err)
}
// Start a long-running read transaction to prevent other transactions
// from checkpointing.
if err := db.acquireReadLock(ctx); err != nil {
return fmt.Errorf("acquire read lock: %w", err)
}
// Read page size.
if err := db.db.QueryRowContext(ctx, `PRAGMA page_size;`).Scan(&db.pageSize); err != nil {
return fmt.Errorf("read page size: %w", err)
} else if db.pageSize <= 0 {
return fmt.Errorf("invalid db page size: %d", db.pageSize)
}
// Ensure meta directory structure exists.
if err := internal.MkdirAll(db.metaPath, db.dirInfo); err != nil {
return err
}
// Ensure WAL has at least one frame in it.
if err := db.ensureWALExists(ctx); err != nil {
return fmt.Errorf("ensure wal exists: %w", err)
}
// Check if database is behind replica (issue #781).
// This must happen before replica.Start() to detect restore scenarios.
if db.Replica != nil {
if err := db.checkDatabaseBehindReplica(ctx); err != nil {
return fmt.Errorf("check database behind replica: %w", err)
}
}
// If we have an existing replication files, ensure the headers match.
// if err := db.verifyHeadersMatch(); err != nil {
// return fmt.Errorf("cannot determine last wal position: %w", err)
// }
// TODO(gen): Generate diff of current LTX snapshot and save as next LTX file.
// Start replication.
if db.Replica != nil {
db.Replica.Start(db.ctx)
}
return nil
}
/*
// verifyHeadersMatch returns an error if
func (db *DB) verifyHeadersMatch() error {
pos, err := db.Pos()
if err != nil {
return false, fmt.Errorf("cannot determine position: %w", err)
} else if pos.TXID == 0 {
return true, nil // no replication performed yet
}
hdr0, err := readWALHeader(db.WALPath())
if os.IsNotExist(err) {
return false, fmt.Errorf("no wal: %w", err)
} else if err != nil {
return false, fmt.Errorf("read wal header: %w", err)
}
salt1 := binary.BigEndian.Uint32(hdr0[16:])
salt2 := binary.BigEndian.Uint32(hdr0[20:])
ltxPath := db.LTXPath(0, pos.TXID, pos.TXID)
f, err := os.Open(ltxPath)
if err != nil {
return false, fmt.Errorf("open ltx path: %w", err)
}
defer func() { _ = f.Close() }()
dec := ltx.NewDecoder(f)
if err := dec.DecodeHeader(); err != nil {
return false, fmt.Errorf("decode ltx header: %w", err)
}
hdr1 := dec.Header()
if salt1 != hdr1.WALSalt1 || salt2 != hdr1.WALSalt2 {
db.Logger.Log(internal.LevelTrace, "salt mismatch",
"path", ltxPath,
"wal", [2]uint32{salt1, salt2},
"ltx", [2]uint32{hdr1.WALSalt1, hdr1.WALSalt2})
return false, nil
}
return true, nil
}
*/
// acquireReadLock begins a read transaction on the database to prevent checkpointing.
func (db *DB) acquireReadLock(ctx context.Context) error {
if db.rtx != nil {
return nil
}
// Start long running read-transaction to prevent checkpoints.
tx, err := db.db.BeginTx(ctx, nil)
if err != nil {
return err
}
// Execute read query to obtain read lock.
if _, err := tx.ExecContext(ctx, `SELECT COUNT(1) FROM _litestream_seq;`); err != nil {
_ = tx.Rollback()
return err
}
// Track transaction so we can release it later before checkpoint.
db.rtx = tx
return nil
}
// releaseReadLock rolls back the long-running read transaction.
func (db *DB) releaseReadLock() error {
// Ignore if we do not have a read lock.
if db.rtx == nil {
return nil
}
// Rollback & clear read transaction.
// Use rollback() helper to suppress "already rolled back" errors that can
// occur during shutdown when concurrent checkpoint and close operations
// both attempt to release the read lock. See issue #934.
err := rollback(db.rtx)
db.rtx = nil
return err
}
// Sync copies pending data from the WAL to the shadow WAL.
func (db *DB) Sync(ctx context.Context) (err error) {
db.mu.Lock()
defer db.mu.Unlock()
// Track total sync metrics.
t := time.Now()
defer func() {
db.syncNCounter.Inc()
if err != nil {
db.syncErrorNCounter.Inc()
}
db.syncSecondsCounter.Add(float64(time.Since(t).Seconds()))
}()
// Initialize database, if necessary. Exit if no DB exists.
if err := db.init(ctx); err != nil {
return err
} else if db.db == nil {
db.Logger.Debug("sync: no database found")
return nil
}
// Ensure WAL has at least one frame in it.
if err := db.ensureWALExists(ctx); err != nil {
return fmt.Errorf("ensure wal exists: %w", err)
}
origWALSize, newWALSize, synced, err := db.verifyAndSync(ctx, false)
if err != nil {
return err
}
// Track that data was synced for time-based checkpoint decisions.
if synced {
db.syncedSinceCheckpoint = true
}
if err := db.checkpointIfNeeded(ctx, origWALSize, newWALSize); err != nil {
return fmt.Errorf("checkpoint: %w", err)
}
// Compute current index and total shadow WAL size.
pos, err := db.Pos()