Diffinery

homeflare/celldpublic

celld/crates/ltx/tests/integration_s3.rs
395 lines · 12.2 KBRaw History
1//! integration_s3 — runs the T5 generic `run_client_suite` against the T7
2//! `ObjectStoreClient` through a real S3-compatible HTTP endpoint.
3//!
4//! The test also verifies provider behavior that the `ReplicaClient` contract
5//! does not expose: byte ranges, object metadata, multipart uploads, and
6//! conditional writes. CI supplies a required fixture. Local runs skip with an
7//! explicit reason when the optional fixture is absent.
8//!
9//! Configuration:
10//! * `CELLD_LTX_S3_ENDPOINT` (default `http://127.0.0.1:7070`)
11//! * `CELLD_LTX_S3_BUCKET` (default `celld-ltx`)
12//! * `CELLD_LTX_S3_REQUIRED=1` (fail instead of skipping)
13//! * `AWS_ACCESS_KEY_ID` (default `celld-ltx-access-key`)
14//! * `AWS_SECRET_ACCESS_KEY` (default `celld-ltx-secret-key`)
15//! * `AWS_REGION` (default `us-east-1`)
16
17#![cfg(feature = "s3")]
18
19use std::sync::atomic::{AtomicU64, Ordering};
20use std::sync::Arc;
21use std::time::{Duration, SystemTime, UNIX_EPOCH};
22
23use celld_ltx::client::object_store::{ObjectStoreClient, ObjectStoreConfig};
24use celld_ltx::client::{run_client_suite, ReplicaClient};
25use celld_ltx::ltx::{self, Header, HEADER_FLAG_NO_CHECKSUM, VERSION};
26use celld_ltx::TXID;
27use futures_util::TryStreamExt;
28use object_store::path::Path as ObjPath;
29use object_store::{
30 Attribute, Error as ObjectStoreError, GetOptions, ObjectStore, PutMode, PutPayload,
31};
32
33const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:7070";
34const DEFAULT_BUCKET: &str = "celld-ltx";
35const DEFAULT_ACCESS_KEY: &str = "celld-ltx-access-key";
36const DEFAULT_SECRET_KEY: &str = "celld-ltx-secret-key";
37const DEFAULT_REGION: &str = "us-east-1";
38const READINESS_TIMEOUT: Duration = Duration::from_secs(5);
39const TIMESTAMP_MILLIS: i64 = 1_609_459_200_123;
40const TIMESTAMP_RFC3339: &str = "2021-01-01T00:00:00.123Z";
41
42static PREFIX_SEQUENCE: AtomicU64 = AtomicU64::new(0);
43
44struct S3Fixture {
45 config: ObjectStoreConfig,
46 store: Arc<dyn ObjectStore>,
47}
48
49impl S3Fixture {
50 fn client(&self) -> ObjectStoreClient {
51 ObjectStoreClient::with_store(self.config.clone(), self.store.clone())
52 }
53}
54
55fn env_or_default(name: &str, default: &str) -> String {
56 std::env::var(name).unwrap_or_else(|_| default.to_string())
57}
58
59fn endpoint() -> String {
60 env_or_default("CELLD_LTX_S3_ENDPOINT", DEFAULT_ENDPOINT)
61}
62
63fn bucket() -> String {
64 env_or_default("CELLD_LTX_S3_BUCKET", DEFAULT_BUCKET)
65}
66
67fn required() -> bool {
68 std::env::var("CELLD_LTX_S3_REQUIRED").as_deref() == Ok("1")
69}
70
71/// A unique path prefix keeps parallel and repeated runs isolated. All cleanup
72/// operations stay below this prefix.
73fn unique_path(tag: &str) -> String {
74 let nanos = SystemTime::now()
75 .duration_since(UNIX_EPOCH)
76 .expect("system clock must be after the Unix epoch")
77 .as_nanos();
78 let sequence = PREFIX_SEQUENCE.fetch_add(1, Ordering::Relaxed);
79 format!(
80 "celld-ltx-test/{tag}/{}-{nanos}-{sequence}",
81 std::process::id()
82 )
83}
84
85fn s3_config(tag: &str) -> ObjectStoreConfig {
86 ObjectStoreConfig {
87 bucket: bucket(),
88 path: unique_path(tag),
89 region: env_or_default("AWS_REGION", DEFAULT_REGION),
90 endpoint: endpoint(),
91 access_key_id: env_or_default("AWS_ACCESS_KEY_ID", DEFAULT_ACCESS_KEY),
92 secret_access_key: env_or_default("AWS_SECRET_ACCESS_KEY", DEFAULT_SECRET_KEY),
93 // The local fixture has no wildcard DNS name, so requests use bucket paths.
94 force_path_style: true,
95 ..Default::default()
96 }
97}
98
99fn fixture_unavailable(
100 test: &str,
101 config: &ObjectStoreConfig,
102 reason: impl std::fmt::Display,
103) -> Option<S3Fixture> {
104 if required() {
105 panic!(
106 "required S3 fixture for {test} is unavailable at endpoint {} bucket {}: {reason}",
107 config.endpoint, config.bucket
108 );
109 }
110
111 eprintln!(
112 "SKIP {test}: optional S3 fixture is unavailable at endpoint {} bucket {}: {reason}",
113 config.endpoint, config.bucket
114 );
115 None
116}
117
118/// Perform a signed, bucket-scoped LIST through the same adapter as the tests.
119/// A TCP listener or an unauthenticated health response is not sufficient.
120async fn ready_fixture(test: &str, tag: &str) -> Option<S3Fixture> {
121 let config = s3_config(tag);
122 let store = match config.build_store() {
123 Ok(store) => store,
124 Err(error) => return fixture_unavailable(test, &config, error),
125 };
126
127 let readiness = tokio::time::timeout(READINESS_TIMEOUT, async {
128 let mut objects = store.list(None);
129 objects.try_next().await
130 })
131 .await;
132
133 match readiness {
134 Ok(Ok(_)) => Some(S3Fixture { config, store }),
135 Ok(Err(error)) => fixture_unavailable(test, &config, error),
136 Err(_) => fixture_unavailable(
137 test,
138 &config,
139 format_args!("S3 LIST exceeded the {READINESS_TIMEOUT:?} timeout"),
140 ),
141 }
142}
143
144#[tokio::test]
145async fn object_store_passes_s3_conformance_suite() {
146 let Some(fixture) =
147 ready_fixture("object_store_passes_s3_conformance_suite", "conformance").await
148 else {
149 return;
150 };
151 let client = fixture.client();
152
153 run_client_suite(&client).await;
154
155 client.delete_all().await.expect("final cleanup");
156}
157
158#[tokio::test]
159async fn object_store_preserves_metadata_and_supports_range_reads() {
160 let Some(fixture) = ready_fixture(
161 "object_store_preserves_metadata_and_supports_range_reads",
162 "metadata-range",
163 )
164 .await
165 else {
166 return;
167 };
168 let client = fixture.client();
169 let data = make_timestamped_ltx(TXID(1), TXID(1), TIMESTAMP_MILLIS);
170
171 client
172 .write_ltx_file(0, TXID(1), TXID(1), &data)
173 .await
174 .expect("write LTX object");
175
176 let key = ObjPath::from(format!(
177 "{}/0000/{}",
178 fixture.config.path,
179 ltx::format_filename(TXID(1), TXID(1))
180 ));
181 let head = fixture
182 .store
183 .get_opts(
184 &key,
185 GetOptions {
186 head: true,
187 ..Default::default()
188 },
189 )
190 .await
191 .expect("HEAD LTX object");
192 let timestamp = head
193 .attributes
194 .get(&Attribute::Metadata("litestream-timestamp".into()))
195 .expect("litestream timestamp metadata");
196 assert_eq!(timestamp.as_ref(), TIMESTAMP_RFC3339);
197
198 let range = (data.len() / 4)..(data.len() * 3 / 4);
199 assert!(range.len() >= 32, "range must cover a nontrivial window");
200 let ranged = fixture
201 .store
202 .get_range(&key, range.clone())
203 .await
204 .expect("range GET LTX object");
205 assert_eq!(ranged.as_ref(), &data[range]);
206
207 client.delete_all().await.expect("cleanup");
208}
209
210/// A file at or above the 5 MiB threshold uses multipart upload and reads back
211/// byte-for-byte. This keeps the boundary from the upstream S3 client test.
212#[tokio::test]
213async fn object_store_multipart_upload_round_trips() {
214 let Some(fixture) =
215 ready_fixture("object_store_multipart_upload_round_trips", "multipart").await
216 else {
217 return;
218 };
219 let client = fixture.client();
220 client.delete_all().await.expect("clean start");
221
222 // Pad a real, decodable LTX file past the multipart threshold.
223 let data = make_large_ltx(TXID(1), TXID(1), 6 * 1024 * 1024);
224 assert!(
225 data.len() >= 5 * 1024 * 1024,
226 "test file must exceed the multipart threshold (got {} bytes)",
227 data.len()
228 );
229
230 let info = client
231 .write_ltx_file(0, TXID(1), TXID(1), &data)
232 .await
233 .expect("multipart write");
234 assert_eq!(info.size, data.len() as i64);
235
236 let got = client
237 .open_ltx_file(0, TXID(1), TXID(1))
238 .await
239 .expect("read back multipart object");
240 assert_eq!(got, data, "multipart round-trip is byte-exact");
241
242 client.delete_all().await.expect("cleanup");
243}
244
245#[tokio::test]
246async fn object_store_rejects_duplicate_create_and_stale_update() {
247 let Some(fixture) = ready_fixture(
248 "object_store_rejects_duplicate_create_and_stale_update",
249 "conditional-put",
250 )
251 .await
252 else {
253 return;
254 };
255 let key = ObjPath::from(format!("{}/conditional", fixture.config.path));
256
257 let first = fixture
258 .store
259 .put_opts(
260 &key,
261 PutPayload::from(b"first".to_vec()),
262 PutMode::Create.into(),
263 )
264 .await
265 .expect("conditional create");
266 let first_etag = first
267 .e_tag
268 .as_deref()
269 .filter(|etag| !etag.is_empty())
270 .expect("conditional create must return an ETag")
271 .to_string();
272
273 let duplicate_error = fixture
274 .store
275 .put_opts(
276 &key,
277 PutPayload::from(b"duplicate".to_vec()),
278 PutMode::Create.into(),
279 )
280 .await
281 .expect_err("duplicate conditional create must fail");
282 assert!(
283 matches!(duplicate_error, ObjectStoreError::AlreadyExists { .. }),
284 "duplicate create returned {duplicate_error}"
285 );
286
287 let second = fixture
288 .store
289 .put_opts(
290 &key,
291 PutPayload::from(b"current".to_vec()),
292 PutMode::Update(first.clone().into()).into(),
293 )
294 .await
295 .expect("update with current ETag");
296 let second_etag = second
297 .e_tag
298 .as_deref()
299 .filter(|etag| !etag.is_empty())
300 .expect("conditional update must return an ETag");
301 assert_ne!(first_etag, second_etag, "the update must change the ETag");
302
303 let stale_error = fixture
304 .store
305 .put_opts(
306 &key,
307 PutPayload::from(b"stale".to_vec()),
308 PutMode::Update(first.into()).into(),
309 )
310 .await
311 .expect_err("update with stale ETag must fail");
312 assert!(
313 matches!(stale_error, ObjectStoreError::Precondition { .. }),
314 "stale update returned {stale_error}"
315 );
316
317 let final_value = fixture
318 .store
319 .get(&key)
320 .await
321 .expect("read final conditional value")
322 .bytes()
323 .await
324 .expect("collect final conditional value");
325 assert_eq!(final_value.as_ref(), b"current");
326
327 fixture.store.delete(&key).await.expect("cleanup");
328}
329
330fn header(min_txid: TXID, max_txid: TXID, page_size: u32, commit: u32, timestamp: i64) -> Header {
331 Header {
332 version: VERSION,
333 flags: HEADER_FLAG_NO_CHECKSUM,
334 page_size,
335 commit,
336 min_txid,
337 max_txid,
338 timestamp,
339 pre_apply_checksum: 0,
340 wal_offset: 0,
341 wal_size: 0,
342 wal_salt1: 0,
343 wal_salt2: 0,
344 node_id: 0,
345 }
346}
347
348fn make_timestamped_ltx(min_txid: TXID, max_txid: TXID, timestamp: i64) -> Vec<u8> {
349 let page_size = 512;
350 let page = (0..page_size).map(|offset| offset as u8).collect();
351 ltx::encode_file(
352 &header(min_txid, max_txid, page_size, 1, timestamp),
353 &[(1, page)],
354 0,
355 )
356 .expect("encode timestamped LTX")
357}
358
359/// Build a real LTX file whose encoded size is at least `min_bytes`.
360fn make_large_ltx(min_txid: TXID, max_txid: TXID, min_bytes: usize) -> Vec<u8> {
361 let page_size: u32 = 4096;
362 let lock = ltx::lock_pgno(page_size);
363 let n_pages = (min_bytes / page_size as usize) + 8;
364
365 let mut pages: Vec<(u32, Vec<u8>)> = Vec::with_capacity(n_pages);
366 let mut pgno: u32 = 1;
367 let mut commit: u32 = 0;
368 while pages.len() < n_pages {
369 if pgno == lock {
370 pgno += 1;
371 continue;
372 }
373 // SplitMix64-filled pages are deterministic and resist compression.
374 let mut state: u64 = 0x9E37_79B9_7F4A_7C15u64.wrapping_mul(pgno as u64 + 1);
375 let mut buf = vec![0u8; page_size as usize];
376 let mut i = 0;
377 while i < buf.len() {
378 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
379 let mut z = state;
380 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
381 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
382 z ^= z >> 31;
383 let bytes = z.to_le_bytes();
384 let take = bytes.len().min(buf.len() - i);
385 buf[i..i + take].copy_from_slice(&bytes[..take]);
386 i += take;
387 }
388 pages.push((pgno, buf));
389 commit = pgno;
390 pgno += 1;
391 }
392
393 let hdr = header(min_txid, max_txid, page_size, commit, 0);
394 ltx::encode_file(&hdr, &pages, 0).expect("encode large LTX")
395}