Diffinery

homeflare/celldpublic

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