Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/integration_minio.rs
287 lines · 10.5 KBRaw History
1//! integration_minio — runs the T5 generic `run_client_suite` against the T7
2//! `ObjectStoreClient` backed by a **real MinIO** instance. This is the T7
3//! Definition-of-Done gate ("passes the conformance suite against MinIO").
4//!
5//! The Go test file (`s3/replica_client_test.go`) has no live-MinIO test — those
6//! live in the integration suite — so the conformance contract is the same
7//! `run_client_suite` the file client (T6) passes, exercised here over S3.
8//!
9//! MinIO is **optional**: the test connects to the endpoint first and, if it is
10//! unreachable (no Docker / no MinIO), it prints a clear SKIP note and returns
11//! green rather than blocking the gate (per the task brief). To run it, start
12//! MinIO and create the bucket:
13//!
14//! ```sh
15//! docker run -d --name minio -p 9000:9000 \
16//! -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin \
17//! minio/minio:latest server /data
18//! # then: mc mb local/litestream (or any S3 client)
19//! ```
20//!
21//! Configuration (all have defaults matching the command above):
22//! * `RUSTYRIVER_MINIO_ENDPOINT` (default `http://127.0.0.1:9000`)
23//! * `RUSTYRIVER_MINIO_BUCKET` (default `litestream`)
24//! * `AWS_ACCESS_KEY_ID` (default `minioadmin`)
25//! * `AWS_SECRET_ACCESS_KEY` (default `minioadmin`)
26
27#![cfg(feature = "s3")]
28
29use std::time::{Duration, SystemTime, UNIX_EPOCH};
30
31use celld_ltx::client::object_store::{ObjectStoreClient, ObjectStoreConfig};
32use celld_ltx::client::{run_client_suite, ReplicaClient};
33use celld_ltx::ltx::{self, Header, HEADER_FLAG_NO_CHECKSUM, VERSION};
34use celld_ltx::TXID;
35
36const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:9000";
37const DEFAULT_BUCKET: &str = "litestream";
38const DEFAULT_KEY: &str = "minioadmin";
39
40fn endpoint() -> String {
41 std::env::var("RUSTYRIVER_MINIO_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_string())
42}
43fn bucket() -> String {
44 std::env::var("RUSTYRIVER_MINIO_BUCKET").unwrap_or_else(|_| DEFAULT_BUCKET.to_string())
45}
46fn access_key() -> String {
47 std::env::var("AWS_ACCESS_KEY_ID").unwrap_or_else(|_| DEFAULT_KEY.to_string())
48}
49fn secret_key() -> String {
50 std::env::var("AWS_SECRET_ACCESS_KEY").unwrap_or_else(|_| DEFAULT_KEY.to_string())
51}
52
53/// Returns `(host, port)` parsed from an `http://host:port` endpoint.
54fn endpoint_host_port(ep: &str) -> Option<(String, u16)> {
55 let rest = ep
56 .strip_prefix("http://")
57 .or_else(|| ep.strip_prefix("https://"))?;
58 let hostport = rest.split('/').next()?;
59 let (host, port) = hostport.rsplit_once(':')?;
60 Some((host.to_string(), port.parse().ok()?))
61}
62
63/// `true` if a TCP connection to the MinIO endpoint succeeds within a short
64/// timeout. Used to decide skip-vs-run without blocking.
65fn minio_reachable() -> bool {
66 use std::net::ToSocketAddrs;
67 let ep = endpoint();
68 let Some((host, port)) = endpoint_host_port(&ep) else {
69 return false;
70 };
71 let Ok(mut addrs) = (host.as_str(), port).to_socket_addrs() else {
72 return false;
73 };
74 let Some(addr) = addrs.next() else {
75 return false;
76 };
77 std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(750)).is_ok()
78}
79
80/// A unique path prefix per test run so concurrent / repeated runs don't collide
81/// and the suite always starts from a clean slate (it `delete_all`s first).
82fn unique_path(tag: &str) -> String {
83 let nanos = SystemTime::now()
84 .duration_since(UNIX_EPOCH)
85 .unwrap()
86 .as_nanos();
87 format!("rustyriver-test/{tag}/{nanos}")
88}
89
90fn make_client(path: String) -> ObjectStoreClient {
91 let config = ObjectStoreConfig {
92 bucket: bucket(),
93 path,
94 region: "us-east-1".into(),
95 endpoint: endpoint(),
96 access_key_id: access_key(),
97 secret_access_key: secret_key(),
98 force_path_style: true, // MinIO requires path-style
99 ..Default::default()
100 };
101 ObjectStoreClient::new(config)
102}
103
104#[tokio::test]
105async fn object_store_passes_conformance_suite_vs_minio() {
106 if !minio_reachable() {
107 eprintln!(
108 "SKIP object_store_passes_conformance_suite_vs_minio: MinIO not reachable at {} \
109 (start it with `docker run -d --name minio -p 9000:9000 -e MINIO_ROOT_USER=minioadmin \
110 -e MINIO_ROOT_PASSWORD=minioadmin minio/minio:latest server /data` and create the \
111 `{}` bucket). The client code is exercised by the pure-unit tests regardless.",
112 endpoint(),
113 bucket(),
114 );
115 return;
116 }
117
118 let client = make_client(unique_path("conformance"));
119 // Surface a build/connect failure clearly instead of a generic panic.
120 client
121 .init()
122 .await
123 .expect("init ObjectStoreClient against MinIO");
124
125 run_client_suite(&client).await;
126
127 // Leave no residue behind.
128 client.delete_all().await.expect("final cleanup");
129}
130
131/// Exercises the timestamp-metadata path (`use_metadata = true`): the
132/// `litestream-timestamp` header value written on PUT must be read back via the
133/// `head` fan-out, distinct from the listing's `last_modified`. Ported in spirit
134/// from s3/replica_client.go:679-683 + 1543-1553.
135#[tokio::test]
136async fn object_store_use_metadata_reads_header_timestamp() {
137 if !minio_reachable() {
138 eprintln!("SKIP object_store_use_metadata_reads_header_timestamp: MinIO not reachable");
139 return;
140 }
141
142 let client = make_client(unique_path("metadata"));
143 client.delete_all().await.expect("clean start");
144
145 // Build an LTX file with a specific, non-"now" header timestamp.
146 // 2021-01-01T00:00:00.123Z = 1_609_459_200_123 ms.
147 let header_millis: i64 = 1_609_459_200_123;
148 let data = make_ltx_with_timestamp(TXID(1), TXID(1), 7, header_millis);
149
150 client
151 .write_ltx_file(0, TXID(1), TXID(1), &data)
152 .await
153 .expect("write ltx with timestamp");
154
155 // With use_metadata, created_at must equal the header timestamp we stored,
156 // NOT the wall-clock LastModified of the object.
157 let files = client
158 .ltx_files(0, TXID(0), true)
159 .await
160 .expect("list with metadata");
161 assert_eq!(files.len(), 1, "one file listed");
162 let created = files[0].created_at.expect("created_at present");
163 let got_millis = created
164 .duration_since(UNIX_EPOCH)
165 .expect("after epoch")
166 .as_millis() as i64;
167 assert_eq!(
168 got_millis, header_millis,
169 "use_metadata reads back the LTX header timestamp, not LastModified"
170 );
171
172 client.delete_all().await.expect("cleanup");
173}
174
175/// The 5 MiB multipart boundary: a file at or above the threshold is uploaded
176/// via multipart and round-trips byte-exact. Ported (boundary only) from
177/// `TestReplicaClient_MultipartUploadThreshold` (s3/replica_client_test.go:351).
178#[tokio::test]
179async fn object_store_multipart_upload_round_trips() {
180 if !minio_reachable() {
181 eprintln!("SKIP object_store_multipart_upload_round_trips: MinIO not reachable");
182 return;
183 }
184
185 let client = make_client(unique_path("multipart"));
186 client.delete_all().await.expect("clean start");
187
188 // A ~6 MiB LTX file (above the 5 MiB single-PUT threshold) forces the
189 // multipart path. We pad an LTX file's pages so the encoded file exceeds
190 // 5 MiB while still being a real, decodable LTX file.
191 let data = make_large_ltx(TXID(1), TXID(1), 6 * 1024 * 1024);
192 assert!(
193 data.len() >= 5 * 1024 * 1024,
194 "test file must exceed the multipart threshold (got {} bytes)",
195 data.len()
196 );
197
198 let info = client
199 .write_ltx_file(0, TXID(1), TXID(1), &data)
200 .await
201 .expect("multipart write");
202 assert_eq!(info.size, data.len() as i64);
203
204 // Full read returns identical bytes.
205 let got = client
206 .open_ltx_file(0, TXID(1), TXID(1), 0, 0)
207 .await
208 .expect("read back multipart object");
209 assert_eq!(got, data, "multipart round-trip is byte-exact");
210
211 // Partial (byte-range) read still works on a multipart object.
212 let mid = client
213 .open_ltx_file(0, TXID(1), TXID(1), 100, 64)
214 .await
215 .expect("range read");
216 assert_eq!(mid.as_slice(), &data[100..164], "range read window");
217
218 client.delete_all().await.expect("cleanup");
219}
220
221// ── LTX builders (real, decodable files; mirror client::make_test_ltx_file) ───
222
223fn header(min_txid: TXID, max_txid: TXID, page_size: u32, timestamp: i64, commit: u32) -> Header {
224 Header {
225 version: VERSION,
226 flags: HEADER_FLAG_NO_CHECKSUM,
227 page_size,
228 commit,
229 min_txid,
230 max_txid,
231 timestamp,
232 pre_apply_checksum: 0,
233 wal_offset: 0,
234 wal_size: 0,
235 wal_salt1: 0,
236 wal_salt2: 0,
237 node_id: 0,
238 }
239}
240
241fn make_ltx_with_timestamp(min_txid: TXID, max_txid: TXID, seed: u8, timestamp: i64) -> Vec<u8> {
242 let page_size: u32 = 512;
243 let pages = vec![(1u32, vec![seed; page_size as usize])];
244 let hdr = header(min_txid, max_txid, page_size, timestamp, 1);
245 ltx::encode_file(&hdr, &pages, 0).expect("encode ltx")
246}
247
248/// Build a real LTX file whose *encoded* size is at least `min_bytes` by writing
249/// enough pages of incompressible bytes. The lock page is skipped (LTX forbids
250/// it). Page content comes from a SplitMix64 PRNG seeded per page, so LZ4 cannot
251/// shrink it — keeping the encoded file above the 5 MiB multipart threshold.
252fn make_large_ltx(min_txid: TXID, max_txid: TXID, min_bytes: usize) -> Vec<u8> {
253 let page_size: u32 = 4096;
254 let lock = ltx::lock_pgno(page_size);
255 let n_pages = (min_bytes / page_size as usize) + 8;
256
257 let mut pages: Vec<(u32, Vec<u8>)> = Vec::with_capacity(n_pages);
258 let mut pgno: u32 = 1;
259 let mut commit: u32 = 0;
260 while pages.len() < n_pages {
261 if pgno == lock {
262 pgno += 1;
263 continue;
264 }
265 // SplitMix64-filled page: high-entropy, incompressible, deterministic.
266 let mut state: u64 = 0x9E37_79B9_7F4A_7C15u64.wrapping_mul(pgno as u64 + 1);
267 let mut buf = vec![0u8; page_size as usize];
268 let mut i = 0;
269 while i < buf.len() {
270 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
271 let mut z = state;
272 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
273 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
274 z ^= z >> 31;
275 let bytes = z.to_le_bytes();
276 let take = bytes.len().min(buf.len() - i);
277 buf[i..i + take].copy_from_slice(&bytes[..take]);
278 i += take;
279 }
280 pages.push((pgno, buf));
281 commit = pgno;
282 pgno += 1;
283 }
284
285 let hdr = header(min_txid, max_txid, page_size, 0, commit);
286 ltx::encode_file(&hdr, &pages, 0).expect("encode large ltx")
287}