Diffinery

homeflare/celldpublic

177 lines · 6.3 KBRaw History
1// The stand-alone file replica is an external ReplicaClient backend. Celld
2// production uses the injected local node filesystem and an object client.
3#![allow(clippy::disallowed_methods)]
4
5//! client::file — file-backed `ReplicaClient`.
6//!
7//! Ported from [email protected] `file/replica_client.go` (the v0.5 methods
8//! only; the `*V3` legacy generation shim is not included). On-disk
9//! layout matches upstream: `<root>/ltx/<level>/<minTXID>-<maxTXID>.ltx`, the
10//! same tree the golden fixtures were captured from.
11
12use crate::error::{Error, Result};
13use crate::ltx::{self, FileInfo};
14use crate::{ltx_file_path, ltx_level_dir, TXID};
15use async_trait::async_trait;
16use std::time::{Duration, UNIX_EPOCH};
17
18use super::ReplicaClient;
19
20/// A `ReplicaClient` that stores LTX files on the local filesystem.
21#[derive(Debug, Clone)]
22pub struct FileReplicaClient {
23 path: String,
24}
25
26impl FileReplicaClient {
27 /// Creates a client rooted at `path` (the replica destination directory).
28 pub fn new(path: impl Into<String>) -> Self {
29 FileReplicaClient { path: path.into() }
30 }
31}
32
33#[async_trait]
34impl ReplicaClient for FileReplicaClient {
35 async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>> {
36 let dir = ltx_level_dir(&self.path, level as u32);
37 let mut rd = match tokio::fs::read_dir(&dir).await {
38 Ok(rd) => rd,
39 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
40 Err(e) => return Err(e.into()),
41 };
42
43 let mut infos = Vec::new();
44 while let Some(entry) = rd.next_entry().await? {
45 let name = entry.file_name().to_string_lossy().into_owned();
46 // ModTime is the timestamp set at write time; skip non-LTX names.
47 let (min_txid, max_txid) = match ltx::parse_filename(&name) {
48 Ok(t) => t,
49 Err(_) => continue,
50 };
51 if min_txid < seek {
52 continue;
53 }
54 let meta = entry.metadata().await?;
55 infos.push(FileInfo {
56 level,
57 min_txid,
58 max_txid,
59 size: meta.len() as i64,
60 created_at: meta.modified().ok(),
61 ..Default::default()
62 });
63 }
64
65 // Iterator contract: ascending by (level, min_txid, max_txid)
66 // (ltx.NewFileInfoSliceIterator sorts the slice).
67 infos.sort_by(|a, b| {
68 (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0))
69 });
70 Ok(infos)
71 }
72
73 async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>> {
74 let path = ltx_file_path(&self.path, level as u32, min_txid, max_txid);
75 // NotFound is preserved so callers can classify auto-recoverable errors.
76 tokio::fs::read(&path).await.map_err(Error::Io)
77 }
78
79 async fn write_ltx_file(
80 &self,
81 level: i32,
82 min_txid: TXID,
83 max_txid: TXID,
84 data: &[u8],
85 ) -> Result<FileInfo> {
86 // Peek the LTX header timestamp (preserved as the file's creation time).
87 let header = ltx::Header::parse(data)?;
88 let created_at = Some(UNIX_EPOCH + Duration::from_millis(header.timestamp.max(0) as u64));
89
90 let filename = ltx_file_path(&self.path, level as u32, min_txid, max_txid);
91 let dir = ltx_level_dir(&self.path, level as u32);
92 tokio::fs::create_dir_all(&dir).await?;
93
94 // Write to a temp file then atomically rename; clean the temp on error.
95 let tmp = format!("{filename}.tmp");
96 if let Err(e) = write_then_rename(&tmp, &filename, data).await {
97 let _ = tokio::fs::remove_file(&tmp).await;
98 return Err(e);
99 }
100
101 Ok(FileInfo {
102 level,
103 min_txid,
104 max_txid,
105 size: data.len() as i64,
106 created_at,
107 ..Default::default()
108 })
109 }
110
111 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> {
112 for info in files {
113 let path = ltx_file_path(&self.path, info.level as u32, info.min_txid, info.max_txid);
114 match tokio::fs::remove_file(&path).await {
115 Ok(()) => {}
116 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
117 Err(e) => return Err(e.into()),
118 }
119 }
120 Ok(())
121 }
122
123 async fn delete_all(&self) -> Result<()> {
124 match tokio::fs::remove_dir_all(&self.path).await {
125 Ok(()) => Ok(()),
126 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
127 Err(e) => Err(e.into()),
128 }
129 }
130}
131
132/// Writes `data` to `tmp`, fsyncs it, and renames it onto `final_path`.
133async fn write_then_rename(tmp: &str, final_path: &str, data: &[u8]) -> Result<()> {
134 use tokio::io::AsyncWriteExt;
135 let mut f = tokio::fs::File::create(tmp).await?;
136 f.write_all(data).await?;
137 f.sync_all().await?;
138 drop(f);
139 tokio::fs::rename(tmp, final_path).await?;
140 Ok(())
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146 use crate::client::run_client_suite;
147
148 #[tokio::test]
149 async fn passes_conformance_suite() {
150 let dir = tempfile::tempdir().unwrap();
151 let client = FileReplicaClient::new(dir.path().to_string_lossy().into_owned());
152 run_client_suite(&client).await;
153 }
154
155 // The file client reads the real golden replica tree (captured from the
156 // litestream binary): 6 L0 files, in order, each decoding byte-exact.
157 #[tokio::test]
158 async fn lists_and_reads_golden_replica() {
159 let root = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/golden/replica");
160 let client = FileReplicaClient::new(root);
161
162 let files = client.ltx_files(0, TXID(0)).await.unwrap();
163 assert_eq!(files.len(), 6, "golden L0 file count");
164 let order: Vec<u64> = files.iter().map(|f| f.min_txid.0).collect();
165 assert_eq!(order, vec![1, 2, 3, 4, 5, 6], "ascending by txid");
166
167 for f in &files {
168 let bytes = client
169 .open_ltx_file(0, f.min_txid, f.max_txid)
170 .await
171 .unwrap();
172 assert_eq!(bytes.len() as i64, f.size, "read size matches listing");
173 let decoded = ltx::decode_file(&bytes).expect("golden file decodes via client");
174 assert_eq!(decoded.header.min_txid, f.min_txid);
175 }
176 }
177}