-
Notifications
You must be signed in to change notification settings - Fork 347
Expand file tree
/
Copy pathreplica.go
More file actions
1731 lines (1492 loc) · 49.1 KB
/
replica.go
File metadata and controls
1731 lines (1492 loc) · 49.1 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 (
"context"
"crypto/rand"
"database/sql"
"errors"
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/superfly/ltx"
"github.com/benbjohnson/litestream/internal"
)
// Default replica settings.
const (
DefaultSyncInterval = 1 * time.Second
)
// Replica connects a database to a replication destination via a ReplicaClient.
// The replica manages periodic synchronization and maintaining the current
// replica position.
type Replica struct {
db *DB
mu sync.RWMutex
pos ltx.Pos // current replicated position
syncMu sync.Mutex // protects Sync() from concurrent calls
muf sync.Mutex
f *os.File // long-running file descriptor to avoid non-OFD lock issues
wg sync.WaitGroup
cancel func()
// Client used to connect to the remote replica.
Client ReplicaClient
// Time between syncs with the shadow WAL.
SyncInterval time.Duration
// If true, replica monitors database for changes automatically.
// Set to false if replica is being used synchronously (such as in tests).
MonitorEnabled bool
// If true, automatically reset local state when LTX errors are detected.
// This allows recovery from corrupted/missing LTX files by resetting
// the position file and removing local LTX files, forcing a fresh sync.
// Disabled by default to prevent silent data loss scenarios.
AutoRecoverEnabled bool
}
func NewReplica(db *DB) *Replica {
r := &Replica{
db: db,
cancel: func() {},
SyncInterval: DefaultSyncInterval,
MonitorEnabled: true,
}
return r
}
func NewReplicaWithClient(db *DB, client ReplicaClient) *Replica {
r := NewReplica(db)
r.Client = client
return r
}
// Logger returns the DB sub-logger for this replica.
func (r *Replica) Logger() *slog.Logger {
logger := slog.Default()
if r.db != nil {
logger = r.db.Logger
}
return logger.With("replica", r.Client.Type())
}
// DB returns a reference to the database the replica is attached to, if any.
func (r *Replica) DB() *DB { return r.db }
// Starts replicating in a background goroutine.
func (r *Replica) Start(ctx context.Context) error {
// Ignore if replica is being used sychronously.
if !r.MonitorEnabled {
return nil
}
// Stop previous replication.
r.Stop(false)
// Wrap context with cancelation.
ctx, r.cancel = context.WithCancel(ctx)
// Start goroutine to replicate data.
r.wg.Add(1)
go func() { defer r.wg.Done(); r.monitor(ctx) }()
return nil
}
// Stop cancels any outstanding replication and blocks until finished.
//
// Performing a hard stop will close the DB file descriptor which could release
// locks on per-process locks. Hard stops should only be performed when
// stopping the entire process.
func (r *Replica) Stop(hard bool) (err error) {
r.cancel()
r.wg.Wait()
r.muf.Lock()
defer r.muf.Unlock()
if hard && r.f != nil {
if e := r.f.Close(); e != nil && err == nil {
err = e
}
}
return err
}
// Sync copies new WAL frames from the shadow WAL to the replica client.
// Only one Sync can run at a time to prevent concurrent uploads of the same file.
func (r *Replica) Sync(ctx context.Context) (err error) {
r.syncMu.Lock()
defer r.syncMu.Unlock()
// Clear last position if if an error occurs during sync.
defer func() {
if err != nil {
r.mu.Lock()
r.pos = ltx.Pos{}
r.mu.Unlock()
}
}()
// Calculate current replica position, if unknown.
if r.Pos().IsZero() {
pos, err := r.calcPos(ctx)
if err != nil {
return fmt.Errorf("calc pos: %w", err)
}
r.SetPos(pos)
}
// Find current position of database.
dpos, err := r.db.Pos()
if err != nil {
return fmt.Errorf("cannot determine current position: %w", err)
} else if dpos.IsZero() {
return fmt.Errorf("no position, waiting for data")
}
r.Logger().Debug("replica sync", "txid", dpos.TXID.String())
// Replicate all L0 LTX files since last replica position.
for txID := r.Pos().TXID + 1; txID <= dpos.TXID; txID = r.Pos().TXID + 1 {
if err := r.uploadLTXFile(ctx, 0, txID, txID); err != nil {
return err
}
r.SetPos(ltx.Pos{TXID: txID})
}
// Record successful sync for heartbeat monitoring.
r.db.RecordSuccessfulSync()
return nil
}
func (r *Replica) uploadLTXFile(ctx context.Context, level int, minTXID, maxTXID ltx.TXID) (err error) {
filename := r.db.LTXPath(level, minTXID, maxTXID)
f, err := os.Open(filename)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
if _, err := r.Client.WriteLTXFile(ctx, level, minTXID, maxTXID, f); err != nil {
return fmt.Errorf("write ltx file: %w", err)
}
r.Logger().Debug("ltx file uploaded", "filename", filename, "minTXID", minTXID, "maxTXID", maxTXID)
// Track current position
//replicaWALIndexGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(rd.Pos().Index))
//replicaWALOffsetGaugeVec.WithLabelValues(r.db.Path(), r.Name()).Set(float64(rd.Pos().Offset))
return nil
}
// calcPos returns the last position saved to the replica for level 0.
func (r *Replica) calcPos(ctx context.Context) (pos ltx.Pos, err error) {
info, err := r.MaxLTXFileInfo(ctx, 0)
if err != nil {
return pos, fmt.Errorf("max ltx file: %w", err)
}
return ltx.Pos{TXID: info.MaxTXID}, nil
}
// MaxLTXFileInfo returns metadata about the last LTX file for a given level.
// Returns nil if no files exist for the level.
func (r *Replica) MaxLTXFileInfo(ctx context.Context, level int) (info ltx.FileInfo, err error) {
// Normal operation - use fast timestamps
itr, err := r.Client.LTXFiles(ctx, level, 0, false)
if err != nil {
return info, err
}
defer itr.Close()
for itr.Next() {
item := itr.Item()
if item.MaxTXID > info.MaxTXID {
info = *item
}
}
return info, itr.Close()
}
// Pos returns the current replicated position.
// Returns a zero value if the current position cannot be determined.
func (r *Replica) Pos() ltx.Pos {
r.mu.RLock()
defer r.mu.RUnlock()
return r.pos
}
// SetPos sets the current replicated position.
func (r *Replica) SetPos(pos ltx.Pos) {
r.mu.Lock()
defer r.mu.Unlock()
r.pos = pos
}
// EnforceRetention forces a new snapshot once the retention interval has passed.
// Older snapshots and WAL files are then removed.
func (r *Replica) EnforceRetention(ctx context.Context) (err error) {
panic("TODO(ltx): Re-implement after multi-level compaction")
/*
// Obtain list of snapshots that are within the retention period.
snapshots, err := r.Snapshots(ctx)
if err != nil {
return fmt.Errorf("snapshots: %w", err)
}
retained := FilterSnapshotsAfter(snapshots, time.Now().Add(-r.Retention))
// If no retained snapshots exist, create a new snapshot.
if len(retained) == 0 {
snapshot, err := r.Snapshot(ctx)
if err != nil {
return fmt.Errorf("snapshot: %w", err)
}
retained = append(retained, snapshot)
}
// Delete unretained snapshots & WAL files.
snapshot := FindMinSnapshot(retained)
// Otherwise remove all earlier snapshots & WAL segments.
if err := r.deleteSnapshotsBeforeIndex(ctx, snapshot.Index); err != nil {
return fmt.Errorf("delete snapshots before index: %w", err)
} else if err := r.deleteWALSegmentsBeforeIndex(ctx, snapshot.Index); err != nil {
return fmt.Errorf("delete wal segments before index: %w", err)
}
return nil
*/
}
/*
func (r *Replica) deleteBeforeTXID(ctx context.Context, level int, txID ltx.TXID) error {
itr, err := r.Client.LTXFiles(ctx, level)
if err != nil {
return fmt.Errorf("fetch ltx files: %w", err)
}
defer itr.Close()
var a []*ltx.FileInfo
for itr.Next() {
info := itr.Item()
if info.MinTXID >= txID {
continue
}
a = append(a, info)
}
if err := itr.Close(); err != nil {
return err
}
if len(a) == 0 {
return nil
}
if err := r.Client.DeleteLTXFiles(ctx, a); err != nil {
return fmt.Errorf("delete wal segments: %w", err)
}
r.Logger().Info("ltx files deleted before",
slog.Int("level", level),
slog.String("txID", txID.String()),
slog.Int("n", len(a)))
return nil
}
*/
// monitor runs in a separate goroutine and continuously replicates the DB.
// Implements exponential backoff on repeated sync errors to prevent log spam
// and reduce load when persistent errors occur. See issue #927.
func (r *Replica) monitor(ctx context.Context) {
ticker := time.NewTicker(r.SyncInterval)
defer ticker.Stop()
// Continuously check for new data to replicate.
ch := make(chan struct{})
close(ch)
var notify <-chan struct{} = ch
var backoff time.Duration
var lastLogTime time.Time
var consecutiveErrs int
for initial := true; ; initial = false {
// Enforce a minimum time between synchronization.
if !initial {
select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
// If in backoff mode, wait additional time before retrying.
if backoff > 0 {
select {
case <-ctx.Done():
return
case <-time.After(backoff):
}
}
// Wait for changes to the database.
select {
case <-ctx.Done():
return
case <-notify:
}
// Fetch new notify channel before replicating data.
notify = r.db.Notify()
// Synchronize the shadow wal into the replication directory.
if err := r.Sync(ctx); err != nil {
// Don't log context cancellation errors during shutdown
if !errors.Is(err, context.Canceled) && !errors.Is(err, context.DeadlineExceeded) {
consecutiveErrs++
// Exponential backoff: SyncInterval -> 2x -> 4x -> ... -> max
if backoff == 0 {
backoff = r.SyncInterval
} else {
backoff *= 2
if backoff > DefaultSyncBackoffMax {
backoff = DefaultSyncBackoffMax
}
}
// Check for LTX errors and include recovery hints
var ltxErr *LTXError
if errors.As(err, <xErr) {
// Log with rate limiting to avoid log spam during persistent errors.
if time.Since(lastLogTime) >= SyncErrorLogInterval {
if ltxErr.Hint != "" {
r.Logger().Error("monitor error",
"error", err,
"path", ltxErr.Path,
"hint", ltxErr.Hint,
"consecutive_errors", consecutiveErrs,
"backoff", backoff)
} else {
r.Logger().Error("monitor error",
"error", err,
"path", ltxErr.Path,
"consecutive_errors", consecutiveErrs,
"backoff", backoff)
}
lastLogTime = time.Now()
}
// Attempt auto-recovery if enabled
if r.AutoRecoverEnabled {
r.Logger().Warn("auto-recovery enabled, resetting local state")
if resetErr := r.db.ResetLocalState(ctx); resetErr != nil {
r.Logger().Error("auto-recovery failed", "error", resetErr)
} else {
r.Logger().Info("auto-recovery complete, resuming replication")
// Reset backoff after successful recovery
backoff = 0
consecutiveErrs = 0
}
}
} else {
// Log with rate limiting to avoid log spam during persistent errors.
if time.Since(lastLogTime) >= SyncErrorLogInterval {
r.Logger().Error("monitor error",
"error", err,
"consecutive_errors", consecutiveErrs,
"backoff", backoff)
lastLogTime = time.Now()
}
}
}
continue
}
// Success - reset backoff and error counter.
if consecutiveErrs > 0 {
r.Logger().Info("replica sync recovered", "previous_errors", consecutiveErrs)
}
backoff = 0
consecutiveErrs = 0
}
}
// CreatedAt returns the earliest creation time of any LTX file.
// Returns zero time if no LTX files exist.
func (r *Replica) CreatedAt(ctx context.Context) (time.Time, error) {
var min time.Time
// Normal operation - use fast timestamps
itr, err := r.Client.LTXFiles(ctx, 0, 0, false)
if err != nil {
return min, err
}
defer itr.Close()
if itr.Next() {
min = itr.Item().CreatedAt
}
return min, itr.Close()
}
// TimeBounds returns the creation time & last updated time.
// Returns zero time if no LTX files exist.
func (r *Replica) TimeBounds(ctx context.Context) (createdAt, updatedAt time.Time, err error) {
for level := SnapshotLevel; level >= 0; level-- {
itr, err := r.Client.LTXFiles(ctx, level, 0, false)
if err != nil {
return createdAt, updatedAt, err
}
for itr.Next() {
info := itr.Item()
if createdAt.IsZero() || info.CreatedAt.Before(createdAt) {
createdAt = info.CreatedAt
}
if updatedAt.IsZero() || info.CreatedAt.After(updatedAt) {
updatedAt = info.CreatedAt
}
}
if err := itr.Close(); err != nil {
return createdAt, updatedAt, err
}
}
return createdAt, updatedAt, nil
}
// CalcRestoreTarget returns a target time restore from.
func (r *Replica) CalcRestoreTarget(ctx context.Context, opt RestoreOptions) (updatedAt time.Time, err error) {
// Determine the replicated time bounds from LTX files.
createdAt, updatedAt, err := r.TimeBounds(ctx)
if err != nil {
return time.Time{}, fmt.Errorf("created at: %w", err)
}
// Also check v0.3.x time bounds if client supports it.
if client, ok := r.Client.(ReplicaClientV3); ok {
v3CreatedAt, v3UpdatedAt, err := r.TimeBoundsV3(ctx, client)
if err != nil {
return time.Time{}, fmt.Errorf("v0.3.x time bounds: %w", err)
}
// Extend time bounds to include v0.3.x backups.
if !v3CreatedAt.IsZero() && (createdAt.IsZero() || v3CreatedAt.Before(createdAt)) {
createdAt = v3CreatedAt
}
if !v3UpdatedAt.IsZero() && (updatedAt.IsZero() || v3UpdatedAt.After(updatedAt)) {
updatedAt = v3UpdatedAt
}
}
// Skip if it does not contain timestamp.
if !opt.Timestamp.IsZero() {
if createdAt.IsZero() && updatedAt.IsZero() {
return time.Time{}, fmt.Errorf("no backups found")
}
if opt.Timestamp.Before(createdAt) || opt.Timestamp.After(updatedAt) {
return time.Time{}, fmt.Errorf("timestamp does not exist")
}
}
return updatedAt, nil
}
// Replica restores the database from a replica based on the options given.
// This method will restore into opt.OutputPath, if specified, or into the
// DB's original database path. It can optionally restore from a specific
// replica or it will automatically choose the best one. Finally,
// a timestamp can be specified to restore the database to a specific
// point-in-time.
//
// When the replica contains both v0.3.x and LTX format backups, this method
// compares snapshots from both formats and uses whichever has the better backup:
// - With timestamp: uses the format with the most recent snapshot before timestamp
// - Without timestamp: uses the format with the most recent backup overall
func (r *Replica) Restore(ctx context.Context, opt RestoreOptions) (err error) {
// Validate options.
if opt.OutputPath == "" {
return fmt.Errorf("output path required")
} else if opt.TXID != 0 && !opt.Timestamp.IsZero() {
return fmt.Errorf("cannot specify index & timestamp to restore")
} else if opt.Follow && opt.TXID != 0 {
return fmt.Errorf("cannot use follow mode with -txid")
} else if opt.Follow && !opt.Timestamp.IsZero() {
return fmt.Errorf("cannot use follow mode with -timestamp")
}
// In follow mode, if the database already exists, attempt crash recovery
// by reading the last applied TXID from the sidecar file.
if opt.Follow {
if _, statErr := os.Stat(opt.OutputPath); statErr == nil {
txid, readErr := ReadTXIDFile(opt.OutputPath)
if readErr != nil {
return fmt.Errorf("read txid file for crash recovery: %w", readErr)
}
if txid == 0 {
return fmt.Errorf("cannot resume follow mode: database exists but no -txid file found; delete the database to re-restore: %s", opt.OutputPath)
}
// Validate saved TXID is still reachable. If the earliest snapshot
// starts after our saved TXID, retention has pruned the history
// and we can't catch up incrementally.
snapshotItr, itrErr := r.Client.LTXFiles(ctx, SnapshotLevel, 0, false)
if itrErr != nil {
return fmt.Errorf("cannot validate saved TXID for crash recovery: %w", itrErr)
}
var latestSnapshot *ltx.FileInfo
for snapshotItr.Next() {
latestSnapshot = snapshotItr.Item()
}
if err := snapshotItr.Err(); err != nil {
_ = snapshotItr.Close()
return fmt.Errorf("iterate snapshots for crash recovery validation: %w", err)
}
_ = snapshotItr.Close()
if latestSnapshot != nil {
if latestSnapshot.MinTXID > txid {
return fmt.Errorf("cannot resume follow mode: saved TXID %s is behind the earliest snapshot (min TXID %s); replica history has been pruned -- delete %s and %s-txid to re-restore", txid, latestSnapshot.MinTXID, opt.OutputPath, opt.OutputPath)
}
if txid > latestSnapshot.MaxTXID {
return fmt.Errorf("cannot resume follow mode: saved TXID %s is ahead of latest snapshot (max TXID %s); delete %s and %s-txid to re-restore", txid, latestSnapshot.MaxTXID, opt.OutputPath, opt.OutputPath)
}
}
r.Logger().Info("resuming follow mode from crash recovery", "txid", txid, "output", opt.OutputPath)
return r.follow(ctx, opt.OutputPath, txid, opt.FollowInterval)
}
}
// Ensure output path does not already exist.
if _, err := os.Stat(opt.OutputPath); err == nil {
return fmt.Errorf("cannot restore, output path already exists: %s", opt.OutputPath)
} else if !os.IsNotExist(err) {
return err
}
// Compare v0.3.x and LTX formats to find the best backup (unless TXID is specified).
// Skip V3 format when follow mode is enabled (V3 doesn't support incremental following).
if opt.TXID == 0 && !opt.Follow {
if client, ok := r.Client.(ReplicaClientV3); ok {
useV3, err := r.shouldUseV3Restore(ctx, client, opt.Timestamp)
if err != nil {
return err
}
if useV3 {
return r.RestoreV3(ctx, opt)
}
}
}
infos, err := CalcRestorePlan(ctx, r.Client, opt.TXID, opt.Timestamp, r.Logger())
if err != nil {
return fmt.Errorf("cannot calc restore plan: %w", err)
}
r.Logger().Debug("restore plan", "n", len(infos), "txid", infos[len(infos)-1].MaxTXID, "timestamp", infos[len(infos)-1].CreatedAt)
rdrs := make([]io.Reader, 0, len(infos))
defer func() {
for _, rd := range rdrs {
if closer, ok := rd.(io.Closer); ok {
_ = closer.Close()
}
}
}()
for _, info := range infos {
// Validate file size - must be at least header size to be readable
if info.Size < ltx.HeaderSize {
return fmt.Errorf("invalid ltx file: level=%d min=%s max=%s has size %d bytes (minimum %d)",
info.Level, info.MinTXID, info.MaxTXID, info.Size, ltx.HeaderSize)
}
r.Logger().Debug("opening ltx file for restore", "level", info.Level, "min", info.MinTXID, "max", info.MaxTXID)
// Add file to be compacted.
f, err := r.Client.OpenLTXFile(ctx, info.Level, info.MinTXID, info.MaxTXID, 0, 0)
if err != nil {
return fmt.Errorf("open ltx file: %w", err)
}
rdrs = append(rdrs, internal.NewResumableReader(ctx, r.Client, info.Level, info.MinTXID, info.MaxTXID, info.Size, f, r.Logger()))
}
if len(rdrs) == 0 {
return fmt.Errorf("no matching backup files available")
}
// Create parent directory if it doesn't exist.
var dirInfo os.FileInfo
if db := r.DB(); db != nil {
dirInfo = db.dirInfo
}
if err := internal.MkdirAll(filepath.Dir(opt.OutputPath), dirInfo); err != nil {
return fmt.Errorf("create parent directory: %w", err)
}
// Output to temp file & atomically rename.
tmpOutputPath := opt.OutputPath + ".tmp"
r.Logger().Debug("compacting into database", "path", tmpOutputPath, "n", len(rdrs))
f, err := os.Create(tmpOutputPath)
if err != nil {
return fmt.Errorf("create temp database path: %w", err)
}
defer func() { _ = f.Close() }()
pr, pw := io.Pipe()
go func() {
c, err := ltx.NewCompactor(pw, rdrs)
if err != nil {
pw.CloseWithError(fmt.Errorf("new ltx compactor: %w", err))
return
}
c.HeaderFlags = ltx.HeaderFlagNoChecksum
_ = pw.CloseWithError(c.Compact(ctx))
}()
dec := ltx.NewDecoder(pr)
if err := dec.DecodeDatabaseTo(f); err != nil {
return fmt.Errorf("decode database: %w", err)
}
if err := f.Sync(); err != nil {
return err
} else if err := f.Close(); err != nil {
return err
}
// Copy file to final location.
r.Logger().Debug("renaming database from temporary location")
if err := os.Rename(tmpOutputPath, opt.OutputPath); err != nil {
return err
}
if opt.IntegrityCheck != IntegrityCheckNone {
if err := checkIntegrity(opt.OutputPath, opt.IntegrityCheck); err != nil {
_ = os.Remove(opt.OutputPath)
_ = os.Remove(opt.OutputPath + "-shm")
_ = os.Remove(opt.OutputPath + "-wal")
return fmt.Errorf("post-restore integrity check: %w", err)
}
r.Logger().Info("post-restore integrity check passed")
}
// Enter follow mode if enabled, continuously applying new LTX files.
if opt.Follow {
for _, rd := range rdrs {
if closer, ok := rd.(io.Closer); ok {
_ = closer.Close()
}
}
rdrs = nil
maxTXID := infos[len(infos)-1].MaxTXID
if err := WriteTXIDFile(opt.OutputPath, maxTXID); err != nil {
return fmt.Errorf("write initial txid file: %w", err)
}
return r.follow(ctx, opt.OutputPath, maxTXID, opt.FollowInterval)
}
return nil
}
// follow enters a continuous restore loop, polling for new LTX files and
// applying them to the restored database. It blocks until the context is
// cancelled (e.g. Ctrl+C). Returns nil on clean shutdown.
func (r *Replica) follow(ctx context.Context, outputPath string, lastTXID ltx.TXID, interval time.Duration) error {
f, err := os.OpenFile(outputPath, os.O_RDWR, 0)
if err != nil {
return fmt.Errorf("open database for follow: %w", err)
}
defer func() {
_ = f.Sync()
_ = f.Close()
}()
// Read page size from SQLite header (offset 16, 2 bytes, big-endian).
var buf [2]byte
if _, err := f.ReadAt(buf[:], 16); err != nil {
return fmt.Errorf("read page size from database header: %w", err)
}
pageSize := uint32(buf[0])<<8 | uint32(buf[1])
if pageSize == 1 {
pageSize = 65536
}
if interval <= 0 {
interval = DefaultFollowInterval
}
r.Logger().Info("entering follow mode", "output", outputPath, "txid", lastTXID, "interval", interval)
ticker := time.NewTicker(interval)
defer ticker.Stop()
var consecutiveErrors int
for {
select {
case <-ctx.Done():
r.Logger().Info("follow mode stopped")
return nil
case <-ticker.C:
newTXID, err := r.applyNewLTXFiles(ctx, f, lastTXID, pageSize)
if err != nil {
if ctx.Err() != nil {
r.Logger().Info("follow mode stopped")
return nil
}
consecutiveErrors++
r.Logger().Error("follow: error applying updates", "err", err, "consecutive_errors", consecutiveErrors)
continue
}
if newTXID > lastTXID {
if err := WriteTXIDFile(outputPath, newTXID); err != nil {
return fmt.Errorf("write txid file: %w", err)
}
r.Logger().Info("follow: applied updates", "from_txid", lastTXID, "to_txid", newTXID)
lastTXID = newTXID
consecutiveErrors = 0
}
}
}
}
// applyNewLTXFiles polls for new LTX files and applies them to the database.
// It starts from level 0 and falls back to higher levels if there are gaps
// (e.g., level 0 files were compacted away).
func (r *Replica) applyNewLTXFiles(ctx context.Context, f *os.File, afterTXID ltx.TXID, pageSize uint32) (ltx.TXID, error) {
currentTXID := afterTXID
// Poll level 0 for the most recent incremental files.
itr, err := r.Client.LTXFiles(ctx, 0, currentTXID+1, false)
if err != nil {
return currentTXID, fmt.Errorf("list level 0 ltx files: %w", err)
}
closeLevel0 := func(retErr error) (ltx.TXID, error) {
if closeErr := itr.Close(); closeErr != nil {
closeErr = fmt.Errorf("close level 0 ltx iterator: %w", closeErr)
if retErr != nil {
return currentTXID, errors.Join(retErr, closeErr)
}
return currentTXID, closeErr
}
return currentTXID, retErr
}
var sawLevel0 bool
for itr.Next() {
sawLevel0 = true
info := itr.Item()
// If there's a gap, try to fill it from higher compaction levels.
if info.MinTXID > currentTXID+1 {
bridgedTXID, err := r.fillFollowGap(ctx, f, currentTXID, info.MinTXID, pageSize)
if err != nil {
return closeLevel0(err)
}
currentTXID = bridgedTXID
// Re-check if this file is still needed after bridging.
if info.MaxTXID <= currentTXID {
continue
}
if info.MinTXID > currentTXID+1 {
return closeLevel0(nil)
}
}
// Skip if already covered by a higher-level file.
if info.MaxTXID <= currentTXID {
continue
}
if err := r.applyLTXFile(ctx, f, info, pageSize); err != nil {
return closeLevel0(fmt.Errorf(
"apply ltx file (level=%d, min=%s, max=%s): %w",
info.Level, info.MinTXID, info.MaxTXID, err,
))
}
currentTXID = info.MaxTXID
}
if iterErr := itr.Err(); iterErr != nil {
return closeLevel0(fmt.Errorf("iterate level 0 ltx files: %w", iterErr))
}
if _, err := closeLevel0(nil); err != nil {
return currentTXID, err
}
if !sawLevel0 {
bridgedTXID, err := r.fillFollowGap(ctx, f, currentTXID, currentTXID+1, pageSize)
if err != nil {
return currentTXID, err
}
currentTXID = bridgedTXID
}
return currentTXID, nil
}
// applyLTXFile applies a single LTX file's pages to the database file.
// This follows the same pattern as Hydrator.ApplyLTX (vfs.go:712-747).
//
// To prevent concurrent SQLite readers from seeing partial updates, we acquire
// an exclusive file lock before writing. We also rewrite the SQLite header
// (bytes 18-19) to indicate DELETE journal mode instead of WAL mode, and
// randomize the schema change counter (bytes 24-27) to invalidate cached
// schemas in other connections.
func (r *Replica) applyLTXFile(ctx context.Context, f *os.File, info *ltx.FileInfo, pageSize uint32) error {
rc, err := r.Client.OpenLTXFile(ctx, info.Level, info.MinTXID, info.MaxTXID, 0, 0)
if err != nil {
return fmt.Errorf("open ltx file: %w", err)
}
defer rc.Close()
dec := ltx.NewDecoder(rc)
if err := dec.DecodeHeader(); err != nil {
return fmt.Errorf("decode header: %w", err)
}
hdr := dec.Header()
if err := internal.LockFileExclusive(f); err != nil {
return fmt.Errorf("acquire exclusive lock: %w", err)
}
defer internal.UnlockFile(f)
for {
var phdr ltx.PageHeader
data := make([]byte, pageSize)
if err := dec.DecodePage(&phdr, data); err == io.EOF {
break
} else if err != nil {
return fmt.Errorf("decode page: %w", err)
}
if phdr.Pgno == 1 && len(data) >= 28 {
data[18], data[19] = 0x01, 0x01
_, _ = rand.Read(data[24:28])
}
off := int64(phdr.Pgno-1) * int64(pageSize)
if _, err := f.WriteAt(data, off); err != nil {
return fmt.Errorf("write page %d: %w", phdr.Pgno, err)
}
}
if hdr.Commit > 0 {
newSize := int64(hdr.Commit) * int64(pageSize)
if err := f.Truncate(newSize); err != nil {
return fmt.Errorf("truncate: %w", err)
}
}
if err := dec.Close(); err != nil {
return fmt.Errorf("close decoder: %w", err)
}
return f.Sync()
}
// fillFollowGap attempts to bridge a gap in level 0 files by searching
// higher compaction levels for a file that covers the missing TXID range.
func (r *Replica) fillFollowGap(ctx context.Context, f *os.File, afterTXID ltx.TXID, gapMinTXID ltx.TXID, pageSize uint32) (ltx.TXID, error) {
currentTXID := afterTXID
for level := 1; level < SnapshotLevel; level++ {
itr, err := r.Client.LTXFiles(ctx, level, 0, false)
if err != nil {
return currentTXID, fmt.Errorf("list level %d ltx files: %w", level, err)
}
closeLevel := func(retErr error) (ltx.TXID, error) {
if closeErr := itr.Close(); closeErr != nil {
closeErr = fmt.Errorf("close level %d ltx iterator: %w", level, closeErr)
if retErr != nil {
return currentTXID, errors.Join(retErr, closeErr)
}
return currentTXID, closeErr
}
return currentTXID, retErr
}
for itr.Next() {
info := itr.Item()
// Skip if there's a gap at this level too.
if info.MinTXID > currentTXID+1 {
break
}
// Skip if already covered.
if info.MaxTXID <= currentTXID {
continue
}
if err := r.applyLTXFile(ctx, f, info, pageSize); err != nil {
return closeLevel(fmt.Errorf(
"apply gap-fill ltx file (level=%d, min=%s, max=%s): %w",
info.Level, info.MinTXID, info.MaxTXID, err,
))
}
currentTXID = info.MaxTXID
// If we've bridged past the gap, we're done.
if currentTXID+1 >= gapMinTXID {
return closeLevel(nil)
}
}
if iterErr := itr.Err(); iterErr != nil {
return closeLevel(fmt.Errorf("iterate level %d ltx files: %w", level, iterErr))
}
if _, err := closeLevel(nil); err != nil {
return currentTXID, err
}
// If we made progress at this level, restart from level 1.
if currentTXID > afterTXID {
return currentTXID, nil
}
}
return currentTXID, nil
}
// RestoreV3 restores from a v0.3.x format backup.
func (r *Replica) RestoreV3(ctx context.Context, opt RestoreOptions) error {
client, ok := r.Client.(ReplicaClientV3)
if !ok {
return fmt.Errorf("replica client does not support v0.3.x restore")
}
// Validate options.
if opt.OutputPath == "" {
return fmt.Errorf("output path required")
}
// Ensure output path does not already exist.
if _, err := os.Stat(opt.OutputPath); err == nil {
return fmt.Errorf("cannot restore, output path already exists: %s", opt.OutputPath)
} else if !os.IsNotExist(err) {
return err
}
// Find all generations.
generations, err := client.GenerationsV3(ctx)
if err != nil {
return fmt.Errorf("list generations: %w", err)
}
if len(generations) == 0 {
return ErrNoSnapshots
}