| 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 | |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::ltx::{self, FileInfo}; |
| 10 | use crate::{ltx_file_path, ltx_level_dir, TXID}; |
| 11 | use async_trait::async_trait; |
| 12 | use std::time::{Duration, UNIX_EPOCH}; |
| 13 | |
| 14 | use super::ReplicaClient; |
| 15 | |
| 16 | /// A `ReplicaClient` that stores LTX files on the local filesystem. |
| 17 | #[derive(Debug, Clone)] |
| 18 | pub struct FileReplicaClient { |
| 19 | path: String, |
| 20 | } |
| 21 | |
| 22 | impl 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 | /// The replica destination path. |
| 29 | pub fn path(&self) -> &str { |
| 30 | &self.path |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | #[async_trait] |
| 35 | impl ReplicaClient for FileReplicaClient { |
| 36 | fn type_name(&self) -> &str { |
| 37 | "file" |
| 38 | } |
| 39 | |
| 40 | async fn ltx_files( |
| 41 | &self, |
| 42 | level: i32, |
| 43 | seek: TXID, |
| 44 | _use_metadata: bool, |
| 45 | ) -> Result<Vec<FileInfo>> { |
| 46 | let dir = ltx_level_dir(&self.path, level as u32); |
| 47 | let mut rd = match tokio::fs::read_dir(&dir).await { |
| 48 | Ok(rd) => rd, |
| 49 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), |
| 50 | Err(e) => return Err(e.into()), |
| 51 | }; |
| 52 | |
| 53 | let mut infos = Vec::new(); |
| 54 | while let Some(entry) = rd.next_entry().await? { |
| 55 | let name = entry.file_name().to_string_lossy().into_owned(); |
| 56 | // ModTime is the timestamp set at write time; skip non-LTX names. |
| 57 | let (min_txid, max_txid) = match ltx::parse_filename(&name) { |
| 58 | Ok(t) => t, |
| 59 | Err(_) => continue, |
| 60 | }; |
| 61 | if min_txid < seek { |
| 62 | continue; |
| 63 | } |
| 64 | let meta = entry.metadata().await?; |
| 65 | infos.push(FileInfo { |
| 66 | level, |
| 67 | min_txid, |
| 68 | max_txid, |
| 69 | size: meta.len() as i64, |
| 70 | created_at: meta.modified().ok(), |
| 71 | ..Default::default() |
| 72 | }); |
| 73 | } |
| 74 | |
| 75 | // Iterator contract: ascending by (level, min_txid, max_txid) |
| 76 | // (ltx.NewFileInfoSliceIterator sorts the slice). |
| 77 | infos.sort_by(|a, b| { |
| 78 | (a.level, a.min_txid.0, a.max_txid.0).cmp(&(b.level, b.min_txid.0, b.max_txid.0)) |
| 79 | }); |
| 80 | Ok(infos) |
| 81 | } |
| 82 | |
| 83 | async fn open_ltx_file( |
| 84 | &self, |
| 85 | level: i32, |
| 86 | min_txid: TXID, |
| 87 | max_txid: TXID, |
| 88 | offset: i64, |
| 89 | size: i64, |
| 90 | ) -> Result<Vec<u8>> { |
| 91 | let path = ltx_file_path(&self.path, level as u32, min_txid, max_txid); |
| 92 | // NotFound is preserved so callers can classify auto-recoverable errors. |
| 93 | let bytes = tokio::fs::read(&path).await.map_err(Error::Io)?; |
| 94 | |
| 95 | let off = offset.max(0) as usize; |
| 96 | if off >= bytes.len() { |
| 97 | return Ok(Vec::new()); |
| 98 | } |
| 99 | // size == 0 means "read to end of file" (NOT zero bytes). |
| 100 | let end = if size <= 0 { |
| 101 | bytes.len() |
| 102 | } else { |
| 103 | (off + size as usize).min(bytes.len()) |
| 104 | }; |
| 105 | Ok(bytes[off..end].to_vec()) |
| 106 | } |
| 107 | |
| 108 | async fn write_ltx_file( |
| 109 | &self, |
| 110 | level: i32, |
| 111 | min_txid: TXID, |
| 112 | max_txid: TXID, |
| 113 | data: &[u8], |
| 114 | ) -> Result<FileInfo> { |
| 115 | // Peek the LTX header timestamp (preserved as the file's creation time). |
| 116 | let header = ltx::Header::parse(data)?; |
| 117 | let created_at = Some(UNIX_EPOCH + Duration::from_millis(header.timestamp.max(0) as u64)); |
| 118 | |
| 119 | let filename = ltx_file_path(&self.path, level as u32, min_txid, max_txid); |
| 120 | let dir = ltx_level_dir(&self.path, level as u32); |
| 121 | tokio::fs::create_dir_all(&dir).await?; |
| 122 | |
| 123 | // Write to a temp file then atomically rename; clean the temp on error. |
| 124 | let tmp = format!("{filename}.tmp"); |
| 125 | if let Err(e) = write_then_rename(&tmp, &filename, data).await { |
| 126 | let _ = tokio::fs::remove_file(&tmp).await; |
| 127 | return Err(e); |
| 128 | } |
| 129 | |
| 130 | Ok(FileInfo { |
| 131 | level, |
| 132 | min_txid, |
| 133 | max_txid, |
| 134 | size: data.len() as i64, |
| 135 | created_at, |
| 136 | ..Default::default() |
| 137 | }) |
| 138 | } |
| 139 | |
| 140 | async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()> { |
| 141 | for info in files { |
| 142 | let path = ltx_file_path(&self.path, info.level as u32, info.min_txid, info.max_txid); |
| 143 | match tokio::fs::remove_file(&path).await { |
| 144 | Ok(()) => {} |
| 145 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} |
| 146 | Err(e) => return Err(e.into()), |
| 147 | } |
| 148 | } |
| 149 | Ok(()) |
| 150 | } |
| 151 | |
| 152 | async fn delete_all(&self) -> Result<()> { |
| 153 | match tokio::fs::remove_dir_all(&self.path).await { |
| 154 | Ok(()) => Ok(()), |
| 155 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), |
| 156 | Err(e) => Err(e.into()), |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// Writes `data` to `tmp`, fsyncs it, and renames it onto `final_path`. |
| 162 | async fn write_then_rename(tmp: &str, final_path: &str, data: &[u8]) -> Result<()> { |
| 163 | use tokio::io::AsyncWriteExt; |
| 164 | let mut f = tokio::fs::File::create(tmp).await?; |
| 165 | f.write_all(data).await?; |
| 166 | f.sync_all().await?; |
| 167 | drop(f); |
| 168 | tokio::fs::rename(tmp, final_path).await?; |
| 169 | Ok(()) |
| 170 | } |
| 171 | |
| 172 | #[cfg(test)] |
| 173 | mod tests { |
| 174 | use super::*; |
| 175 | use crate::client::run_client_suite; |
| 176 | |
| 177 | #[tokio::test] |
| 178 | async fn passes_conformance_suite() { |
| 179 | let dir = tempfile::tempdir().unwrap(); |
| 180 | let client = FileReplicaClient::new(dir.path().to_string_lossy().into_owned()); |
| 181 | run_client_suite(&client).await; |
| 182 | } |
| 183 | |
| 184 | #[test] |
| 185 | fn type_name_is_file() { |
| 186 | assert_eq!(FileReplicaClient::new("/x").type_name(), "file"); |
| 187 | } |
| 188 | |
| 189 | // The file client reads the real golden replica tree (captured from the |
| 190 | // litestream binary): 6 L0 files, in order, each decoding byte-exact. |
| 191 | #[tokio::test] |
| 192 | async fn lists_and_reads_golden_replica() { |
| 193 | let root = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/golden/replica"); |
| 194 | let client = FileReplicaClient::new(root); |
| 195 | |
| 196 | let files = client.ltx_files(0, TXID(0), false).await.unwrap(); |
| 197 | assert_eq!(files.len(), 6, "golden L0 file count"); |
| 198 | let order: Vec<u64> = files.iter().map(|f| f.min_txid.0).collect(); |
| 199 | assert_eq!(order, vec![1, 2, 3, 4, 5, 6], "ascending by txid"); |
| 200 | |
| 201 | for f in &files { |
| 202 | let bytes = client |
| 203 | .open_ltx_file(0, f.min_txid, f.max_txid, 0, 0) |
| 204 | .await |
| 205 | .unwrap(); |
| 206 | assert_eq!(bytes.len() as i64, f.size, "read size matches listing"); |
| 207 | let decoded = ltx::decode_file(&bytes).expect("golden file decodes via client"); |
| 208 | assert_eq!(decoded.header.min_txid, f.min_txid); |
| 209 | } |
| 210 | |
| 211 | // Partial read of the page-index tail (the restore fast-path). |
| 212 | let f = &files[0]; |
| 213 | let tail = client |
| 214 | .open_ltx_file(0, f.min_txid, f.max_txid, f.size - 24, 0) |
| 215 | .await |
| 216 | .unwrap(); |
| 217 | assert_eq!(tail.len(), 24, "tail read returns last 24 bytes"); |
| 218 | } |
| 219 | } |