-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.rs
More file actions
2183 lines (2082 loc) · 87.1 KB
/
Copy pathstore.rs
File metadata and controls
2183 lines (2082 loc) · 87.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
//! Redb storage: every acknowledgement follows immediate-durability commits on
//! a quorum. Votes, follower appends, snapshots and purges flush before they
//! complete. A leader of at least three voters defers its own log flush
//! (`lazy_flush`), and applied state reaches redb behind its in-memory
//! publication (`persistence`). Disk work uses Tokio's blocking pool so fsync
//! never blocks Raft heartbeats.
//!
//! A process hosting replicas of several groups keeps them in one database
//! under per-replica table prefixes (`Storage::Shared`). Their appends and
//! applied-state writes commit in shared batches (`shared`): one transaction,
//! and one flush when anything in it must be durable.
mod profile;
use profile::{StoragePhase, StorageTrace};
mod lazy_flush;
mod persistence;
mod shared;
pub use shared::SharedDatabase;
mod partition_storage;
use partition_storage::*;
mod retention;
use retention::*;
mod snapshots;
use snapshots::*;
mod snapshot_data;
use snapshot_data::DeferredImage;
mod backup;
pub(super) use backup::{BackupImage, EntryMark, Shippable, decode_stored_entry, holds_replica};
pub use snapshot_data::SnapshotData;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::{Debug, Display};
use std::ops::RangeBounds;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock as PublishedLock};
use std::time::Instant;
use anyhow::{Context, bail};
use openraft::storage::{LogFlushed, RaftLogStorage, RaftStateMachine};
use openraft::{
BasicNode, Entry, EntryPayload, ErrorSubject, ErrorVerb, LogId, LogState, OptionalSend,
RaftLogReader, RaftSnapshotBuilder, Snapshot as RaftSnapshot, SnapshotMeta, StorageError,
StoredMembership, Vote,
};
use redb::{
Database, Durability, ReadableDatabase, ReadableTable, TableDefinition, TableHandle,
WriteTransaction,
};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::{Mutex, RwLock, watch};
use super::{
ApplyResult, Commit, CommitResult, CompactBatch, PartitionBinding, PartitionInfo, RaftCommand,
Receipt, Receipts, Records, Snapshot, TypeConfig,
partitions::{self, PartitionState, Partitions},
};
/// Where a replica keeps its state.
pub enum Storage {
/// A directory of its own, with the database `flower.redb` inside it.
Directory(PathBuf),
/// The database of the process that hosts it, shared with its other
/// replicas under a table prefix of its own. Snapshot transfers use
/// `directory`.
Shared {
database: Arc<SharedDatabase>,
prefix: String,
directory: PathBuf,
},
}
impl From<PathBuf> for Storage {
fn from(directory: PathBuf) -> Self {
Storage::Directory(directory)
}
}
impl From<&std::path::Path> for Storage {
fn from(directory: &std::path::Path) -> Self {
Storage::Directory(directory.to_owned())
}
}
type Table<K> = TableDefinition<'static, K, &'static [u8]>;
// Application keys are UTF-8, stored as bytes: redb compares bytes as they
// are, where a string key is checked as UTF-8 at every comparison.
type PairTable = Table<(&'static [u8], &'static [u8])>;
/// One replica's tables. Replicas that share a database prefix their names;
/// the empty prefix keeps the names of a database holding a single replica.
#[derive(Clone, Copy)]
pub(super) struct Tables {
meta: Table<&'static str>,
logs: Table<u64>,
data: Table<&'static [u8]>,
requests: Table<&'static [u8]>,
partition_meta: Table<&'static str>,
partition_data: PairTable,
partition_requests: PairTable,
partition_base_data: PairTable,
partition_base_requests: PairTable,
partition_chunks: PairTable,
}
impl Tables {
fn new(prefix: &str) -> Self {
// A replica opens once per storage lifetime; its prefixed names live
// as long as the process.
let name = |table: &'static str| -> &'static str {
if prefix.is_empty() {
table
} else {
Box::leak(format!("{prefix}{table}").into_boxed_str())
}
};
Self {
meta: TableDefinition::new(name("raft_meta_v1")),
logs: TableDefinition::new(name("raft_logs_v1")),
data: TableDefinition::new(name("application_data_v4")),
requests: TableDefinition::new(name("application_requests_v4")),
partition_meta: TableDefinition::new(name("logical_partitions_v1")),
partition_data: TableDefinition::new(name("logical_partition_data_v3")),
partition_requests: TableDefinition::new(name("logical_partition_requests_v3")),
partition_base_data: TableDefinition::new(name("partition_copy_base_data_v3")),
partition_base_requests: TableDefinition::new(name("partition_copy_base_requests_v3")),
partition_chunks: TableDefinition::new(name("partition_difference_chunks_v3")),
}
}
}
// Tests inspect a single-replica database by its unprefixed names.
#[cfg(test)]
const META: TableDefinition<&str, &[u8]> = TableDefinition::new("raft_meta_v1");
#[cfg(test)]
const LOGS: TableDefinition<u64, &[u8]> = TableDefinition::new("raft_logs_v1");
#[cfg(test)]
const DATA: TableDefinition<&[u8], &[u8]> = TableDefinition::new("application_data_v4");
#[cfg(test)]
const REQUESTS: TableDefinition<&[u8], &[u8]> = TableDefinition::new("application_requests_v4");
const STATE_META: &str = "state_v4";
/// How far above the stored version bound a restarted process starts.
const RESTART_MARGIN: u64 = 1 << 24;
// Present when index entries use the current layout.
const INDEX_LAYOUT_META: &str = "index_layout_v2";
const PREVIOUS_STATE_META: &str = "state_v3";
const LEGACY_STATE_META: &str = "state_v2";
// An older binary must fail to decode the retired blob instead of silently
// opening an empty or stale application after this one-way storage migration.
const RETIRED_STATE: &[u8] = br#"{"storage_format":4,"error":"application state uses materialized graph generations and deferred projection recovery; use a current Flower binary"}"#;
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct StoredState {
last_applied: Option<LogId<u64>>,
membership: StoredMembership<u64, BasicNode>,
application: Snapshot,
#[serde(default)]
partitions: Partitions,
}
#[derive(Clone, Serialize, Deserialize)]
struct StateMetadata {
last_applied: Option<LogId<u64>>,
membership: StoredMembership<u64, BasicNode>,
revision: u64,
// Above every version stored so far, which a restart must not reuse;
// persistence raises it to cover what it writes (persistence.rs).
#[serde(default)]
versions: u64,
}
impl From<&StoredState> for StateMetadata {
fn from(state: &StoredState) -> Self {
Self {
last_applied: state.last_applied,
membership: state.membership.clone(),
revision: state.application.revision,
versions: super::versions_high_water(),
}
}
}
/// The application tables as stored now, served from a read snapshot rather
/// than loaded into memory.
fn stored_application(db: &Database, tables: Tables, revision: u64) -> anyhow::Result<Snapshot> {
let (data, requests) = stored_backings(db, tables)?;
Ok(Snapshot {
revision,
data: Records::backed(data),
requests: Receipts::backed(requests),
})
}
/// The application's data and receipt tables in one read snapshot.
fn stored_backings(
db: &Database,
tables: Tables,
) -> anyhow::Result<(Arc<super::backing::Backing>, Arc<super::backing::Backing>)> {
let transaction = db.begin_read()?;
Ok((
Arc::new(super::backing::Backing::plain(
transaction.open_table(tables.data)?,
)),
Arc::new(super::backing::Backing::plain(
transaction.open_table(tables.requests)?,
)),
))
}
/// Versions for a delta's writes, stored with them and published with them,
/// so a record keeps its version when it moves from memory to disk.
#[derive(Default)]
struct DeltaVersions {
data: BTreeMap<String, u64>,
requests: BTreeMap<String, u64>,
}
/// The only application allocations needed to stage an apply are changed keys
/// and new receipts. The locked state remains untouched until atomic commit.
struct ApplicationDelta {
revision: u64,
data: BTreeMap<String, Option<Value>>,
requests: BTreeMap<String, Receipt>,
deleted_requests: BTreeSet<String>,
}
impl ApplicationDelta {
fn new(revision: u64) -> Self {
Self {
revision,
data: BTreeMap::new(),
requests: BTreeMap::new(),
deleted_requests: BTreeSet::new(),
}
}
/// Publish into `state`, with the versions stored with these writes, or
/// fresh ones for state that is not stored that way.
/// Apply the delta to `state` as persistence batch `sequence` writes it.
fn publish(self, state: &mut Snapshot, versions: Option<&DeltaVersions>, sequence: u64) {
for (key, value) in self.data {
match value {
Some(value) => {
let version =
versions.map_or_else(super::next_version, |versions| versions.data[&key]);
state
.data
.insert_versioned(key.clone(), Arc::new(value), version);
}
None => {
state.data.remove(&key);
}
}
state.data.stamp(&key, sequence);
}
for key in self.deleted_requests {
state.requests.remove(&key);
state.requests.stamp(&key, sequence);
}
for (key, receipt) in self.requests {
let version =
versions.map_or_else(super::next_version, |versions| versions.requests[&key]);
state
.requests
.insert_versioned(key.clone(), Arc::new(receipt), version);
state.requests.stamp(&key, sequence);
}
state.revision = self.revision;
}
fn receipt<'a>(&'a self, state: &'a Snapshot, id: &str) -> Option<&'a Receipt> {
self.requests.get(id).or_else(|| {
(!self.deleted_requests.contains(id))
.then(|| state.requests.get(id))
.flatten()
})
}
}
/// A checkpoint and the state it describes, held only while a transfer
/// reads it.
struct SnapshotImage {
meta: SnapshotMeta<u64, BasicNode>,
state: Arc<StoredState>,
}
struct SnapshotCapture {
state: StoredState,
installation: u64,
accounting: super::snapshot_policy::Capture,
}
/// Immutable data and retry history move together only after atomic apply.
/// An already-linearized reader or pipelined writer can retain this view while
/// a later apply is committing, without waiting on its state lock.
#[derive(Clone)]
struct Published {
partitions: Partitions,
last_applied: Option<LogId<u64>>,
revision: u64,
data: Records,
requests: Receipts,
}
impl From<&StoredState> for Published {
fn from(state: &StoredState) -> Self {
Self {
partitions: state.partitions.clone(),
last_applied: state.last_applied,
revision: state.application.revision,
data: state.application.data.clone(),
requests: state.application.requests.clone(),
}
}
}
fn publish(lock: &PublishedLock<Published>, state: &StoredState) {
let next = Published::from(state);
let previous = std::mem::replace(&mut *lock.write().expect("published state lock"), next);
// A snapshot installation can replace the entire tree. Free its old nodes
// outside the publication lock rather than making new readers wait.
drop(previous);
}
/// A log entry as stored: its JSON, packed. Snapshot byte triggers count the
/// JSON, which is what replaying it costs.
fn encode_log(profile: &mut StorageTrace, entry: &Entry<TypeConfig>) -> anyhow::Result<Vec<u8>> {
let json = profile.encode(entry)?;
Ok(match super::packed::pack(&json) {
std::borrow::Cow::Owned(packed) => packed,
std::borrow::Cow::Borrowed(_) => json,
})
}
fn decode_log(bytes: &[u8]) -> anyhow::Result<Entry<TypeConfig>> {
Ok(serde_json::from_slice(&super::packed::unpack(bytes)?)?)
}
/// Appends submitted but not yet committed, in log order.
type AppendingLogs = Arc<PublishedLock<Vec<Arc<Vec<Entry<TypeConfig>>>>>>;
/// One append readable before it commits. Removed once its batch commits
/// (or fails), including when a storage worker panics.
struct PendingAppend {
logs: AppendingLogs,
entries: Arc<Vec<Entry<TypeConfig>>>,
}
impl PendingAppend {
fn publish(logs: &AppendingLogs, entries: Arc<Vec<Entry<TypeConfig>>>) -> Self {
logs.write()
.expect("appending log lock")
.push(entries.clone());
Self {
logs: logs.clone(),
entries,
}
}
}
impl Drop for PendingAppend {
fn drop(&mut self) {
let mut logs = self.logs.write().expect("appending log lock");
if let Some(position) = logs
.iter()
.position(|entries| Arc::ptr_eq(entries, &self.entries))
{
drop(logs.remove(position));
}
}
}
/// This replica's writes queued in shared batches but not yet committed.
/// Batches commit in submission order, so queued writes need no further
/// ordering among themselves; a direct transaction waits until none remain.
#[derive(Default)]
struct PendingWrites {
count: std::sync::atomic::AtomicUsize,
idle: tokio::sync::Notify,
}
struct PendingWrite(Arc<PendingWrites>);
impl Drop for PendingWrite {
fn drop(&mut self) {
if self.0.count.fetch_sub(1, Ordering::AcqRel) == 1 {
self.0.idle.notify_waiters();
}
}
}
impl PendingWrites {
fn begin(self: &Arc<Self>) -> PendingWrite {
self.count.fetch_add(1, Ordering::AcqRel);
PendingWrite(self.clone())
}
async fn idle(&self) {
loop {
let idle = self.idle.notified();
tokio::pin!(idle);
idle.as_mut().enable();
if self.count.load(Ordering::Acquire) == 0 {
return;
}
idle.await;
}
}
}
struct Inner {
id: u64,
shared: Arc<SharedDatabase>,
tables: Tables,
snapshot_directory: PathBuf,
io: Arc<Mutex<()>>,
// Appends queued in shared batches. Their readable suffix lets
// replication overlap the flush; only the completion callback
// establishes durability for Raft.
appending: AppendingLogs,
pending: Arc<PendingWrites>,
// An old asynchronous builder must never replace an installed snapshot,
// including an installation with the same log position.
snapshot_installation: AtomicU64,
// The latest durable checkpoint, without its state: a retained state pins
// a redb read transaction, and redb reuses no page freed after it began.
// Between checkpoints that grew the file by every page each commit
// rewrote. A transfer captures the current state instead.
current_snapshot: PublishedLock<Option<SnapshotMeta<u64, BasicNode>>>,
snapshot_accounting: Arc<super::snapshot_policy::Accounting>,
// This lock orders apply, snapshot capture and install_snapshot. Readers only
// see a new value after its complete redb projection has committed atomically.
state: Arc<RwLock<StoredState>>,
// No await, I/O or user code runs under this lock, only a root-pointer swap
// or clone. Complete retry history shares the same published revision.
published: Arc<PublishedLock<Published>>,
// The current leader's own appends whose flush is deferred.
lazy: Arc<lazy_flush::LazyFlush>,
// Applied states published in memory but not yet written to redb.
persistence: Arc<persistence::Persistence>,
// How many written states the application's read snapshot includes.
backing_persisted: Arc<AtomicU64>,
// Rebases so far, which choose the settled partitions each one moves.
rebase_rounds: Arc<AtomicU64>,
// Partitions replaced wholesale, by the sequence number of that write.
replaced_partitions: Arc<std::sync::Mutex<BTreeMap<String, u64>>>,
// Background writers currently holding this storage.
holders: Arc<persistence::Holders>,
// What each publication wrote, for watches.
changes: super::changes::Sender,
// Apply times and held log entries, for backups.
backup: Arc<backup::Hooks>,
}
#[derive(Clone)]
pub(super) struct Store {
inner: Arc<Inner>,
// Only handles passed into Raft carry this lifetime. Ordinary Consensus and
// HTTP router clones must not delay shutdown. The receiver closes when the
// final Raft log reader/state-machine/snapshot worker releases storage and
// the store has closed.
raft_lifetime: Option<Arc<RaftLifetime>>,
}
/// Once Raft releases its last storage handle, close the store before
/// signaling drain, so a waiting shutdown finds every applied state written
/// and the leader's deferred appends durable.
struct RaftLifetime {
inner: Arc<Inner>,
drained: Option<watch::Sender<()>>,
}
impl Drop for RaftLifetime {
fn drop(&mut self) {
let drained = self.drained.take();
let Ok(runtime) = tokio::runtime::Handle::try_current() else {
return;
};
let store = Store {
inner: self.inner.clone(),
raft_lifetime: None,
};
runtime.spawn(async move {
if let Err(error) = store.close().await {
tracing::error!(target: "flower::storage", error = %format!("{error:#}"), "Raft storage closed without persisting applied state; it replays from the log");
}
drop(store);
drop(drained);
});
}
}
// Field order matters: release the database reference before signaling drain,
// including during unwinding. Cancellation cannot stop a spawn_blocking task.
struct DatabaseWork {
shared: Arc<SharedDatabase>,
_raft_lifetime: Option<Arc<RaftLifetime>>,
}
impl DatabaseWork {
fn run<T>(self, operation: impl FnOnce(&Database) -> T) -> T {
operation(self.shared.database())
}
}
impl Store {
pub(super) async fn open(id: u64, storage: Storage) -> anyhow::Result<Self> {
let (shared, tables, state, directory, snapshot_accounting, current_snapshot) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
let (shared, prefix, directory) = match storage {
Storage::Directory(directory) => (None, String::new(), directory),
Storage::Shared { database, prefix, directory } => (Some(database), prefix, directory),
};
let tables = Tables::new(&prefix);
let directory = if directory.is_absolute() {
directory
} else {
std::env::current_dir()?.join(directory)
};
#[cfg(unix)]
let directories_to_sync = {
let mut paths = vec![directory.clone()];
let mut path = directory.as_path();
while !path.exists() {
let Some(parent) = path.parent() else { break };
paths.push(parent.to_owned());
path = parent;
}
paths
};
std::fs::create_dir_all(&directory).context("create Raft data directory")?;
let shared = match shared {
Some(shared) => shared,
None => SharedDatabase::open(&directory.join("flower.redb"))?,
};
let db = shared.database();
// Hosted replicas and a lone replica never mix in one file.
let names: Vec<String> = db
.begin_read()?
.list_tables()?
.map(|table| table.name().to_owned())
.filter(|name| name != shared::FILE_META.name())
.collect();
if prefix.is_empty() && names.iter().any(|name| name.contains('/')) {
bail!("{} holds the database of several hosted replicas; start it with --replica", directory.display());
}
if !prefix.is_empty() && names.iter().any(|name| !name.contains('/')) {
bail!("{} holds a single replica's database; host replicas in a new data directory", directory.display());
}
let mut transaction = db.begin_write()?;
transaction.set_durability(Durability::Immediate)?;
{
transaction.open_table(tables.logs)?;
let mut meta = transaction.open_table(tables.meta)?;
let prior_id = meta
.get("node_id")?
.map(|value| serde_json::from_slice::<u64>(value.value()))
.transpose()?;
if let Some(prior_id) = prior_id {
if prior_id != id {
bail!("data directory belongs to node {prior_id}, not node {id}");
}
} else {
meta.insert("node_id", serde_json::to_vec(&id)?.as_slice())?;
}
// A leader flushes its own appends lazily, so after a crash
// its log can lack entries its followers hold. Resuming the
// same term at startup would append different entries under
// their log ids. Its own vote comes back uncommitted: it must
// win a later term, which only an up-to-date log can.
let vote = meta
.get("vote")?
.map(|value| serde_json::from_slice::<Vote<u64>>(value.value()))
.transpose()?;
if let Some(vote) = vote
&& vote.committed
&& vote.leader_id.node_id == id
{
let vote = Vote { committed: false, ..vote };
meta.insert("vote", serde_json::to_vec(&vote)?.as_slice())?;
}
}
let mut state = load_application(&transaction, tables)?;
transaction.open_table(tables.data)?;
transaction.open_table(tables.requests)?;
for table in [
tables.partition_data,
tables.partition_requests,
tables.partition_base_data,
tables.partition_base_requests,
tables.partition_chunks,
] {
transaction.open_table(table)?;
}
let checkpoint = recover_checkpoint(&transaction, tables, id, &state)?;
transaction.commit()?;
// Serve the committed tables instead of loading every record.
// Its records were checked when applied; reading every receipt
// again would make startup time grow with retained history.
state.application = stored_application(db, tables, state.application.revision)?;
partition_storage::load_served_partitions(db, tables, &mut state.partitions)?;
let current_snapshot = checkpoint;
let snapshot_index=read_snapshot_metadata(db, tables)?.and_then(|meta|meta.last_log_id.map(|id|id.index));
let applied_index=state.last_applied.map(|id|id.index);
let mut unsnapshotted_bytes=0u128;
if let Some(applied)=applied_index && snapshot_index.is_none_or(|snapshot|snapshot<applied) {
let transaction=db.begin_read()?;
let logs=transaction.open_table(tables.logs)?;
let start=snapshot_index.map_or(std::ops::Bound::Unbounded,std::ops::Bound::Excluded);
for entry in logs.range((start,std::ops::Bound::Included(applied)))? {
unsnapshotted_bytes=unsnapshotted_bytes.saturating_add(super::packed::json_len(entry?.1.value()) as u128);
}
}
let snapshot_accounting=super::snapshot_policy::Accounting::new(unsnapshotted_bytes,applied_index,snapshot_index);
// A file's fsync does not persist newly created directory entries.
// Flush the database's directory and each newly created ancestor.
#[cfg(unix)]
for path in directories_to_sync {
std::fs::File::open(path)?.sync_all()?;
}
Ok((shared, tables, state, directory, snapshot_accounting, current_snapshot))
})
.await
.context("open database worker")??;
let lazy = Arc::new(lazy_flush::LazyFlush::default());
lazy.update_membership(&state.membership);
let store = Self {
inner: Arc::new(Inner {
id,
shared,
tables,
snapshot_directory: directory,
io: Arc::new(Mutex::new(())),
appending: Arc::new(PublishedLock::new(Vec::new())),
pending: Arc::default(),
snapshot_installation: AtomicU64::new(0),
current_snapshot: PublishedLock::new(current_snapshot),
snapshot_accounting,
published: Arc::new(PublishedLock::new(Published::from(&state))),
state: Arc::new(RwLock::new(state)),
lazy: lazy.clone(),
persistence: Arc::default(),
backing_persisted: Arc::default(),
rebase_rounds: Arc::default(),
replaced_partitions: Arc::default(),
holders: Arc::default(),
changes: super::changes::sender(),
backup: Arc::default(),
}),
raft_lifetime: None,
};
lazy_flush::spawn(
Arc::downgrade(&store.inner),
store.inner.holders.clone(),
lazy,
);
Ok(store)
}
/// After Raft has stopped: write every applied state, make the leader's
/// held appends durable, and wait until no background task holds the
/// database, so it can be reopened at once. Raft's storage lifetime runs
/// this before signaling drain.
pub(super) async fn close(&self) -> anyhow::Result<()> {
self.inner.pending.idle().await;
let persisted = self.inner.persistence.drain().await;
lazy_flush::flush(self, &self.inner.lazy).await;
self.inner.holders.idle().await;
persisted
}
/// Leader appends that did not wait for their own flush.
#[cfg(test)]
pub(super) fn deferred_leader_appends(&self) -> u64 {
self.inner.lazy.deferred()
}
/// Wait until every applied state so far has been written.
#[cfg(test)]
pub(super) async fn persisted(&self) -> anyhow::Result<()> {
self.inner.persistence.drain().await
}
pub(super) fn raft_storage(&self) -> (Self, watch::Receiver<()>) {
let (sender, drained) = watch::channel(());
(
Self {
inner: self.inner.clone(),
raft_lifetime: Some(Arc::new(RaftLifetime {
inner: self.inner.clone(),
drained: Some(sender),
})),
},
drained,
)
}
/// Batched commits of this replica's database, shared with any other
/// replica hosted in it.
pub(super) fn storage_metrics(&self) -> Value {
self.inner.shared.metrics()
}
/// The writes of every publication from now on.
pub(super) fn changes(&self) -> tokio::sync::broadcast::Receiver<Arc<super::changes::Changes>> {
self.inner.changes.subscribe()
}
pub(super) fn snapshot_accounting(&self) -> Arc<super::snapshot_policy::Accounting> {
self.inner.snapshot_accounting.clone()
}
fn database_work(&self) -> DatabaseWork {
DatabaseWork {
shared: self.inner.shared.clone(),
_raft_lifetime: self.raft_lifetime.clone(),
}
}
pub(super) async fn snapshot(&self) -> Snapshot {
self.inner.state.read().await.application.clone()
}
/// Queries need no receipts; a projected mutation read retains only the
/// requested receipt allocation from the same published data revision.
pub(super) async fn snapshot_for(&self, request_id: Option<&str>) -> Snapshot {
let state = self.inner.published.read().expect("published state lock");
Snapshot {
revision: state.revision,
data: state.data.clone(),
requests: request_id
.and_then(|id| state.requests.get_shared(id).map(|value| (id, value)))
.map(|(id, receipt)| (id.to_owned(), receipt.clone()))
.into_iter()
.collect(),
}
}
/// The log position and application revision come from the same atomic
/// publication as query data, including blank/membership/rejected entries.
pub(super) fn read_fence(&self) -> anyhow::Result<super::read::ReadFence> {
let state = self.inner.published.read().expect("published state lock");
Ok(super::read::ReadFence {
applied: state
.last_applied
.context("unavailable: no applied Raft state")?,
revision: state.revision,
})
}
/// Test the fence and retain its immutable data root under one short lock.
/// A metrics read followed by an unrelated state read would not establish
/// that the captured state belongs to the observed applied log position.
pub(super) fn snapshot_after_fence(
&self,
fence: &super::read::ReadFence,
) -> anyhow::Result<Option<Snapshot>> {
let state = self.inner.published.read().expect("published state lock");
let Some(applied) = state.last_applied else {
return Ok(None);
};
if applied.index < fence.applied.index {
return Ok(None);
}
if (applied.index == fence.applied.index && applied != fence.applied)
|| applied.leader_id < fence.applied.leader_id
{
bail!("unavailable: local applied log does not match the read fence");
}
if state.revision < fence.revision
|| (applied == fence.applied && state.revision != fence.revision)
{
bail!("unavailable: local application revision does not match the read fence");
}
Ok(Some(Snapshot {
revision: state.revision,
data: state.data.clone(),
requests: Receipts::default(),
}))
}
pub(super) async fn snapshot_for_many(&self, request_ids: &[String]) -> Snapshot {
let state = self.inner.published.read().expect("published state lock");
Snapshot {
revision: state.revision,
data: state.data.clone(),
requests: request_ids
.iter()
.filter_map(|id| state.requests.get_shared(id).map(|value| (id, value)))
.map(|(id, receipt)| (id.clone(), receipt.clone()))
.collect(),
}
}
/// Full writer baseline: cloning both persistent roots is O(1), including
/// arbitrarily old request IDs that can arrive in later pipeline groups.
pub(super) async fn snapshot_for_writer(&self) -> Snapshot {
let state = self.inner.published.read().expect("published state lock");
Snapshot {
revision: state.revision,
data: state.data.clone(),
requests: state.requests.clone(),
}
}
pub(super) fn partition_infos(&self) -> Vec<PartitionInfo> {
self.inner
.published
.read()
.expect("published state lock")
.partitions
.iter()
.map(|(_, state)| state.info.clone())
.collect()
}
pub(super) fn partition_info(&self, id: &str) -> anyhow::Result<PartitionInfo> {
self.inner
.published
.read()
.expect("published state lock")
.partitions
.get(id)
.map(|state| state.info.clone())
.context("partition does not exist")
}
pub(super) fn partition_state(&self, id: &str) -> anyhow::Result<PartitionState> {
self.inner
.published
.read()
.expect("published state lock")
.partitions
.get(id)
.cloned()
.context("partition does not exist")
}
pub(super) fn partition_snapshot(
&self,
binding: &PartitionBinding,
request_id: Option<&str>,
all: bool,
) -> anyhow::Result<Snapshot> {
let state = self.inner.published.read().expect("published state lock");
let snapshot = partitions::active(state.partitions.get(&binding.partition), binding)?;
let requests = if all {
snapshot.requests.clone()
} else {
request_id
.and_then(|id| {
snapshot
.requests
.get(id)
.map(|receipt| (id.to_owned(), receipt.clone()))
})
.into_iter()
.collect()
};
Ok(Snapshot {
revision: snapshot.revision,
data: snapshot.data.clone(),
requests,
})
}
pub(super) fn snapshot_after_fence_scoped(
&self,
fence: &super::read::ReadFence,
binding: Option<&PartitionBinding>,
) -> anyhow::Result<Option<Snapshot>> {
let state = self.inner.published.read().expect("published state lock");
let Some(applied) = state.last_applied else {
return Ok(None);
};
if applied.index < fence.applied.index {
return Ok(None);
}
anyhow::ensure!(
!(applied.index == fence.applied.index && applied != fence.applied)
&& applied.leader_id >= fence.applied.leader_id
&& state.revision >= fence.revision
&& (applied != fence.applied || state.revision == fence.revision),
"local publication does not match read fence"
);
match binding {
Some(binding) => {
let snapshot =
partitions::active(state.partitions.get(&binding.partition), binding)?;
Ok(Some(Snapshot {
revision: snapshot.revision,
data: snapshot.data.clone(),
requests: Receipts::default(),
}))
}
None => Ok(Some(Snapshot {
revision: state.revision,
data: state.data.clone(),
requests: Receipts::default(),
})),
}
}
async fn disk_profiled<T, F>(
&self,
mut profile: StorageTrace,
operation: F,
) -> anyhow::Result<T>
where
T: Send + 'static,
F: FnOnce(&Database, &mut StorageTrace) -> anyhow::Result<T> + Send + 'static,
{
// Move the serialization guard into the blocking task. Even cancellation
// of an awaiting Raft future cannot let a later I/O overtake this one.
let guard = self.inner.io.clone().lock_owned().await;
// A direct transaction follows every write already queued in batches.
self.inner.pending.idle().await;
profile.phase(StoragePhase::IoQueue);
let work = self.database_work();
tokio::task::spawn_blocking(move || {
work.run(|db| {
let span = profile.span();
let _entered = span.enter();
profile.phase(StoragePhase::BlockingQueue);
let result = operation(db, &mut profile);
drop(guard);
profile.report(result.is_ok());
result
})
})
.await
.context("Raft storage worker")?
}
/// Stage a write into the shared database's next batch, in this replica's
/// storage order. It is queued under the order guard, which is released
/// as soon as it is queued: later writes queue behind it, and direct
/// transactions wait until it has committed.
async fn batched(
&self,
durable: bool,
mut profile: StorageTrace,
write: impl FnMut(&WriteTransaction, &mut StorageTrace) -> anyhow::Result<()> + Send + 'static,
) -> anyhow::Result<()> {
let guard = self.inner.io.clone().lock_owned().await;
profile.phase(StoragePhase::IoQueue);
let pending = self.inner.pending.begin();
let submitted =
self.inner
.shared
.submit(durable, profile, self.raft_lifetime.clone(), write);
drop(guard);
// Count it as pending until it commits, even if this caller is cancelled.
tokio::spawn(async move {
let result = submitted.committed().await;
drop(pending);
result
})
.await
.context("Raft storage batch")?
}
async fn read_disk<T, F>(&self, operation: F) -> anyhow::Result<T>
where
T: Send + 'static,
F: FnOnce(&Database) -> anyhow::Result<T> + Send + 'static,
{
// redb read transactions see one committed MVCC revision even while a
// writer is staging or flushing another one. Do not make replication
// log reads queue behind application commits. Writes retain disk_profiled()'s
// ordering/cancellation guard. Log readers also merge the single
// in-flight append, whose callback still waits for the durable flush.
let work = self.database_work();
tokio::task::spawn_blocking(move || work.run(operation))
.await
.context("Raft storage reader")?
}
async fn start_append(
&self,
entries: Vec<Entry<TypeConfig>>,
durability: Durability,
) -> tokio::task::JoinHandle<anyhow::Result<()>> {
let deferred = matches!(durability, Durability::None);
let mut profile = StorageTrace::new(
self.inner.id,
if deferred { "leader_append" } else { "append" },
);
profile.entries(&entries);
profile.phase(StoragePhase::Prepare);
// Acquire before publishing or submitting: appends, votes, truncation,
// purge and application retain their storage order on cancellation.
let guard = self.inner.io.clone().lock_owned().await;
profile.phase(StoragePhase::IoQueue);
let entries = Arc::new(entries);
let appended = PendingAppend::publish(&self.inner.appending, entries.clone());
let pending = self.inner.pending.begin();
let shared = self.inner.shared.clone();