Diffinery

homeflare/celldpublic

199 lines · 7.1 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 read_range(
112 &self,
113 level: i32,
114 min: TXID,
115 max: TXID,
116 offset: u64,
117 len: u64,
118 ) -> Result<Vec<u8>> {
119 use tokio::io::{AsyncReadExt, AsyncSeekExt};
120 let mut file =
121 tokio::fs::File::open(ltx_file_path(&self.path, level as u32, min, max)).await?;
122 file.seek(std::io::SeekFrom::Start(offset)).await?;
123 let mut bytes = Vec::new();
124 file.take(len).read_to_end(&mut bytes).await?;
125 Ok(bytes)
126 }
127
128 async fn write_ltx_file_from_file(
129 &self,
130 level: i32,
131 min_txid: TXID,
132 max_txid: TXID,
133 file: crate::host::HostFile,
134 host: crate::LtxHost,
135 ) -> Result<FileInfo> {
136 use tokio::io::AsyncWriteExt;
137 let (mut file, first, size) = super::read_upload_chunk(file, &host, 0, 1 << 20).await?;
138 let header = ltx::Header::parse(&first)?;
139 let filename = ltx_file_path(&self.path, level as u32, min_txid, max_txid);
140 tokio::fs::create_dir_all(ltx_level_dir(&self.path, level as u32)).await?;
141 // The named temporary file owns cleanup on errors and cancellation.
142 let temporary = tempfile::NamedTempFile::new_in(ltx_level_dir(&self.path, level as u32))?;
143 let mut output = tokio::fs::File::from_std(temporary.reopen()?);
144 output.write_all(&first).await?;
145 let mut offset = first.len() as u64;
146 drop(first);
147 while offset < size {
148 let (next_file, bytes, _) =
149 super::read_upload_chunk(file, &host, offset, 1 << 20).await?;
150 file = next_file;
151 output.write_all(&bytes).await?;
152 offset += bytes.len() as u64;
153 }
154 output.sync_all().await?;
155 drop(output);
156 temporary
157 .persist(&filename)
158 .map_err(|error| Error::Io(error.error))?;
159 Ok(FileInfo {
160 level,
161 min_txid,
162 max_txid,
163 size: size as i64,
164 created_at: Some(UNIX_EPOCH + Duration::from_millis(header.timestamp.max(0) as u64)),
165 ..Default::default()
166 })
167 }
168
169 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> {
170 for info in files {
171 let path = ltx_file_path(&self.path, info.level as u32, info.min_txid, info.max_txid);
172 match tokio::fs::remove_file(&path).await {
173 Ok(()) => {}
174 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
175 Err(e) => return Err(e.into()),
176 }
177 }
178 Ok(())
179 }
180
181 async fn delete_all(&self) -> Result<()> {
182 match tokio::fs::remove_dir_all(&self.path).await {
183 Ok(()) => Ok(()),
184 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
185 Err(e) => Err(e.into()),
186 }
187 }
188}
189
190/// Writes `data` to `tmp`, fsyncs it, and renames it onto `final_path`.
191async fn write_then_rename(tmp: &str, final_path: &str, data: &[u8]) -> Result<()> {
192 use tokio::io::AsyncWriteExt;
193 let mut f = tokio::fs::File::create(tmp).await?;
194 f.write_all(data).await?;
195 f.sync_all().await?;
196 drop(f);
197 tokio::fs::rename(tmp, final_path).await?;
198 Ok(())
199}