Diffinery

homeflare/celldpublic

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