-
Notifications
You must be signed in to change notification settings - Fork 378
/
Copy pathreplicator.rs
2201 lines (2035 loc) · 88.6 KB
/
replicator.rs
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
use crate::backup::WalCopier;
use crate::completion_progress::{CompletionProgress, SavepointTracker};
use crate::read::BatchReader;
use crate::uuid_utils::decode_unix_timestamp;
use crate::wal::WalFileReader;
use anyhow::{anyhow, bail};
use arc_swap::ArcSwapOption;
use async_compression::tokio::write::{GzipEncoder, ZstdEncoder};
use aws_config::BehaviorVersion;
use aws_sdk_s3::config::{
Credentials, Region, SharedCredentialsProvider, StalledStreamProtectionConfig,
};
use aws_sdk_s3::error::SdkError;
use aws_sdk_s3::operation::get_object::builders::GetObjectFluentBuilder;
use aws_sdk_s3::operation::get_object::GetObjectError;
use aws_sdk_s3::operation::list_objects::builders::ListObjectsFluentBuilder;
use aws_sdk_s3::operation::list_objects::ListObjectsOutput;
use aws_sdk_s3::primitives::ByteStream;
use aws_sdk_s3::{Client, Config};
use bytes::{Buf, Bytes};
use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use libsql_replication::injector::Injector as _;
use libsql_replication::rpc::replication::Frame as RpcFrame;
use libsql_sys::{Cipher, EncryptionConfig};
use metrics::{counter, gauge, histogram};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use tokio::fs::{File, OpenOptions};
use tokio::io::AsyncWriteExt;
use tokio::sync::watch::{channel, Receiver, Sender};
use tokio::sync::{Mutex, Semaphore};
use tokio::task::JoinHandle;
use tokio::task::JoinSet;
use tokio::time::Duration;
use tokio::time::{timeout_at, Instant};
use uuid::{NoContext, Uuid};
/// Maximum number of generations that can participate in database restore procedure.
/// This effectively means that at least one in [MAX_RESTORE_STACK_DEPTH] number of
/// consecutive generations has to have a snapshot included.
const MAX_RESTORE_STACK_DEPTH: usize = 100;
pub type Result<T> = anyhow::Result<T>;
#[derive(Debug)]
pub struct Replicator {
pub client: Client,
/// Frame number, incremented whenever a new frame is written from SQLite.
next_frame_no: Arc<AtomicU32>,
/// Last frame which has been requested to be sent to S3.
/// Always: [last_sent_frame_no] <= [next_frame_no].
last_sent_frame_no: Arc<AtomicU32>,
/// Last frame which has been confirmed as stored locally outside of WAL file.
/// Always: [last_committed_frame_no] <= [last_sent_frame_no].
last_committed_frame_no: Receiver<Result<u32>>,
flush_trigger: Option<Sender<()>>,
shutdown_trigger: Option<tokio::sync::watch::Sender<()>>,
snapshot_waiter: Receiver<Result<Option<Uuid>>>,
snapshot_notifier: Arc<Sender<Result<Option<Uuid>>>>,
pub page_size: usize,
generation: Arc<ArcSwapOption<Uuid>>,
verify_crc: bool,
pub bucket: String,
pub db_path: String,
pub db_name: String,
use_compression: CompressionKind,
encryption_config: Option<EncryptionConfig>,
max_frames_per_batch: usize,
s3_max_parallelism: usize,
join_set: JoinSet<()>,
upload_progress: Arc<Mutex<CompletionProgress>>,
last_uploaded_frame_no: Receiver<u32>,
skip_snapshot: bool,
skip_shutdown_upload: bool,
}
#[derive(Debug)]
pub struct FetchedResults {
pub pages: Vec<(i32, Bytes)>,
pub next_marker: Option<String>,
}
#[derive(Debug)]
pub enum RestoreAction {
SnapshotMainDbFile,
ReuseGeneration(Uuid),
}
#[derive(Clone, Debug)]
pub struct Options {
pub create_bucket_if_not_exists: bool,
/// If `true` when restoring, frames checksums will be verified prior their pages being flushed
/// into the main database file.
pub verify_crc: bool,
/// Kind of compression algorithm used on the WAL frames to be sent to S3.
pub use_compression: CompressionKind,
pub encryption_config: Option<EncryptionConfig>,
pub aws_endpoint: Option<String>,
pub access_key_id: Option<String>,
pub secret_access_key: Option<String>,
pub session_token: Option<String>,
pub region: Option<String>,
pub db_id: Option<String>,
/// Bucket directory name where all S3 objects are backed up. General schema is:
/// - `{db-name}-{uuid-v7}` subdirectories:
/// - `.meta` file with database page size and initial WAL checksum.
/// - Series of files `{first-frame-no}-{last-frame-no}.{compression-kind}` containing
/// the batches of frames from which the restore will be made.
pub bucket_name: String,
/// Max number of WAL frames per S3 object.
pub max_frames_per_batch: usize,
/// Max time before next frame of batched frames should be synced. This works in the case
/// when we don't explicitly run into `max_frames_per_batch` threshold and the corresponding
/// checkpoint never commits.
pub max_batch_interval: Duration,
/// Maximum number of S3 file upload requests that may happen in parallel.
pub s3_max_parallelism: usize,
/// Max number of retries for S3 operations
pub s3_max_retries: u32,
/// Skip snapshot upload per checkpoint.
pub skip_snapshot: bool,
/// Skip uploading snapshots on shutdown
pub skip_shutdown_upload: bool,
/// Stall protection grace period duration for AWS S3 client
pub stall_protection_grace_period: std::time::Duration,
}
impl Options {
pub async fn client_config(&self) -> Result<Config> {
let mut loader = aws_config::SdkConfig::builder();
if let Some(endpoint) = self.aws_endpoint.as_deref() {
loader = loader.endpoint_url(endpoint);
}
let region = self
.region
.clone()
.ok_or(anyhow!("LIBSQL_BOTTOMLESS_AWS_DEFAULT_REGION was not set"))?;
let access_key_id = self
.access_key_id
.clone()
.ok_or(anyhow!("LIBSQL_BOTTOMLESS_AWS_ACCESS_KEY_ID was not set"))?;
let secret_access_key = self.secret_access_key.clone().ok_or(anyhow!(
"LIBSQL_BOTTOMLESS_AWS_SECRET_ACCESS_KEY was not set"
))?;
let session_token: Option<String> = self.session_token.clone();
let mut stall_protection = StalledStreamProtectionConfig::enabled();
stall_protection.set_grace_period(Some(self.stall_protection_grace_period));
let conf = loader
.behavior_version(BehaviorVersion::latest())
.stalled_stream_protection(stall_protection.build())
.region(Region::new(region))
.credentials_provider(SharedCredentialsProvider::new(Credentials::new(
access_key_id,
secret_access_key,
session_token,
None,
"Static",
)))
.retry_config(
aws_sdk_s3::config::retry::RetryConfig::standard()
.with_max_attempts(self.s3_max_retries),
)
.build();
let s3_config = aws_sdk_s3::config::Builder::from(&conf)
.force_path_style(true)
.build();
Ok(s3_config)
}
pub fn from_env() -> Result<Self> {
fn env_var(key: &str) -> Result<String> {
match std::env::var(key) {
Ok(res) => {
let res = res.trim().to_string();
if res.is_empty() {
bail!("{} environment variable is empty", key)
} else {
Ok(res)
}
}
Err(_) => bail!("{} environment variable not set", key),
}
}
fn env_var_or<S: ToString>(key: &str, default_value: S) -> String {
match env_var(key) {
Ok(res) => res,
Err(_) => default_value.to_string(),
}
}
let db_id = env_var("LIBSQL_BOTTOMLESS_DATABASE_ID").ok();
let aws_endpoint = env_var("LIBSQL_BOTTOMLESS_ENDPOINT").ok();
let bucket_name = env_var_or("LIBSQL_BOTTOMLESS_BUCKET", "bottomless");
let max_batch_interval = Duration::from_secs(
env_var_or("LIBSQL_BOTTOMLESS_BATCH_INTERVAL_SECS", 15).parse::<u64>()?,
);
let access_key_id = env_var("LIBSQL_BOTTOMLESS_AWS_ACCESS_KEY_ID").ok();
let secret_access_key = env_var("LIBSQL_BOTTOMLESS_AWS_SECRET_ACCESS_KEY").ok();
let session_token = env_var("LIBSQL_BOTTOMLESS_AWS_SESSION_TOKEN").ok();
let region = env_var("LIBSQL_BOTTOMLESS_AWS_DEFAULT_REGION").ok();
let max_frames_per_batch =
env_var_or("LIBSQL_BOTTOMLESS_BATCH_MAX_FRAMES", 10000).parse::<usize>()?;
let s3_max_parallelism =
env_var_or("LIBSQL_BOTTOMLESS_S3_PARALLEL_MAX", 32).parse::<usize>()?;
let use_compression =
CompressionKind::parse(&env_var_or("LIBSQL_BOTTOMLESS_COMPRESSION", "zstd"))
.map_err(|e| anyhow!("unknown compression kind: {}", e))?;
let encryption_cipher = env_var("LIBSQL_BOTTOMLESS_ENCRYPTION_CIPHER").ok();
let encryption_key = env_var("LIBSQL_BOTTOMLESS_ENCRYPTION_KEY")
.map(Bytes::from)
.ok();
let verify_crc = match env_var_or("LIBSQL_BOTTOMLESS_VERIFY_CRC", true)
.to_lowercase()
.as_ref()
{
"yes" | "true" | "1" | "y" | "t" => true,
"no" | "false" | "0" | "n" | "f" => false,
other => bail!(
"Invalid LIBSQL_BOTTOMLESS_VERIFY_CRC environment variable: {}",
other
),
};
let skip_snapshot = match env_var_or("LIBSQL_BOTTOMLESS_SKIP_SNAPSHOT", false)
.to_lowercase()
.as_ref()
{
"yes" | "true" | "1" | "y" | "t" => true,
"no" | "false" | "0" | "n" | "f" => false,
other => bail!(
"Invalid LIBSQL_BOTTOMLESS_SKIP_SNAPSHOT environment variable: {}",
other
),
};
let s3_max_retries = env_var_or("LIBSQL_BOTTOMLESS_S3_MAX_RETRIES", 10).parse::<u32>()?;
let cipher = match encryption_cipher {
Some(cipher) => Cipher::from_str(&cipher)?,
None => Cipher::default(),
};
let encryption_config = match encryption_key {
Some(key) => Some(EncryptionConfig::new(cipher, key)),
None => None,
};
let skip_shutdown_upload =
env_var_or("LIBSQL_BOTTOMLESS_SKIP_SHUTDOWN_UPLOAD", false).parse::<bool>()?;
let stall_protection_grace_period_sec =
env_var_or("LIBSQL_S3_STALL_PROTECTION_GRACE_PERIOD_SEC", 20).parse::<u64>()?;
let stall_protection_grace_period =
std::time::Duration::from_secs(stall_protection_grace_period_sec);
Ok(Options {
db_id,
create_bucket_if_not_exists: true,
verify_crc,
use_compression,
encryption_config,
max_batch_interval,
max_frames_per_batch,
s3_max_parallelism,
aws_endpoint,
access_key_id,
secret_access_key,
session_token,
region,
bucket_name,
s3_max_retries,
skip_snapshot,
skip_shutdown_upload,
stall_protection_grace_period,
})
}
}
impl Replicator {
pub const UNSET_PAGE_SIZE: usize = usize::MAX;
pub async fn new<S: Into<String>>(db_path: S) -> Result<Self> {
Self::with_options(db_path, Options::from_env()?).await
}
fn set_local_last_frame_no(db_name: &str, last_frame_no: u32) {
let db_name = db_name.to_string();
gauge!("bottomless_local_last_frame_no", last_frame_no as f64, "db_name" => db_name);
}
fn increment_local_ready_frame_ranges(db_name: &str, ready_ranges: u32) {
let db_name = db_name.to_string();
counter!("bottomless_local_ready_frame_ranges", ready_ranges as u64, "db_name" => db_name);
}
fn record_local_flush_time(db_name: &str, duration: Duration) {
let db_name = db_name.to_string();
histogram!("bottomless_local_flush_time", duration.as_secs_f64(), "db_name" => db_name);
}
fn record_s3_write_time(db_name: &str, duration: Duration) {
let db_name = db_name.to_string();
histogram!("bottomless_s3_write_time", duration.as_secs_f64(), "db_name" => db_name);
}
fn increment_s3_processed_frame_ranges(db_name: &str, processed: u64) {
let db_name = db_name.to_string();
counter!("bottomless_s3_processed_frame_ranges", processed, "db_name" => db_name);
}
fn record_snapshot_upload_time(db_name: &str, duration: Duration) {
let db_name = db_name.to_string();
histogram!("bottomless_snapshot_upload_time", duration.as_secs_f64(), "db_name" => db_name);
}
fn record_restore_upload_files_time(db_name: &str, duration: Duration) {
let db_name = db_name.to_string();
histogram!("bottomless_restore_upload_files_time", duration.as_secs_f64(), "db_name" => db_name);
}
fn record_restore_time(db_name: &str, duration: Duration) {
let db_name = db_name.to_string();
histogram!("bottomless_restore_time", duration.as_secs_f64(), "db_name" => db_name);
}
fn set_s3_processing_frame_no(db_name: &str, frame_no: u32) {
let db_name = db_name.to_string();
gauge!("bottomless_s3_processing_frame_no", frame_no as f64, "db_name" => db_name);
}
fn set_s3_queue_size(db_name: &str, size: usize) {
let db_name = db_name.to_string();
gauge!("bottomless_s3_queue_size", size as f64, "db_name" => db_name);
}
pub async fn with_options<S: Into<String>>(db_path: S, options: Options) -> Result<Self> {
let config = options.client_config().await?;
let client = Client::from_conf(config);
let bucket = options.bucket_name.clone();
let generation = Arc::new(ArcSwapOption::default());
match client.head_bucket().bucket(&bucket).send().await {
Ok(_) => tracing::info!("Bucket {} exists and is accessible", bucket),
Err(SdkError::ServiceError(err)) if err.err().is_not_found() => {
if options.create_bucket_if_not_exists {
tracing::info!("Bucket {} not found, recreating", bucket);
client.create_bucket().bucket(&bucket).send().await?;
} else {
tracing::error!("Bucket {} does not exist", bucket);
return Err(SdkError::ServiceError(err).into());
}
}
Err(e) => {
tracing::error!("Bucket checking error: {}", e);
return Err(e.into());
}
}
let db_path = db_path.into();
let db_name = if let Some(db_id) = options.db_id.clone() {
db_id
} else {
bail!("database id was not set")
};
tracing::debug!("Database path: '{}', name: '{}'", db_path, db_name);
let skip_shutdown_upload = options.skip_shutdown_upload;
if skip_shutdown_upload {
tracing::warn!("skipping upload on shutdown");
}
let (flush_trigger, mut flush_trigger_rx) = channel(());
let (last_committed_frame_no_sender, last_committed_frame_no) = channel(Ok(0));
let next_frame_no = Arc::new(AtomicU32::new(1));
let last_sent_frame_no = Arc::new(AtomicU32::new(0));
let mut join_set = JoinSet::new();
let (shutdown_trigger, shutdown_watch) = tokio::sync::watch::channel(());
let (frames_outbox, mut frames_inbox) = tokio::sync::mpsc::unbounded_channel();
let _local_backup = {
let mut copier = WalCopier::new(
bucket.clone(),
db_name.clone().into(),
generation.clone(),
&db_path,
options.max_frames_per_batch,
options.use_compression,
frames_outbox,
);
let next_frame_no = next_frame_no.clone();
let last_sent_frame_no = last_sent_frame_no.clone();
let batch_interval = options.max_batch_interval;
let db_name = db_name.clone();
join_set.spawn(async move {
loop {
let timeout = Instant::now() + batch_interval;
let trigger = match timeout_at(timeout, flush_trigger_rx.changed()).await {
Ok(Ok(())) => true,
Ok(Err(_)) => {
return;
}
Err(_) => {
true // timeout reached
}
};
if trigger {
let next_frame = next_frame_no.load(Ordering::Acquire);
let last_sent_frame =
last_sent_frame_no.swap(next_frame - 1, Ordering::Acquire);
let frames = (last_sent_frame + 1)..next_frame;
if !frames.is_empty() {
let start_time = Instant::now();
let res = copier.flush(frames).await;
Self::record_local_flush_time(&db_name, start_time.elapsed());
if let Ok((last_frame_no, ready_ranges)) = res {
Self::set_local_last_frame_no(&db_name, last_frame_no);
Self::increment_local_ready_frame_ranges(&db_name, ready_ranges);
}
if last_committed_frame_no_sender
.send(res.map(|r| r.0))
.is_err()
{
// Replicator was probably dropped and therefore corresponding
// receiver has been closed
return;
}
}
}
}
})
};
let (upload_progress, last_uploaded_frame_no) = CompletionProgress::new(0);
let upload_progress = Arc::new(Mutex::new(upload_progress));
let _s3_upload = {
let client = client.clone();
let bucket = options.bucket_name.clone();
let max_parallelism = options.s3_max_parallelism;
let upload_progress = upload_progress.clone();
let db_name = db_name.clone();
let shutdown_watch = Arc::new(shutdown_watch);
join_set.spawn(async move {
let sem = Arc::new(tokio::sync::Semaphore::new(max_parallelism));
let mut join_set = JoinSet::new();
while let Some(req) = frames_inbox.recv().await {
tracing::trace!("Received S3 upload request: {}", req.path);
let start = Instant::now();
let sem = sem.clone();
let permit = sem.acquire_owned().await.unwrap();
let client = client.clone();
let bucket = bucket.clone();
let upload_progress = upload_progress.clone();
if let Some(ref frames) = req.frames {
Self::set_s3_processing_frame_no(&db_name, *frames.end());
}
Self::set_s3_queue_size(&db_name, frames_inbox.len());
let db_name = db_name.clone();
let shutdown_watch = shutdown_watch.clone();
join_set.spawn(async move {
let fpath = format!("{}/{}", &bucket, &req.path);
loop {
let start_time = Instant::now();
let body = ByteStream::from_path(&fpath).await.unwrap();
let response = client
.put_object()
.bucket(&bucket)
.key(&req.path)
.body(body)
.send()
.await;
Self::record_s3_write_time(&db_name, start_time.elapsed());
if response.is_ok() {
break;
}
tracing::error!("Failed to send {} to S3: {}, will retry after 1 second", fpath, response.err().unwrap());
if shutdown_watch.has_changed().is_err() {
tracing::error!("stop retry for failed S3 frames upload because shutdown was requested");
return
}
tokio::time::sleep(Duration::from_millis(1000)).await;
}
tokio::fs::remove_file(&fpath).await.unwrap();
let elapsed = Instant::now() - start;
tracing::debug!("Uploaded to S3: {} in {:?}", fpath, elapsed);
if let Some(frames) = req.frames {
let mut up = upload_progress.lock().await;
up.update(*frames.start(), *frames.end());
Self::increment_s3_processed_frame_ranges(&db_name, 1);
}
drop(permit);
});
}
while join_set.join_next().await.is_some() {}
})
};
let (snapshot_notifier, snapshot_waiter) = channel(Ok(None));
Ok(Self {
client,
bucket,
page_size: Self::UNSET_PAGE_SIZE,
generation,
next_frame_no,
last_sent_frame_no,
flush_trigger: Some(flush_trigger),
shutdown_trigger: Some(shutdown_trigger),
last_committed_frame_no,
verify_crc: options.verify_crc,
db_path,
db_name,
snapshot_waiter,
snapshot_notifier: Arc::new(snapshot_notifier),
use_compression: options.use_compression,
encryption_config: options.encryption_config,
max_frames_per_batch: options.max_frames_per_batch,
s3_max_parallelism: options.s3_max_parallelism,
skip_snapshot: options.skip_snapshot,
join_set,
upload_progress,
last_uploaded_frame_no,
skip_shutdown_upload,
})
}
/// Checks if there exists any backup of given database
pub async fn has_backup_of(db_name: impl AsRef<str>, options: &Options) -> Result<bool> {
let prefix = match &options.db_id {
Some(db_id) => format!("{db_id}-"),
None => format!("ns-:{}-", db_name.as_ref()),
};
let config = options.client_config().await?;
let client = Client::from_conf(config);
let bucket = options.bucket_name.clone();
match client.head_bucket().bucket(&bucket).send().await {
Ok(_) => tracing::trace!("Bucket {bucket} exists and is accessible"),
Err(e) => {
tracing::trace!("Bucket checking error: {e}");
return Err(e.into());
}
}
let mut last_frame = 0;
let list_objects = client.list_objects().bucket(&bucket).prefix(&prefix);
let response = list_objects.send().await?;
let _ = Self::try_get_last_frame_no(response, &mut last_frame);
tracing::trace!("Last frame of {prefix}: {last_frame}");
Ok(last_frame > 0)
}
pub async fn shutdown_gracefully(&mut self) -> Result<()> {
if !self.skip_shutdown_upload {
tracing::info!("bottomless replicator: shutting down...");
// 1. wait for all committed WAL frames to be committed locally
let last_frame_no = self.last_known_frame();
// force flush in order to not wait for periodic wake up of local back up process
if let Some(tx) = &self.flush_trigger {
let _ = tx.send(());
}
self.wait_until_committed(last_frame_no).await?;
tracing::info!(
"bottomless replicator: local backup replicated frames until {}",
last_frame_no
);
// 2. wait for snapshot upload to S3 to finish
self.wait_until_snapshotted().await?;
tracing::info!("bottomless replicator: snapshot succesfully uploaded to S3");
// 3. drop flush trigger, which will cause WAL upload loop to close. Since this action will
// close the channel used by wait_until_committed, it must happen after wait_until_committed
// has finished. If trigger won't be dropped, tasks from join_set will never finish.
self.flush_trigger.take();
// 4. drop shutdown trigger which will notify S3 upload process to stop all retry attempts
// and finish upload process
self.shutdown_trigger.take();
while let Some(t) = self.join_set.join_next().await {
// one of the tasks we're waiting for is upload of local WAL segment from pt.1 to S3
// this should ensure that all WAL frames are one S3
t?;
}
} else {
tracing::warn!("skipping snapshot upload during shutdown");
}
tracing::info!("bottomless replicator: shutdown complete");
Ok(())
}
pub fn next_frame_no(&self) -> u32 {
self.next_frame_no.load(Ordering::Acquire)
}
pub fn last_known_frame(&self) -> u32 {
self.next_frame_no() - 1
}
pub fn last_sent_frame_no(&self) -> u32 {
self.last_sent_frame_no.load(Ordering::Acquire)
}
pub fn compression_kind(&self) -> CompressionKind {
self.use_compression
}
pub async fn is_snapshotted(&mut self) -> bool {
if let Ok(generation) = self.generation() {
if !self.main_db_exists_and_not_empty().await {
tracing::debug!("Not snapshotting, the main db file does not exist or is empty");
let _ = self.snapshot_notifier.send(Ok(Some(generation)));
return false;
}
tracing::debug!("waiting for generation snapshot {} to complete", generation);
let current = self.snapshot_waiter.borrow();
match &*current {
Ok(Some(gen)) => *gen == generation,
_ => false,
}
} else {
false
}
}
/// FIXME: I'm pretty sure that this function is buggy. First of all we don't check the output
/// of that function in the wal, second of all, we assume that an error means that we have
/// snapshotted. This whole stuff is a mess.
pub async fn wait_until_snapshotted(&mut self) -> Result<bool> {
if let Ok(generation) = self.generation() {
if !self.main_db_exists_and_not_empty().await {
tracing::debug!("Not snapshotting, the main db file does not exist or is empty");
let _ = self.snapshot_notifier.send(Ok(Some(generation)));
return Ok(false);
}
tracing::debug!("waiting for generation snapshot {} to complete", generation);
let res = self
.snapshot_waiter
.wait_for(|result| match result {
Ok(Some(gen)) => *gen == generation,
Ok(None) => false,
Err(_) => true,
})
.await?;
tracing::debug!("done waiting");
match res.deref() {
Ok(_) => Ok(true),
Err(e) => Err(anyhow!("Failed snapshot generation {}: {}", generation, e)),
}
} else {
Ok(false)
}
}
async fn reset_wal_tracker(&self) {
let mut lock = self.upload_progress.lock().await;
lock.reset();
}
pub fn savepoint(&self) -> SavepointTracker {
tracing::debug!(
"calling for backup savepoint for `{}` on generation `{}`, frame no.: {}",
self.db_name,
match self.generation() {
Ok(gen) => gen.to_string(),
_ => "".to_string(),
},
self.next_frame_no() - 1
);
if let Some(tx) = &self.flush_trigger {
let _ = tx.send(());
}
SavepointTracker::new(
self.generation.clone(),
self.snapshot_waiter.clone(),
self.next_frame_no.clone(),
self.last_uploaded_frame_no.clone(),
self.db_path.clone(),
)
}
/// Waits until the commit for a given frame_no or higher was given.
pub async fn wait_until_committed(&mut self, frame_no: u32) -> Result<u32> {
let res = self
.last_committed_frame_no
.wait_for(|result| match result {
Ok(last_committed) => *last_committed >= frame_no,
Err(_) => true,
})
.await?;
match res.deref() {
Ok(last_committed) => {
tracing::trace!(
"Confirmed commit of frame no. {} (waited for >= {})",
last_committed,
frame_no
);
Ok(*last_committed)
}
Err(e) => Err(anyhow!("Failed to flush frames: {}", e)),
}
}
/// Returns number of frames waiting to be replicated.
pub fn pending_frames(&self) -> u32 {
self.next_frame_no() - self.last_sent_frame_no() - 1
}
// The database can use different page size - as soon as it's known,
// it should be communicated to the replicator via this call.
// NOTICE: in practice, WAL journaling mode does not allow changing page sizes,
// so verifying that it hasn't changed is a panic check. Perhaps in the future
// it will be useful, if WAL ever allows changing the page size.
pub fn set_page_size(&mut self, page_size: usize) -> Result<()> {
if self.page_size != page_size {
tracing::trace!("Setting page size to: {}", page_size);
}
if self.page_size != Self::UNSET_PAGE_SIZE && self.page_size != page_size {
return Err(anyhow::anyhow!(
"Cannot set page size to {}, it was already set to {}",
page_size,
self.page_size
));
}
self.page_size = page_size;
Ok(())
}
// Gets an object from the current bucket
fn get_object(&self, key: String) -> GetObjectFluentBuilder {
self.client.get_object().bucket(&self.bucket).key(key)
}
// Lists objects from the current bucket
fn list_objects(&self) -> ListObjectsFluentBuilder {
self.client.list_objects().bucket(&self.bucket)
}
fn reset_frames(&mut self, frame_no: u32) {
let last_sent = self.last_sent_frame_no();
self.next_frame_no.store(frame_no + 1, Ordering::Release);
self.last_sent_frame_no
.store(last_sent.min(frame_no), Ordering::Release);
}
// Generates a new generation UUID v7, which contains a timestamp and is binary-sortable.
// This timestamp goes back in time - that allows us to list newest generations
// first in the S3-compatible bucket, under the assumption that fetching newest generations
// is the most common operation.
// NOTICE: at the time of writing, uuid v7 is an unstable feature of the uuid crate
fn generate_generation() -> Uuid {
let ts = uuid::timestamp::Timestamp::now(uuid::NoContext);
Self::generation_from_timestamp(ts)
}
fn generation_from_timestamp(ts: uuid::Timestamp) -> Uuid {
let (seconds, nanos) = ts.to_unix();
let (seconds, nanos) = (253370761200 - seconds, 999999999 - nanos);
let synthetic_ts = uuid::Timestamp::from_unix(uuid::NoContext, seconds, nanos);
crate::uuid_utils::new_v7(synthetic_ts)
}
pub fn generation_to_timestamp(generation: &Uuid) -> Option<uuid::Timestamp> {
let ts = decode_unix_timestamp(generation);
let (seconds, nanos) = ts.to_unix();
let (seconds, nanos) = (253370761200 - seconds, 999999999 - nanos);
Some(uuid::Timestamp::from_unix(NoContext, seconds, nanos))
}
// Starts a new generation for this replicator instance
pub async fn new_generation(&mut self) -> Option<Uuid> {
self.reset_wal_tracker().await;
let curr = Self::generate_generation();
let prev = self.set_generation(curr);
if let Some(prev) = prev {
if prev != curr {
// try to store dependency between previous and current generation
tracing::trace!("New generation {} (parent: {})", curr, prev);
self.store_dependency(prev, curr)
}
}
prev
}
// Sets a generation for this replicator instance. This function
// should be called if a generation number from S3-compatible storage
// is reused in this session.
pub fn set_generation(&mut self, generation: Uuid) -> Option<Uuid> {
let prev_generation = self.generation.swap(Some(Arc::new(generation)));
self.reset_frames(0);
if let Some(prev) = prev_generation.as_deref() {
tracing::debug!("Generation changed from {} -> {}", prev, generation);
Some(*prev)
} else {
tracing::debug!("Generation set {}", generation);
None
}
}
pub fn generation(&self) -> Result<Uuid> {
let guard = self.generation.load();
guard
.as_deref()
.cloned()
.ok_or(anyhow!("Replicator generation was not initialized"))
}
/// Request to store dependency between current generation and its predecessor on S3 object.
/// This works asynchronously on best-effort rules, as putting object to S3 introduces an
/// extra undesired latency and this method may be called during SQLite checkpoint.
fn store_dependency(&self, prev: Uuid, curr: Uuid) {
let key = format!("{}-{}/.dep", self.db_name, curr);
let request =
self.client
.put_object()
.bucket(&self.bucket)
.key(key)
.body(ByteStream::from(Bytes::copy_from_slice(
prev.into_bytes().as_slice(),
)));
tokio::spawn(async move {
if let Err(e) = request.send().await {
tracing::error!(
"Failed to store dependency between generations {} -> {}: {}",
prev,
curr,
e
);
} else {
tracing::trace!(
"Stored dependency between parent ({}) and child ({})",
prev,
curr
);
}
});
}
pub async fn get_dependency(&self, generation: &Uuid) -> Result<Option<Uuid>> {
let key = format!("{}-{}/.dep", self.db_name, generation);
let resp = self
.client
.get_object()
.bucket(&self.bucket)
.key(key)
.send()
.await;
match resp {
Ok(out) => {
let bytes = out.body.collect().await?.into_bytes();
let prev_generation = Uuid::from_bytes(bytes.as_ref().try_into()?);
Ok(Some(prev_generation))
}
Err(SdkError::ServiceError(se)) => match se.into_err() {
GetObjectError::NoSuchKey(_) => Ok(None),
e => Err(e.into()),
},
Err(e) => Err(e.into()),
}
}
// Returns the current last valid frame in the replicated log
pub fn peek_last_valid_frame(&self) -> u32 {
self.next_frame_no().saturating_sub(1)
}
// Sets the last valid frame in the replicated log.
pub fn register_last_valid_frame(&mut self, frame: u32) {
let last_valid_frame = self.peek_last_valid_frame();
if frame != last_valid_frame {
// If frame >= last_valid_frame, it comes from a transaction large enough
// that it got split to multiple xFrames calls. In this case, we just
// update the last_valid_frame to this one, all good.
if last_valid_frame != 0 && frame < last_valid_frame {
tracing::error!(
"[BUG] Local max valid frame is {}, while replicator thinks it's {}",
frame,
last_valid_frame
);
}
self.reset_frames(frame);
}
}
/// Submit next `frame_count` of frames to be replicated.
pub fn submit_frames(&mut self, frame_count: u32) {
let prev = self.next_frame_no.fetch_add(frame_count, Ordering::SeqCst);
let last_sent = self.last_sent_frame_no();
let most_recent = prev + frame_count - 1;
if most_recent - last_sent >= self.max_frames_per_batch as u32 {
self.request_flush();
}
}
pub fn request_flush(&self) {
if let Some(tx) = self.flush_trigger.as_ref() {
tracing::trace!("Requesting flush");
let _ = tx.send(());
} else {
tracing::warn!("Cannot request flush - replicator is closing");
}
}
// Drops uncommitted frames newer than given last valid frame
pub fn rollback_to_frame(&mut self, last_valid_frame: u32) {
// NOTICE: O(size), can be optimized to O(removed) if ever needed
self.reset_frames(last_valid_frame);
tracing::debug!("Rolled back to {}", last_valid_frame);
}
// Opens a raw libSQL connection that doesn't checkpoint.
// Useful for reading metadata from the database file.
fn open_db(&self) -> Result<libsql_sys::Connection<libsql_sys::wal::Sqlite3Wal>> {
use libsql_sys::connection::OpenFlags;
use libsql_sys::wal::Sqlite3WalManager;
let flags = OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_URI
| OpenFlags::SQLITE_OPEN_NO_MUTEX;
let conn = libsql_sys::Connection::open(
&self.db_path,
flags,
Sqlite3WalManager::new(),
libsql_sys::connection::NO_AUTOCHECKPOINT, // no checkpointing
self.encryption_config.clone(),
)?;
Ok(conn)
}
// Tries to read the local change counter from the given database file
fn read_change_counter(&self) -> Result<[u8; 4]> {
if !<str as AsRef<Path>>::as_ref(self.db_path.as_str()).try_exists()? {
return Ok([0; 4]);
}
let conn = self.open_db()?;
let change_counter = conn.db_change_counter().map_err(|rc| {
anyhow::anyhow!(
"Failed to read local change counter from `{}`: {rc}",
self.db_path,
)
})?;
tracing::trace!("Local change counter: {change_counter}");
// TODO: we shouldn't leak the connection here but for some reason when this connection get
// dropped it seems to checkpoint the database
if std::env::var("LIBSQL_BOTTOMLESS_DISABLE_INIT_CHECKPOINTING").is_ok()
|| std::env::var("LIBSQL_DISABLE_INIT_CHECKPOINTING").is_ok()
{
std::mem::forget(conn);
}
Ok(change_counter.to_be_bytes())
}
// Tries to read the local page size from the given database file
async fn read_page_size(&self) -> Result<usize> {
let conn = self.open_db()?;
let page_size = conn.query_row("PRAGMA page_size", (), |r| r.get::<usize, usize>(0))?;
tracing::trace!("Local page size: {page_size}");
Ok(page_size)
}
// Returns the compressed database file path and its change counter, extracted
// from the header of page1 at offset 24..27 (as per SQLite documentation).
pub async fn maybe_compress_main_db_file(
db_path: &Path,
compression: CompressionKind,
) -> Result<ByteStream> {
if !tokio::fs::try_exists(db_path).await? {
bail!("database file was not found at `{}`", db_path.display())
}
match compression {
CompressionKind::None => Ok(ByteStream::from_path(db_path).await?),
CompressionKind::Gzip => {
let mut reader = File::open(db_path).await?;
let gzip_path = Self::db_compressed_path(db_path, "gz");
let compressed_file = OpenOptions::new()
.create(true)
.write(true)
.read(true)
.truncate(true)
.open(&gzip_path)
.await?;
let mut writer = GzipEncoder::new(compressed_file);
let size = tokio::io::copy(&mut reader, &mut writer).await?;
writer.shutdown().await?;
tracing::debug!(
"Compressed database file ({} bytes) into `{}`",
size,
gzip_path.display()
);