-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrelational_db.rs
More file actions
3897 lines (3387 loc) · 142 KB
/
relational_db.rs
File metadata and controls
3897 lines (3387 loc) · 142 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
use crate::db::durability::DurabilityWorker;
use crate::db::MetricsRecorderQueue;
use crate::error::{DBError, RestoreSnapshotError};
use crate::messages::control_db::HostType;
use crate::subscription::ExecutionCounters;
use crate::util::{asyncify, spawn_rayon};
use crate::worker_metrics::WORKER_METRICS;
use anyhow::{anyhow, Context};
use enum_map::EnumMap;
use log::info;
use spacetimedb_commitlog::repo::OnNewSegmentFn;
use spacetimedb_commitlog::{self as commitlog, Commitlog, SizeOnDisk};
use spacetimedb_datastore::db_metrics::DB_METRICS;
use spacetimedb_datastore::error::{DatastoreError, TableError, ViewError};
use spacetimedb_datastore::execution_context::{Workload, WorkloadType};
use spacetimedb_datastore::locking_tx_datastore::datastore::TxMetrics;
use spacetimedb_datastore::locking_tx_datastore::state_view::{
IterByColEqMutTx, IterByColRangeMutTx, IterMutTx, StateView,
};
use spacetimedb_datastore::locking_tx_datastore::{ApplyHistoryCounters, MutTxId, TxId};
use spacetimedb_datastore::system_tables::{
system_tables, StModuleRow, ST_CLIENT_ID, ST_CONNECTION_CREDENTIALS_ID, ST_VIEW_SUB_ID,
};
use spacetimedb_datastore::system_tables::{StFields, StVarFields, StVarName, StVarRow, ST_MODULE_ID, ST_VAR_ID};
use spacetimedb_datastore::traits::{
InsertFlags, IsolationLevel, Metadata, MutTx as _, MutTxDatastore, Program, RowTypeForTable, Tx as _, TxDatastore,
UpdateFlags,
};
use spacetimedb_datastore::{
locking_tx_datastore::{
datastore::Locking,
state_view::{IterByColEqTx, IterByColRangeTx},
},
traits::TxData,
};
use spacetimedb_durability::{self as durability, History};
use spacetimedb_lib::bsatn::ToBsatn;
use spacetimedb_lib::db::auth::StAccess;
use spacetimedb_lib::db::raw_def::v9::{btree, RawModuleDefV9Builder, RawSql};
use spacetimedb_lib::st_var::StVarValue;
use spacetimedb_lib::ConnectionId;
use spacetimedb_lib::Identity;
use spacetimedb_paths::server::{ReplicaDir, SnapshotsPath};
use spacetimedb_primitives::*;
use spacetimedb_sats::algebraic_type::fmt::fmt_algebraic_type;
use spacetimedb_sats::memory_usage::MemoryUsage;
use spacetimedb_sats::{AlgebraicType, AlgebraicValue, ProductType, ProductValue};
use spacetimedb_schema::def::{ModuleDef, TableDef, ViewDef};
use spacetimedb_schema::schema::{
ColumnSchema, IndexSchema, RowLevelSecuritySchema, Schema, SequenceSchema, TableSchema,
};
use spacetimedb_snapshot::{ReconstructedSnapshot, SnapshotError, SnapshotRepository};
use spacetimedb_table::indexes::RowPointer;
use spacetimedb_table::page_pool::PagePool;
use spacetimedb_table::table::{RowRef, TableScanIter};
use spacetimedb_vm::errors::{ErrorType, ErrorVm};
use spacetimedb_vm::ops::parse;
use std::borrow::Cow;
use std::collections::HashSet;
use std::io;
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;
use tokio::sync::watch;
pub use super::persistence::{DiskSizeFn, Durability, Persistence};
pub use super::snapshot::SnapshotWorker;
pub use durability::{DurableOffset, TxOffset};
// NOTE(cloutiertyler): We should be using the associated types, but there is
// a bug in the Rust compiler that prevents us from doing so.
pub type MutTx = MutTxId; //<Locking as spacetimedb_datastore::traits::MutTx>::MutTx;
pub type Tx = TxId; //<Locking as spacetimedb_datastore::traits::Tx>::Tx;
type RowCountFn = Arc<dyn Fn(TableId, &str) -> i64 + Send + Sync>;
/// The type of transactions committed by [RelationalDB].
pub type Txdata = commitlog::payload::Txdata<ProductValue>;
/// We've added a module version field to the system tables, but we don't yet
/// have the infrastructure to support multiple versions.
/// All modules are currently locked to this version, but this will be
/// relaxed post 1.0.
pub const ONLY_MODULE_VERSION: &str = "0.0.1";
/// The set of clients considered connected to the database.
///
/// A client is considered connected if there exists a corresponding row in the
/// `st_clients` system table.
///
/// If rows exist in `st_clients` upon [`RelationalDB::open`], the database was
/// not shut down gracefully. Such "dangling" clients should be removed by
/// calling [`crate::host::ModuleHost::call_identity_connected_disconnected`]
/// for each entry in [`ConnectedClients`].
pub type ConnectedClients = HashSet<(Identity, ConnectionId)>;
pub struct RelationalDB {
database_identity: Identity,
owner_identity: Identity,
inner: Locking,
durability: Option<DurabilityWorker>,
snapshot_worker: Option<SnapshotWorker>,
row_count_fn: RowCountFn,
/// Function to determine the durable size on disk.
/// `Some` if `durability` is `Some`, `None` otherwise.
disk_size_fn: Option<DiskSizeFn>,
/// A map from workload types to their cached prometheus counters.
workload_type_to_exec_counters: Arc<EnumMap<WorkloadType, ExecutionCounters>>,
/// An async queue for recording transaction metrics off the main thread
metrics_recorder_queue: Option<MetricsRecorderQueue>,
}
/// Perform a snapshot every `SNAPSHOT_FREQUENCY` transactions.
// TODO(config): Allow DBs to specify how frequently to snapshot.
// TODO(bikeshedding): Snapshot based on number of bytes written to commitlog, not tx offsets.
//
// NOTE: Replicas must agree on the snapshot frequency. By making them consult
// this value, later introduction of dynamic configuration will allow the
// compiler to find external dependencies.
pub const SNAPSHOT_FREQUENCY: u64 = 1_000_000;
impl std::fmt::Debug for RelationalDB {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RelationalDB")
.field("identity", &self.database_identity)
.finish()
}
}
impl Drop for RelationalDB {
fn drop(&mut self) {
// Attempt to flush the outstanding transactions.
if let Some(worker) = self.durability.take() {
worker.spawn_close(self.database_identity);
}
}
}
impl RelationalDB {
fn new(
database_identity: Identity,
owner_identity: Identity,
inner: Locking,
persistence: Option<Persistence>,
metrics_recorder_queue: Option<MetricsRecorderQueue>,
) -> Self {
let workload_type_to_exec_counters =
Arc::new(EnumMap::from_fn(|ty| ExecutionCounters::new(&ty, &database_identity)));
let (durability, disk_size_fn, snapshot_worker, rt) = Persistence::unzip(persistence);
let durability = durability
.zip(rt)
.map(|(durability, rt)| DurabilityWorker::new(durability, rt));
Self {
inner,
durability,
snapshot_worker,
database_identity,
owner_identity,
row_count_fn: default_row_count_fn(database_identity),
disk_size_fn,
workload_type_to_exec_counters,
metrics_recorder_queue,
}
}
/// Open a database, which may or may not already exist.
///
/// # Initialization
///
/// When this method returns, the internal state of the database has been
/// initialized with nothing written to disk (regardless of the `durability`
/// setting).
///
/// This allows to hand over a pointer to the database to a [`ModuleHost`][ModuleHost]
/// for initialization, which will call [`Self::set_initialized`],
/// initializing the database's [`Metadata`] transactionally.
///
/// If, however, a non-empty `history` was supplied, [`Metadata`] will
/// already be be set. In this case, i.e. if either [`Self::metadata`] or
/// [`Self::program_bytes`] return a `Some` value, [`Self::set_initialized`]
/// should _not_ be called.
///
/// Sometimes, one may want to obtain a database without a module (e.g. for
/// testing). In this case, **always** call [`Self::set_initialized`],
/// supplying a zero `program_hash` and empty `program_bytes`.
///
/// # Parameters
///
/// - `root`
///
/// The database directory. Does not need to exist.
///
/// Note that, even if no `durability` is supplied, the directory will be
/// created and equipped with an advisory lock file.
///
/// - `database_identity`
///
/// The [`Identity`] of the database.
///
/// An error is returned if the database already exists, but has a
/// different identity.
/// If it is a new database, the identity is stored in the database's
/// system tables upon calling [`Self::set_initialized`].
///
/// - `owner_identity`
///
/// The [`Identity`] of the database's owner.
///
/// An error is returned if the database already exists, but has a
/// different owner.
/// If it is a new database, the identity is stored in the database's
/// system tables upon calling [`Self::set_initialized`].
///
/// - `history`
///
/// The [`durability::History`] to restore the database from.
///
/// If using local durability, this must be a pointer to the same object.
/// [`durability::EmptyHistory`] can be used to start from an empty history.
///
/// - `durability`
///
/// The [`Durability`] implementation to use, along with a [`DiskSizeFn`]
/// reporting its size on disk. The [`DiskSizeFn`] must report zero if
/// this database is a follower instance.
///
/// `None` may be passed to obtain an in-memory only database.
///
/// - `snapshot_repo`
///
/// The [`SnapshotRepository`] which stores snapshots of this database.
/// This is only meaningful if `history` and `durability` are also supplied.
/// If restoring from an existing database, the `snapshot_repo` must
/// store views of the same sequence of TXes as the `history`.
///
/// - `metrics_recorder_queue`
///
/// The send side of a queue for recording transaction metrics.
///
/// # Return values
///
/// Alongside `Self`, [`ConnectedClients`] is returned, which is the set of
/// clients considered connected at the given snapshot and `history`.
///
/// If [`ConnectedClients`] is non-empty, the database did not shut down
/// gracefully. The caller is responsible for disconnecting the clients.
///
/// [ModuleHost]: crate::host::module_host::ModuleHost
#[allow(clippy::too_many_arguments)]
pub fn open(
database_identity: Identity,
owner_identity: Identity,
history: impl durability::History<TxData = Txdata>,
mut persistence: Option<Persistence>,
metrics_recorder_queue: Option<MetricsRecorderQueue>,
page_pool: PagePool,
) -> Result<(Self, ConnectedClients), DBError> {
log::trace!("[{database_identity}] DATABASE: OPEN");
// Check the latest durable TX and restore from a snapshot no newer than it,
// so that you drop TXes which were committed but not durable before the restart.
// TODO: delete or mark as invalid snapshots newer than this.
let durable_tx_offset = persistence
.as_ref()
.map(|p| p.durable_tx_offset())
.transpose()?
.flatten();
let (min_commitlog_offset, _) = history.tx_range_hint();
log::info!("[{database_identity}] DATABASE: durable_tx_offset is {durable_tx_offset:?}");
let start_time = std::time::Instant::now();
let inner = Self::restore_from_snapshot_or_bootstrap(
database_identity,
persistence.as_ref().and_then(|p| p.snapshot_repo()),
durable_tx_offset,
min_commitlog_offset,
page_pool,
)?;
if let Some(persistence) = &mut persistence {
// Sanity check because the snapshot worker could've been used before.
debug_assert!(
persistence
.snapshot_repo()
.map(|repo| repo.database_identity() == database_identity)
.unwrap_or(true),
"snapshot repository does not match database identity",
);
persistence.set_snapshot_state(inner.committed_state.clone());
}
apply_history(&inner, database_identity, history)?;
let elapsed_time = start_time.elapsed();
WORKER_METRICS
.replay_total_time_seconds
.with_label_values(&database_identity)
.set(elapsed_time.as_secs_f64());
let db = Self::new(
database_identity,
owner_identity,
inner,
persistence,
metrics_recorder_queue,
);
db.migrate_system_tables()?;
if let Some(meta) = db.metadata()? {
if meta.database_identity != database_identity {
return Err(anyhow!(
"mismatched database identity: {} != {}",
meta.database_identity,
database_identity
)
.into());
}
if meta.owner_identity != owner_identity {
return Err(anyhow!(
"mismatched owner identity: {} != {}",
meta.owner_identity,
owner_identity
)
.into());
}
};
let connected_clients = db.connected_clients()?;
Ok((db, connected_clients))
}
/// Shut down the database, without dropping it.
///
/// If the database is in-memory only, this does nothing.
/// Otherwise, it instructs the durability layer to shut down
/// and waits until all outstanding transactions are reported as durable.
///
/// After calling this method, calling [Self::commit_tx_downgrade] or
/// [Self::commit_tx] will panic.
///
/// Returns `None` if the database is in-memory only,
/// or nothing has been durably persisted yet.
///
/// Returns the durable [TxOffset] in a `Some` otherwise.
pub async fn shutdown(&self) -> Option<TxOffset> {
if let Some(durability) = &self.durability {
return durability.close().await;
}
None
}
fn migrate_system_tables(&self) -> Result<(), DBError> {
let mut tx = self.begin_mut_tx(IsolationLevel::Serializable, Workload::Internal);
for schema in system_tables() {
if !self.table_id_exists_mut(&tx, &schema.table_id) {
log::info!(
"[{}] DATABASE: adding missing system table {}",
self.database_identity,
schema.table_name
);
// FIXME: `create_table` of tables with sequences
// gives a different initial allocation than is given by `CommittedState::bootstrap_system_tables`.
// See comment in that method.
// This results in requiring `CommittedState::fixup_delete_duplicate_system_sequence_rows`.
// Fix `migrate_system_tables` to create new system sequences
// with the same initial allocation as `bootstrap_system_tables`.
let _ = self.create_table(&mut tx, schema.clone())?;
}
}
let _ = self.commit_tx(tx)?;
self.inner.assert_system_tables_match()?;
Ok(())
}
/// Mark the database as initialized with the given module parameters.
///
/// Records the database's identity, owner and module parameters in the
/// system tables. The transactional context is supplied by the caller.
///
/// It is an error to call this method on an already-initialized database.
///
/// See [`Self::open`] for further information.
pub fn set_initialized(&self, tx: &mut MutTx, host_type: HostType, program: Program) -> Result<(), DBError> {
log::trace!(
"[{}] DATABASE: set initialized owner={} program_hash={}",
self.database_identity,
self.owner_identity,
program.hash
);
// Probably a bug: the database is already initialized.
// Ignore if it would be a no-op.
if let Some(meta) = self.inner.metadata_mut_tx(tx)? {
if program.hash == meta.program_hash
&& self.database_identity == meta.database_identity
&& self.owner_identity == meta.owner_identity
{
return Ok(());
}
return Err(anyhow!("database {} already initialized", self.database_identity).into());
}
let row = StModuleRow {
database_identity: self.database_identity.into(),
owner_identity: self.owner_identity.into(),
program_kind: host_type.into(),
program_hash: program.hash,
program_bytes: program.bytes,
module_version: ONLY_MODULE_VERSION.into(),
};
Ok(tx.insert_via_serialize_bsatn(ST_MODULE_ID, &row).map(drop)?)
}
/// Obtain the [`Metadata`] of this database.
///
/// `None` if the database is not yet fully initialized.
pub fn metadata(&self) -> Result<Option<Metadata>, DBError> {
Ok(self.with_read_only(Workload::Internal, |tx| self.inner.metadata(tx))?)
}
/// Obtain the module associated with this database.
///
/// `None` if the database is not yet fully initialized.
/// Note that a `Some` result may yield an empty slice.
pub fn program(&self) -> Result<Option<Program>, DBError> {
Ok(self.with_read_only(Workload::Internal, |tx| self.inner.program(tx))?)
}
/// Read the set of clients currently connected to the database.
pub fn connected_clients(&self) -> Result<ConnectedClients, DBError> {
self.with_read_only(Workload::Internal, |tx| {
self.inner
.connected_clients(tx)?
.collect::<Result<ConnectedClients, _>>()
})
.map_err(DBError::from)
}
/// Update the module associated with this database.
///
/// The caller must ensure that:
///
/// - `program.hash` is the [`Hash`] over `program.bytes`.
/// - `program.bytes` is a valid module acc. to `host_type`.
/// - the schema updates contained in the module have been applied within
/// the transactional context `tx`.
/// - the `__init__` reducer contained in the module has been executed
/// within the transactional context `tx`.
pub fn update_program(&self, tx: &mut MutTx, host_type: HostType, program: Program) -> Result<(), DBError> {
Ok(self.inner.update_program(tx, host_type.into(), program)?)
}
fn restore_from_snapshot_or_bootstrap(
database_identity: Identity,
snapshot_repo: Option<&SnapshotRepository>,
durable_tx_offset: Option<TxOffset>,
min_commitlog_offset: TxOffset,
page_pool: PagePool,
) -> Result<Locking, RestoreSnapshotError> {
// Try to load the `ReconstructedSnapshot` at `snapshot_offset`.
fn try_load_snapshot(
database_identity: &Identity,
snapshot_repo: &SnapshotRepository,
snapshot_offset: TxOffset,
page_pool: &PagePool,
) -> Result<ReconstructedSnapshot, Box<SnapshotError>> {
log::info!("[{database_identity}] DATABASE: restoring snapshot of tx_offset {snapshot_offset}");
let start = std::time::Instant::now();
let snapshot = snapshot_repo
.read_snapshot(snapshot_offset, page_pool)
.map_err(Box::new)?;
let elapsed_time = start.elapsed();
WORKER_METRICS
.replay_snapshot_read_time_seconds
.with_label_values(database_identity)
.set(elapsed_time.as_secs_f64());
log::info!(
"[{database_identity}] DATABASE: read snapshot of tx_offset {snapshot_offset} in {elapsed_time:?}",
);
Ok(snapshot)
}
// Do restore a `Locking` from the `ReconstructedSnapshot`.
fn restore_from_snapshot(
database_identity: &Identity,
snapshot: ReconstructedSnapshot,
page_pool: PagePool,
) -> Result<Locking, Box<DBError>> {
let start = std::time::Instant::now();
let snapshot_offset = snapshot.tx_offset;
Locking::restore_from_snapshot(snapshot, page_pool)
.inspect(|_| {
let elapsed_time = start.elapsed();
WORKER_METRICS.replay_snapshot_restore_time_seconds.with_label_values(database_identity).set(elapsed_time.as_secs_f64());
log::info!(
"[{database_identity}] DATABASE: restored from snapshot of tx_offset {snapshot_offset} in {elapsed_time:?}",
)
})
.inspect_err(|e| {
log::warn!(
"[{database_identity}] DATABASE: failed to restore snapshot of tx_offset {snapshot_offset}: {e}"
)
})
.map_err(DBError::from)
.map_err(Box::new)
}
// `true` if the `SnapshotError` can be considered transient.
// It is not transient if it has to do with hash verification,
// deserialization or the snapshot format itself.
fn is_transient_error(e: &SnapshotError) -> bool {
match e {
SnapshotError::Open(_)
| SnapshotError::WriteObject { .. }
| SnapshotError::ReadObject { .. }
| SnapshotError::Serialize { .. }
| SnapshotError::Incomplete { .. }
| SnapshotError::NotDirectory { .. }
| SnapshotError::Lockfile(_)
| SnapshotError::Io(_) => true,
SnapshotError::HashMismatch { .. }
| SnapshotError::Deserialize { .. }
| SnapshotError::BadMagic { .. }
| SnapshotError::BadVersion { .. } => false,
}
}
if let Some((snapshot_repo, durable_tx_offset)) = snapshot_repo.zip(durable_tx_offset) {
// Mark any newer snapshots as invalid, as the history past
// `durable_tx_offset` may have been reset and thus diverge from
// any snapshots taken earlier.
snapshot_repo
.invalidate_newer_snapshots(durable_tx_offset)
.map_err(|e| RestoreSnapshotError::Invalidate {
offset: durable_tx_offset,
source: Box::new(e),
})?;
// Try to restore from any snapshot that was taken within the
// range `(min_commitlog_offset + 1)..=durable_tx_offset`.
let mut upper_bound = durable_tx_offset;
loop {
let Some(snapshot_offset) = snapshot_repo
.latest_snapshot_older_than(upper_bound)
.map_err(Box::new)?
else {
break;
};
if min_commitlog_offset > 0 && min_commitlog_offset > snapshot_offset + 1 {
log::debug!("snapshot_offset={snapshot_offset} min_commitlog_offset={min_commitlog_offset}");
break;
}
match try_load_snapshot(&database_identity, snapshot_repo, snapshot_offset, &page_pool) {
Ok(snapshot) if snapshot.database_identity != database_identity => {
return Err(RestoreSnapshotError::IdentityMismatch {
expected: database_identity,
actual: snapshot.database_identity,
});
}
Ok(snapshot) => {
return restore_from_snapshot(&database_identity, snapshot, page_pool)
.map_err(RestoreSnapshotError::Datastore);
}
Err(e) => {
// Invalidate the snapshot if the error is permanent.
// Newly created snapshots should not depend on it.
if !is_transient_error(&e) {
let path = snapshot_repo.snapshot_dir_path(snapshot_offset);
log::info!("invalidating bad snapshot at {}", path.display());
path.rename_invalid().map_err(|e| RestoreSnapshotError::Invalidate {
offset: snapshot_offset,
source: Box::new(e.into()),
})?;
}
// Try the next older one if the error was transient.
//
// `latest_snapshot_older_than` is inclusive of the
// upper bound, so subtract one and give up if there
// are no more offsets to try.
match snapshot_offset.checked_sub(1) {
None => break,
Some(older_than) => upper_bound = older_than,
}
}
}
}
}
log::info!("[{database_identity}] DATABASE: no usable snapshot on disk");
// If we didn't find a snapshot and the commitlog doesn't start at the
// zero-th commit (e.g. due to archiving), there is no way to restore
// the database.
if min_commitlog_offset > 0 {
return Err(RestoreSnapshotError::NoConnectedSnapshot { min_commitlog_offset });
}
Locking::bootstrap(database_identity, page_pool)
.map_err(DBError::from)
.map_err(Box::new)
.map_err(RestoreSnapshotError::Bootstrap)
}
/// Apply the provided [`spacetimedb_durability::History`] onto the database
/// state.
///
/// Consumes `self` in order to ensure exclusive access, and to prevent use
/// of the database in case of an incomplete replay.
/// This restriction may be lifted in the future to allow for "live" followers.
pub fn apply<T>(self, history: T) -> Result<Self, DBError>
where
T: durability::History<TxData = Txdata>,
{
apply_history(&self.inner, self.database_identity, history)?;
Ok(self)
}
/// Returns an approximate row count for a particular table.
/// TODO: Unify this with `Relation::row_count` when more statistics are added.
pub fn row_count(&self, table_id: TableId, table_name: &str) -> i64 {
(self.row_count_fn)(table_id, table_name)
}
/// Update this `RelationalDB` with an approximate row count function.
pub fn with_row_count(mut self, row_count: RowCountFn) -> Self {
self.row_count_fn = row_count;
self
}
/// Returns the identity for this database
pub fn database_identity(&self) -> Identity {
self.database_identity
}
pub fn owner_identity(&self) -> Identity {
self.owner_identity
}
/// The number of bytes on disk occupied by the durability layer.
///
/// If this is an in-memory instance, `Ok(0)` is returned.
pub fn size_on_disk(&self) -> io::Result<SizeOnDisk> {
self.disk_size_fn.as_ref().map_or(Ok(<_>::default()), |f| f())
}
/// The size in bytes of all of the in-memory data in this database.
pub fn size_in_memory(&self) -> usize {
self.inner.heap_usage()
}
/// Update data size metrics.
pub fn update_data_size_metrics(&self) {
let cs = self.inner.committed_state.read();
cs.report_data_size(self.database_identity)
}
pub fn encode_row(row: &ProductValue, bytes: &mut Vec<u8>) {
// TODO: large file storage of the row elements
row.encode(bytes);
}
pub fn schema_for_table_mut(&self, tx: &MutTx, table_id: TableId) -> Result<Arc<TableSchema>, DBError> {
Ok(self.inner.schema_for_table_mut_tx(tx, table_id)?)
}
pub fn schema_for_table(&self, tx: &Tx, table_id: TableId) -> Result<Arc<TableSchema>, DBError> {
Ok(self.inner.schema_for_table_tx(tx, table_id)?)
}
pub fn row_schema_for_table<'tx>(
&self,
tx: &'tx MutTx,
table_id: TableId,
) -> Result<RowTypeForTable<'tx>, DBError> {
Ok(self.inner.row_type_for_table_mut_tx(tx, table_id)?)
}
pub fn get_all_tables_mut(&self, tx: &MutTx) -> Result<Vec<Arc<TableSchema>>, DBError> {
Ok(self.inner.get_all_tables_mut_tx(tx)?)
}
pub fn get_all_tables(&self, tx: &Tx) -> Result<Vec<Arc<TableSchema>>, DBError> {
Ok(self.inner.get_all_tables_tx(tx)?)
}
pub fn table_scheduled_id_and_at(
&self,
tx: &impl StateView,
table_id: TableId,
) -> Result<Option<(ColId, ColId)>, DBError> {
let schema = tx.schema_for_table(table_id)?;
let Some(sched) = &schema.schedule else { return Ok(None) };
let primary_key = schema
.primary_key
.context("scheduled table doesn't have a primary key?")?;
Ok(Some((primary_key, sched.at_column)))
}
pub fn decode_column(
&self,
tx: &MutTx,
table_id: TableId,
col_id: ColId,
bytes: &[u8],
) -> Result<AlgebraicValue, DBError> {
// We need to do a manual bounds check here
// since we want to do `swap_remove` to get an owned value
// in the case of `Cow::Owned` and avoid a `clone`.
let check_bounds = |schema: &ProductType| -> Result<_, DBError> {
let col_idx = col_id.idx();
if col_idx >= schema.elements.len() {
return Err(DatastoreError::Table(TableError::ColumnNotFound(col_id)).into());
}
Ok(col_idx)
};
let row_ty = &*self.row_schema_for_table(tx, table_id)?;
let col_idx = check_bounds(row_ty)?;
let col_ty = &row_ty.elements[col_idx].algebraic_type;
Ok(AlgebraicValue::decode(col_ty, &mut &*bytes)?)
}
/// Returns the execution counters for this database.
pub fn exec_counter_map(&self) -> Arc<EnumMap<WorkloadType, ExecutionCounters>> {
self.workload_type_to_exec_counters.clone()
}
/// Returns the execution counters for `workload_type` for this database.
pub fn exec_counters_for(&self, workload_type: WorkloadType) -> &ExecutionCounters {
&self.workload_type_to_exec_counters[workload_type]
}
/// Begin a transaction.
///
/// **Note**: this call **must** be paired with [`Self::rollback_mut_tx`] or
/// [`Self::commit_tx`], otherwise the database will be left in an invalid
/// state. See also [`Self::with_auto_commit`].
#[tracing::instrument(level = "trace", skip_all)]
pub fn begin_mut_tx(&self, isolation_level: IsolationLevel, workload: Workload) -> MutTx {
log::trace!("BEGIN MUT TX");
let r = self.inner.begin_mut_tx(isolation_level, workload);
log::trace!("ACQUIRED MUT TX");
r
}
#[tracing::instrument(level = "trace", skip_all)]
pub fn begin_tx(&self, workload: Workload) -> Tx {
log::trace!("BEGIN TX");
let r = self.inner.begin_tx(workload);
log::trace!("ACQUIRED TX");
r
}
#[tracing::instrument(level = "trace", skip_all)]
pub fn rollback_mut_tx(&self, tx: MutTx) -> (TxOffset, TxMetrics, String) {
log::trace!("ROLLBACK MUT TX");
self.inner.rollback_mut_tx(tx)
}
#[tracing::instrument(level = "trace", skip_all)]
pub fn rollback_mut_tx_downgrade(&self, tx: MutTx, workload: Workload) -> (TxMetrics, Tx) {
log::trace!("ROLLBACK MUT TX");
self.inner.rollback_mut_tx_downgrade(tx, workload)
}
#[tracing::instrument(level = "trace", skip_all)]
pub fn release_tx(&self, tx: Tx) -> (TxOffset, TxMetrics, String) {
log::trace!("RELEASE TX");
self.inner.release_tx(tx)
}
#[tracing::instrument(level = "trace", skip_all)]
#[allow(clippy::type_complexity)]
pub fn commit_tx(&self, tx: MutTx) -> Result<Option<(TxOffset, Arc<TxData>, TxMetrics, String)>, DBError> {
log::trace!("COMMIT MUT TX");
let reducer_context = tx.ctx.reducer_context().cloned();
// TODO: Never returns `None` -- should it?
let Some((tx_offset, tx_data, tx_metrics, reducer)) = self.inner.commit_mut_tx(tx)? else {
return Ok(None);
};
self.maybe_do_snapshot(&tx_data);
let tx_data = Arc::new(tx_data);
if let Some(durability) = &self.durability {
durability.request_durability(reducer_context, &tx_data);
}
Ok(Some((tx_offset, tx_data, tx_metrics, reducer)))
}
#[tracing::instrument(level = "trace", skip_all)]
pub fn commit_tx_downgrade(&self, tx: MutTx, workload: Workload) -> (Arc<TxData>, TxMetrics, Tx) {
log::trace!("COMMIT MUT TX");
let (tx_data, tx_metrics, tx) = self.inner.commit_mut_tx_downgrade(tx, workload);
self.maybe_do_snapshot(&tx_data);
let tx_data = Arc::new(tx_data);
if let Some(durability) = &self.durability {
durability.request_durability(tx.ctx.reducer_context().cloned(), &tx_data);
}
(tx_data, tx_metrics, tx)
}
/// Get the [`DurableOffset`] of this database, or `None` if this is an
/// in-memory instance.
pub fn durable_tx_offset(&self) -> Option<DurableOffset> {
self.durability
.as_ref()
.map(|durability| durability.durable_tx_offset())
}
/// Decide based on the `committed_state.next_tx_offset`
/// whether to request that the [`SnapshotWorker`] in `self` capture a snapshot of the database.
///
/// Actual snapshotting happens asynchronously in a Tokio worker.
///
/// Snapshotting must happen independent of the durable TX offset known by the [`Durability`]
/// because capturing a snapshot requires access to the committed state,
/// which in the general case may advance beyond the durable TX offset,
/// as our durability is an asynchronous write-behind log.
/// An alternate implementation might keep a second materialized [`CommittedState`]
/// which followed the durable TX offset rather than the committed-not-yet-durable state,
/// in which case we would be able to snapshot only TXes known to be durable.
/// In this implementation, we snapshot the existing [`CommittedState`]
/// which stores the committed-not-yet-durable state.
/// This requires a small amount of additional logic when restoring from a snapshot
/// to ensure we don't restore a snapshot more recent than the durable TX offset.
fn maybe_do_snapshot(&self, tx_data: &TxData) {
if let Some(snapshot_worker) = &self.snapshot_worker {
if let Some(tx_offset) = tx_data.tx_offset() {
if tx_offset % SNAPSHOT_FREQUENCY == 0 {
snapshot_worker.request_snapshot();
}
}
}
}
/// Subscribe to a channel of snapshot offsets.
///
/// If a `snapshot_repo` was provided when this database was opened, this method
/// returns a `watch::Receiver` that updates with the latest [`TxOffset`] a snapshot
/// was taken at.
pub fn subscribe_to_snapshots(&self) -> Option<watch::Receiver<TxOffset>> {
self.snapshot_worker.as_ref().map(|snap| snap.subscribe())
}
/// Run a fallible function in a transaction.
///
/// If the supplied function returns `Ok`, the transaction is automatically
/// committed. Otherwise, the transaction is rolled back.
///
/// This method is provided for convenience, as it allows to safely use the
/// `?` operator in code running within a transaction context. Recall that a
/// [`MutTx`] does not follow the RAII pattern, so the following code is
/// wrong:
///
/// ```ignore
/// let tx = db.begin_mut_tx(IsolationLevel::Serializable);
/// let _ = db.schema_for_table(tx, 42)?;
/// // ...
/// let _ = db.commit_tx(tx)?;
/// ```
///
/// If `schema_for_table` returns an error, the transaction is not properly
/// cleaned up, as the `?` short-circuits. To avoid this, but still be able
/// to use `?`, you can write:
///
/// ```ignore
/// db.with_auto_commit(|tx| {
/// let _ = db.schema_for_table(tx, 42)?;
/// // ...
/// Ok(())
/// })?;
/// ```
pub fn with_auto_commit<F, A, E>(&self, workload: Workload, f: F) -> Result<A, E>
where
F: FnOnce(&mut MutTx) -> Result<A, E>,
E: From<DBError>,
{
let mut tx = self.begin_mut_tx(IsolationLevel::Serializable, workload);
let res = f(&mut tx);
self.finish_tx(tx, res)
}
/// Run a fallible function in a transaction, rolling it back if the
/// function returns `Err`.
///
/// Similar in purpose to [`Self::with_auto_commit`], but returns the
/// [`MutTx`] alongside the `Ok` result of the function `F` without
/// committing the transaction.
pub fn with_auto_rollback<F, A, E>(&self, mut tx: MutTx, f: F) -> Result<(MutTx, A), E>
where
F: FnOnce(&mut MutTx) -> Result<A, E>,
{
let res = f(&mut tx);
self.rollback_on_err(tx, res)
}
/// Run a fallible function in a transaction.
///
/// This is similar to `with_auto_commit`, but regardless of the return value of
/// the fallible function, the transaction will ALWAYS be rolled back. This can be used to
/// emulate a read-only transaction.
///
/// TODO(jgilles): when we support actual read-only transactions, use those here instead.
/// TODO(jgilles, kim): get this merged with the above function (two people had similar ideas
/// at the same time)
pub fn with_read_only<F, T>(&self, workload: Workload, f: F) -> T
where
F: FnOnce(&mut Tx) -> T,
{
let mut tx = self.begin_tx(workload);
let res = f(&mut tx);
let (_tx_offset, tx_metrics, reducer) = self.release_tx(tx);
self.report_read_tx_metrics(reducer, tx_metrics);
res
}
/// Perform the transactional logic for the `tx` according to the `res`
pub fn finish_tx<A, E>(&self, tx: MutTx, res: Result<A, E>) -> Result<A, E>
where
E: From<DBError>,
{
if res.is_err() {
let (_, tx_metrics, reducer) = self.rollback_mut_tx(tx);
self.report_mut_tx_metrics(reducer, tx_metrics, None);
} else {
match self.commit_tx(tx).map_err(E::from)? {
Some((_tx_offset, tx_data, tx_metrics, reducer)) => {
self.report_mut_tx_metrics(reducer, tx_metrics, Some(tx_data));
}
None => panic!("TODO: retry?"),
}
}
res
}
/// Roll back transaction `tx` if `res` is `Err`, otherwise return it
/// alongside the `Ok` value.
pub fn rollback_on_err<A, E>(&self, tx: MutTx, res: Result<A, E>) -> Result<(MutTx, A), E> {
match res {
Err(e) => {
let (_, tx_metrics, reducer) = self.rollback_mut_tx(tx);
self.report_mut_tx_metrics(reducer, tx_metrics, None);
Err(e)
}
Ok(a) => Ok((tx, a)),
}
}
pub(crate) fn alter_table_access(&self, tx: &mut MutTx, name: &str, access: StAccess) -> Result<(), DBError> {
Ok(self.inner.alter_table_access_mut_tx(tx, name, access)?)
}
pub(crate) fn alter_table_row_type(
&self,
tx: &mut MutTx,
table_id: TableId,
column_schemas: Vec<ColumnSchema>,
) -> Result<(), DBError> {
Ok(self.inner.alter_table_row_type_mut_tx(tx, table_id, column_schemas)?)
}
pub(crate) fn add_columns_to_table(
&self,
tx: &mut MutTx,
table_id: TableId,
column_schemas: Vec<ColumnSchema>,
default_values: Vec<AlgebraicValue>,
) -> Result<TableId, DBError> {
Ok(self
.inner
.add_columns_to_table_mut_tx(tx, table_id, column_schemas, default_values)?)
}
/// Reports the `TxMetrics`s passed.