Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/integration_minio.rs
223 lines · 8.2 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 run_client_suite(&client).await;
120
121 // Leave no residue behind.
122 client.delete_all().await.expect("final cleanup");
123}
124
125/// The 5 MiB multipart boundary: a file at or above the threshold is uploaded
126/// via multipart and round-trips byte-exact. Ported (boundary only) from
127/// `TestReplicaClient_MultipartUploadThreshold` (s3/replica_client_test.go:351).
128#[tokio::test]
129async fn object_store_multipart_upload_round_trips() {
130 if !minio_reachable() {
131 eprintln!("SKIP object_store_multipart_upload_round_trips: MinIO not reachable");
132 return;
133 }
134
135 let client = make_client(unique_path("multipart"));
136 client.delete_all().await.expect("clean start");
137
138 // A ~6 MiB LTX file (above the 5 MiB single-PUT threshold) forces the
139 // multipart path. We pad an LTX file's pages so the encoded file exceeds
140 // 5 MiB while still being a real, decodable LTX file.
141 let data = make_large_ltx(TXID(1), TXID(1), 6 * 1024 * 1024);
142 assert!(
143 data.len() >= 5 * 1024 * 1024,
144 "test file must exceed the multipart threshold (got {} bytes)",
145 data.len()
146 );
147
148 let info = client
149 .write_ltx_file(0, TXID(1), TXID(1), &data)
150 .await
151 .expect("multipart write");
152 assert_eq!(info.size, data.len() as i64);
153
154 // Full read returns identical bytes.
155 let got = client
156 .open_ltx_file(0, TXID(1), TXID(1))
157 .await
158 .expect("read back multipart object");
159 assert_eq!(got, data, "multipart round-trip is byte-exact");
160
161 client.delete_all().await.expect("cleanup");
162}
163
164// ── LTX builders (real, decodable files; mirror client::make_test_ltx_file) ───
165
166fn header(min_txid: TXID, max_txid: TXID, page_size: u32, commit: u32) -> Header {
167 Header {
168 version: VERSION,
169 flags: HEADER_FLAG_NO_CHECKSUM,
170 page_size,
171 commit,
172 min_txid,
173 max_txid,
174 timestamp: 0,
175 pre_apply_checksum: 0,
176 wal_offset: 0,
177 wal_size: 0,
178 wal_salt1: 0,
179 wal_salt2: 0,
180 node_id: 0,
181 }
182}
183
184/// Build a real LTX file whose *encoded* size is at least `min_bytes` by writing
185/// enough pages of incompressible bytes. The lock page is skipped (LTX forbids
186/// it). Page content comes from a SplitMix64 PRNG seeded per page, so LZ4 cannot
187/// shrink it — keeping the encoded file above the 5 MiB multipart threshold.
188fn make_large_ltx(min_txid: TXID, max_txid: TXID, min_bytes: usize) -> Vec<u8> {
189 let page_size: u32 = 4096;
190 let lock = ltx::lock_pgno(page_size);
191 let n_pages = (min_bytes / page_size as usize) + 8;
192
193 let mut pages: Vec<(u32, Vec<u8>)> = Vec::with_capacity(n_pages);
194 let mut pgno: u32 = 1;
195 let mut commit: u32 = 0;
196 while pages.len() < n_pages {
197 if pgno == lock {
198 pgno += 1;
199 continue;
200 }
201 // SplitMix64-filled page: high-entropy, incompressible, deterministic.
202 let mut state: u64 = 0x9E37_79B9_7F4A_7C15u64.wrapping_mul(pgno as u64 + 1);
203 let mut buf = vec![0u8; page_size as usize];
204 let mut i = 0;
205 while i < buf.len() {
206 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
207 let mut z = state;
208 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
209 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
210 z ^= z >> 31;
211 let bytes = z.to_le_bytes();
212 let take = bytes.len().min(buf.len() - i);
213 buf[i..i + take].copy_from_slice(&bytes[..take]);
214 i += take;
215 }
216 pages.push((pgno, buf));
217 commit = pgno;
218 pgno += 1;
219 }
220
221 let hdr = header(min_txid, max_txid, page_size, commit);
222 ltx::encode_file(&hdr, &pages, 0).expect("encode large ltx")
223}