Diffinery

homeflare/celldpublic

celld/crates/celld/replication.rs
143 lines · 4.7 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Shared replication primitives for the in-process LTX backend
4//! ([`crate::ltx_repl::LtxRepl`]). Each cell db lives at
5//! `<watch>/<cell>/ltx/e<epoch>/db.sqlite` and replicates to
6//! `cells/<cell>/ltx/e<epoch>/` in the bucket — epoch-in-prefix is the
7//! data-path fence: a stale owner writes a dead prefix.
8use rusqlite::Connection;
9use std::path::PathBuf;
10use std::time::Duration;
11
12/// Outcome of a blocking replication wait on one cell db.
13pub enum SyncWait {
14 /// The latest local commit is in the bucket.
15 Durable,
16 /// The replicator does not track this cell; the caller decides its
17 /// fallback.
18 Unsupported,
19 /// The wait failed or timed out.
20 Failed,
21}
22
23pub struct RestoredSnapshot {
24 pub epoch: u64,
25 path: PathBuf,
26 directory: PathBuf,
27}
28
29impl RestoredSnapshot {
30 pub fn path(&self) -> &std::path::Path {
31 &self.path
32 }
33
34 /// Construct a snapshot whose `directory` is removed on drop, handing the
35 /// caller an inspection copy with RAII cleanup.
36 pub(crate) fn new(epoch: u64, path: PathBuf, directory: PathBuf) -> Self {
37 Self {
38 epoch,
39 path,
40 directory,
41 }
42 }
43}
44
45impl Drop for RestoredSnapshot {
46 fn drop(&mut self) {
47 let _ = std::fs::remove_dir_all(&self.directory);
48 }
49}
50
51#[derive(Clone)]
52pub struct StorageCredentials {
53 pub access_key_id: String,
54 pub secret_access_key: String,
55 pub session_token: Option<String>,
56}
57
58pub struct ActivationOptions<'a> {
59 pub cell: &'a str,
60 pub epoch: u64,
61 /// The epoch-one ownership record was created conditionally by this
62 /// activation. No earlier replica can exist for this cell.
63 pub fresh: bool,
64 /// This activation seized the cell from a DIFFERENT node. When false the
65 /// ownership record still named us at `epoch - 1`, so no other process
66 /// has written the cell since we evicted it and our preserved local
67 /// state is authoritative.
68 pub took_over: bool,
69 /// Open the exact existing local epoch after a certified node-level
70 /// handoff. This path performs no remote discovery or restore.
71 pub resume_local: bool,
72}
73
74pub struct ActivationResult {
75 pub path: PathBuf,
76 pub restored: bool,
77}
78
79/// Enforce a byte ceiling over the preserved snapshots under `watch`,
80/// evicting least-recently-used first. The walk is layout-independent.
81/// `.hibernated` is the pre-2026-08-05 name and is still swept, or a node
82/// upgrading would keep those files forever without counting them.
83pub(crate) fn prune_watch(watch: &std::path::Path, max_bytes: u64) -> (usize, usize, u64) {
84 use celld_logic::cache::CacheEntry;
85 let mut paths = Vec::new();
86 let mut entries = Vec::new();
87 let mut stack = vec![watch.to_path_buf()];
88 while let Some(dir) = stack.pop() {
89 let Ok(read) = std::fs::read_dir(&dir) else {
90 continue;
91 };
92 for item in read.flatten() {
93 let path = item.path();
94 let Ok(meta) = item.metadata() else { continue };
95 if meta.is_dir() {
96 stack.push(path);
97 } else if path
98 .extension()
99 .is_some_and(|ext| ext == "evicted" || ext == "hibernated")
100 {
101 let last_used_ms = meta
102 .modified()
103 .ok()
104 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
105 .map(|d| d.as_millis() as i64)
106 .unwrap_or(0);
107 entries.push(CacheEntry {
108 last_used_ms,
109 bytes: meta.len(),
110 });
111 paths.push(path);
112 }
113 }
114 }
115 let evict = celld_logic::cache::plan_eviction(&entries, max_bytes);
116 for &index in &evict {
117 let _ = std::fs::remove_file(&paths[index]);
118 }
119 let remaining: u64 = entries
120 .iter()
121 .enumerate()
122 .filter(|(index, _)| !evict.contains(index))
123 .map(|(_, entry)| entry.bytes)
124 .sum();
125 (entries.len() - evict.len(), evict.len(), remaining)
126}
127
128/// Copy a live database into a standalone snapshot. SQLite's backup API
129/// includes committed WAL state without checkpointing or interfering with the
130/// replicator's ownership of the WAL.
131pub(crate) fn sqlite_snapshot(
132 source: &std::path::Path,
133 destination: &std::path::Path,
134) -> anyhow::Result<()> {
135 {
136 let source =
137 Connection::open_with_flags(source, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
138 let mut destination = Connection::open(destination)?;
139 let backup = rusqlite::backup::Backup::new(&source, &mut destination)?;
140 backup.run_to_completion(64, Duration::from_millis(5), None)?;
141 }
142 Ok(())
143}