Diffinery

homeflare/celldpublic

171 lines · 6.7 KBRaw History
1//! client — the `ReplicaClient` trait + a generic conformance suite.
2//!
3//! Ported from [email protected] `replica_client.go`. The trait is the storage
4//! abstraction every backend implements; `run_client_suite` is the reusable
5//! conformance test that each backend (T6 file, T7 object_store) must pass.
6//!
7//! # DECISION: buffered I/O for the KEEP scope
8//! Go's `ReplicaClient` uses `io.Reader`/`io.ReadCloser`. We take/return owned
9//! byte buffers (`&[u8]` / `Vec<u8>`) instead. L0 files are bounded in size;
10//! streaming large snapshots is a noted follow-on (logged in OPEN_QUESTIONS).
11
12use crate::error::Result;
13use crate::ltx::{self, FileInfo, Header, HEADER_FLAG_NO_CHECKSUM, VERSION};
14use crate::TXID;
15use async_trait::async_trait;
16
17pub mod file;
18pub mod object_store;
19
20/// Client for reading and writing LTX files on a replica backend.
21///
22/// Ported from the `ReplicaClient` interface (replica_client.go:19-51). Methods
23/// take a compaction `level` (0 = L0, the only level in the one-shot scope).
24#[async_trait]
25pub trait ReplicaClient: Send + Sync {
26 /// Returns all LTX files for `level`, sorted ascending by `min_txid`, that
27 /// start at or after `seek`.
28 async fn ltx_files(&self, level: i32, seek: TXID) -> Result<Vec<FileInfo>>;
29
30 /// Returns at most `limit` LTX files at or after `seek`.
31 ///
32 /// Remote clients can stop their object listing after they collect the
33 /// requested prefix. The default keeps compatibility with local and test
34 /// clients.
35 async fn ltx_files_bounded(
36 &self,
37 level: i32,
38 seek: TXID,
39 limit: usize,
40 ) -> Result<Vec<FileInfo>> {
41 let mut files = self.ltx_files(level, seek).await?;
42 files.truncate(limit);
43 Ok(files)
44 }
45
46 /// Reads an LTX file. Returns an `io::ErrorKind::NotFound` error (wrapped)
47 /// if the file does not exist.
48 async fn open_ltx_file(&self, level: i32, min_txid: TXID, max_txid: TXID) -> Result<Vec<u8>>;
49
50 /// Writes an LTX file to the replica and returns its metadata.
51 async fn write_ltx_file(
52 &self,
53 level: i32,
54 min_txid: TXID,
55 max_txid: TXID,
56 data: &[u8],
57 ) -> Result<FileInfo>;
58
59 /// Deletes the given LTX files.
60 async fn delete_ltx_files(&self, files: &[FileInfo]) -> Result<()>;
61
62 /// Deletes all files on the replica.
63 async fn delete_all(&self) -> Result<()>;
64}
65
66/// Builds a small, valid L0 LTX file for tests. Files use the `NoChecksum` flag
67/// (matching real litestream L0 WAL-segment files), so any `min_txid`/`max_txid`
68/// is valid without a pre-apply checksum. One 512-byte page filled with `seed`.
69pub fn make_test_ltx_file(min_txid: TXID, max_txid: TXID, seed: u8) -> Vec<u8> {
70 let page_size: u32 = 512;
71 let pages = vec![(1u32, vec![seed; page_size as usize])];
72 let header = Header {
73 version: VERSION,
74 flags: HEADER_FLAG_NO_CHECKSUM,
75 page_size,
76 commit: 1,
77 min_txid,
78 max_txid,
79 timestamp: 0,
80 pre_apply_checksum: 0,
81 wal_offset: 0,
82 wal_size: 0,
83 wal_salt1: 0,
84 wal_salt2: 0,
85 node_id: 0,
86 };
87 ltx::encode_file(&header, &pages, 0).expect("encode test ltx file")
88}
89
90/// Generic conformance suite every `ReplicaClient` backend must pass: empty
91/// state, write, listing order, seek filtering, reads, not-found, and deletion.
92/// Call from an async test; panics with a descriptive message on
93/// the first violation.
94///
95/// Ported from the shared `TestReplicaClient_*` behaviors in replica_client_test.go.
96pub async fn run_client_suite<C: ReplicaClient>(client: &C) {
97 // 1. Starts empty.
98 client.delete_all().await.expect("delete_all");
99 let files = client.ltx_files(0, TXID(0)).await.expect("list empty");
100 assert!(files.is_empty(), "replica should start empty");
101
102 // 2. Write a snapshot (txid 1) plus four incremental L0 files.
103 let mut written: Vec<(FileInfo, Vec<u8>)> = Vec::new();
104 for i in 1u64..=5 {
105 let data = make_test_ltx_file(TXID(i), TXID(i), i as u8);
106 let info = client
107 .write_ltx_file(0, TXID(i), TXID(i), &data)
108 .await
109 .unwrap_or_else(|e| panic!("write txid {i}: {e}"));
110 assert_eq!(info.min_txid, TXID(i), "written min txid");
111 assert_eq!(info.max_txid, TXID(i), "written max txid");
112 assert_eq!(info.size, data.len() as i64, "written size");
113 written.push((info, data));
114 }
115
116 // 3. Listing returns all files, ascending by min txid (the brief's sort
117 // invariant — must hold regardless of backend listing order).
118 let listed = client.ltx_files(0, TXID(0)).await.expect("list all");
119 assert_eq!(listed.len(), 5, "all files listed");
120 let order: Vec<u64> = listed.iter().map(|f| f.min_txid.0).collect();
121 assert_eq!(
122 order,
123 vec![1, 2, 3, 4, 5],
124 "files sorted ascending by min txid"
125 );
126
127 // 4. Seek filters to files starting at or after the given txid.
128 let seeked = client.ltx_files(0, TXID(3)).await.expect("seek list");
129 let order: Vec<u64> = seeked.iter().map(|f| f.min_txid.0).collect();
130 assert_eq!(order, vec![3, 4, 5], "seek=3 yields txids >= 3");
131
132 let bounded = client
133 .ltx_files_bounded(0, TXID(2), 2)
134 .await
135 .expect("bounded list");
136 let order: Vec<u64> = bounded.iter().map(|f| f.min_txid.0).collect();
137 assert_eq!(order, vec![2, 3], "bounded listing stops at its limit");
138
139 // 5. Full read returns the exact written bytes, which still decode + verify.
140 for (info, data) in &written {
141 let got = client
142 .open_ltx_file(0, info.min_txid, info.max_txid)
143 .await
144 .expect("full read");
145 assert_eq!(&got, data, "full read matches written bytes");
146 ltx::decode_file(&got).expect("round-tripped file still verifies");
147 }
148
149 // 6. Opening a missing file is an error.
150 let missing = client.open_ltx_file(0, TXID(99), TXID(99)).await;
151 assert!(missing.is_err(), "missing file must error");
152
153 // 7. Deleting a subset removes exactly those files.
154 let to_delete: Vec<FileInfo> = listed.iter().take(2).cloned().collect();
155 client
156 .delete_ltx_files(&to_delete)
157 .await
158 .expect("delete subset");
159 let after = client
160 .ltx_files(0, TXID(0))
161 .await
162 .expect("list after delete");
163 assert_eq!(after.len(), 3, "two files deleted");
164 let order: Vec<u64> = after.iter().map(|f| f.min_txid.0).collect();
165 assert_eq!(order, vec![3, 4, 5], "the first two were removed");
166
167 // 8. delete_all clears everything.
168 client.delete_all().await.expect("delete_all");
169 let empty = client.ltx_files(0, TXID(0)).await.expect("list empty");
170 assert!(empty.is_empty(), "delete_all clears the replica");
171}