edgestore-repl 2.2.2

REPL and HTTP server for EdgeStore
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
//! S3RemoteStore — AWS S3 implementation of `RemoteStore`.
//!
//! Stores content-addressed segments as S3 objects. The `RemoteStore` trait is
//! sync (`Send + Sync`); this implementation bridges to the async AWS SDK via
//! an internal Tokio runtime.
//!
//! ## Cargo feature
//!
//! Requires the `s3` feature on `edgestore-repl`:
//!
//! ```toml
//! [dependencies]
//! edgestore-repl = { version = "1.0", features = ["s3"] }
//! ```
//!
//! ## Path layout
//!
//! ```text
//! s3://{bucket}/{prefix}segments/{hash_hex}.dat
//! ```
//!
//! `prefix` is optional and defaults to `""`. If provided it should end with `/`
//! (e.g. `"mydb/"`).
//!
//! ## Local testing
//!
//! Set `EDGESTORE_S3_ENDPOINT_URL=http://localhost:9000` for testing against
//! a MinIO container (`make s3-up`). Credentials and region are resolved via
//! the standard `aws-config` chain (env vars, `~/.aws/credentials`, IAM roles).

use std::sync::Arc;

use aws_config::{meta::region::RegionProviderChain, BehaviorVersion};
use aws_sdk_s3::primitives::ByteStream;

use edgestore::error::EdgestoreError;
use edgestore::RemoteStore;

use crate::wire::hash_to_hex;

/// Maximum S3 list pages per `list()` call. S3 returns at most 1000 objects
/// per page; 10_000 pages covers 10 million segments — far beyond any
/// practical deployment.
const MAX_LIST_PAGES: usize = 10_000;

/// S3-backed implementation of `RemoteStore`.
///
/// # Example
///
/// ```no_run
/// use edgestore::RemoteStore;
/// use edgestore_repl::S3RemoteStore;
///
/// let store = S3RemoteStore::new(
///     "my-bucket",
///     Some("mydb/"),
///     Some("http://localhost:9000"),
/// ).expect("S3RemoteStore::new");
///
/// let hash = [0x42u8; 32];
/// let data = b"hello edgestore";
/// store.upload(&hash, data).expect("upload");
/// ```
pub struct S3RemoteStore {
    client: aws_sdk_s3::Client,
    bucket: String,
    prefix: String,
    /// Runtime we created ourselves. `None` if we are re-using the caller's
    /// runtime — avoids drop-from-async-context panics.
    owned_runtime: Option<Arc<tokio::runtime::Runtime>>,
}

impl S3RemoteStore {
    /// Create a new `S3RemoteStore`.
    ///
    /// # Arguments
    ///
    /// * `bucket` — S3 bucket name.
    /// * `prefix` — Optional key prefix. Should end with `/` if non-empty
    ///   (e.g. `"mydb/"`). Pass `None` for a flat layout.
    /// * `endpoint_url` — Optional custom endpoint URL. Use
    ///   `Some("http://localhost:9000")` for MinIO. Pass `None` to use the
    ///   standard AWS endpoint for the resolved region.
    ///
    /// # Async context safety
    ///
    /// This function may be called from inside an existing Tokio runtime
    /// (e.g. `#[tokio::main]`) or from a purely synchronous context. In
    /// both cases it will not panic.
    pub fn new(
        bucket: impl Into<String>,
        prefix: Option<&str>,
        endpoint_url: Option<&str>,
    ) -> Result<Self, EdgestoreError> {
        let (client, owned_runtime) = match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                let client = tokio::task::block_in_place(|| {
                    handle.block_on(async { Self::build_client(endpoint_url).await })
                });
                (client, None)
            }
            Err(_) => {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| {
                        EdgestoreError::ReplicationError(format!(
                            "failed to create Tokio runtime: {e}"
                        ))
                    })?;
                let client = rt.block_on(async { Self::build_client(endpoint_url).await });
                (client, Some(Arc::new(rt)))
            }
        };

        Ok(Self {
            client,
            bucket: bucket.into(),
            prefix: prefix.unwrap_or("").to_string(),
            owned_runtime,
        })
    }

    async fn build_client(endpoint_url: Option<&str>) -> aws_sdk_s3::Client {
        let region_provider = RegionProviderChain::default_provider().or_else("us-east-1");

        let mut config_loader =
            aws_config::defaults(BehaviorVersion::latest()).region(region_provider);

        if let Some(url) = endpoint_url {
            config_loader = config_loader.endpoint_url(url.to_string());
        }

        let sdk_config = config_loader.load().await;
        let mut s3_builder = aws_sdk_s3::config::Builder::from(&sdk_config);
        if endpoint_url.is_some() {
            // MinIO requires path-style addressing.
            s3_builder = s3_builder.force_path_style(true);
        }
        aws_sdk_s3::Client::from_conf(s3_builder.build())
    }

    fn seg_key(&self, hash: &[u8; 32]) -> String {
        format!("{}segments/{}.dat", self.prefix, hash_to_hex(hash))
    }

    fn aux_key(&self, hash: &[u8; 32], ext: &str) -> String {
        format!("{}segments/{}.{}", self.prefix, hash_to_hex(hash), ext)
    }

    fn validate_ext(ext: &str) -> Result<(), EdgestoreError> {
        assert!(!ext.is_empty(), "ext must not be empty");
        if !ext.bytes().all(|b| b.is_ascii_lowercase()) {
            return Err(EdgestoreError::InvalidOperation(format!(
                "invalid sidecar ext {:?}: only lowercase ASCII letters allowed",
                ext
            )));
        }
        Ok(())
    }

    /// Run an async future to completion, bridging to the caller's runtime
    /// or to our own runtime if none is active.
    fn block_on<F, R>(&self, future: F) -> R
    where
        F: std::future::Future<Output = R> + Send,
        R: Send,
    {
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => tokio::task::block_in_place(|| handle.block_on(future)),
            Err(_) => self
                .owned_runtime
                .as_ref()
                .expect("S3RemoteStore created without a runtime and called outside a runtime")
                .block_on(future),
        }
    }

    /// Create the bucket if it does not exist. Idempotent: succeeds when the
    /// bucket already exists and is owned by the current credentials.
    /// Removes the need for external tooling (aws CLI, mc) in CI and local
    /// test setups — call this once from your test harness after `new()`.
    pub fn ensure_bucket(&self) -> Result<(), EdgestoreError> {
        assert!(!self.bucket.is_empty(), "bucket name must not be empty");
        self.block_on(async {
            match self.client.create_bucket().bucket(&self.bucket).send().await {
                Ok(_) => Ok(()),
                Err(e) => {
                    let svc = e.into_service_error();
                    if svc.is_bucket_already_owned_by_you() || svc.is_bucket_already_exists() {
                        Ok(())
                    } else {
                        Err(EdgestoreError::ReplicationError(format!(
                            "ensure_bucket failed for {}: {svc}",
                            self.bucket
                        )))
                    }
                }
            }
        })
    }

    /// PUT bytes at `key`. Used by both `upload` and `upload_aux`.
    fn put_bytes(&self, key: String, data: &[u8]) -> Result<(), EdgestoreError> {
        assert!(!key.is_empty(), "S3 key must not be empty");
        assert!(!data.is_empty(), "upload data must not be empty");
        self.block_on(async {
            self.client
                .put_object()
                .bucket(&self.bucket)
                .key(&key)
                .body(ByteStream::from(data.to_vec()))
                .send()
                .await
                .map(|_| ())
                .map_err(|e| {
                    EdgestoreError::ReplicationError(format!("S3 put failed for {key}: {e}"))
                })
        })
    }

    /// GET bytes from `key`. Used by both `download` and `download_aux`.
    fn get_bytes(&self, key: String) -> Result<Vec<u8>, EdgestoreError> {
        assert!(!key.is_empty(), "S3 key must not be empty");
        self.block_on(async {
            let output = self
                .client
                .get_object()
                .bucket(&self.bucket)
                .key(&key)
                .send()
                .await
                .map_err(|e| {
                    EdgestoreError::ReplicationError(format!("S3 get failed for {key}: {e}"))
                })?;
            output
                .body
                .collect()
                .await
                .map(|d| d.into_bytes().to_vec())
                .map_err(|e| {
                    EdgestoreError::ReplicationError(format!("S3 body stream error for {key}: {e}"))
                })
        })
    }
}

impl RemoteStore for S3RemoteStore {
    fn upload(&self, hash: &[u8; 32], data: &[u8]) -> Result<(), EdgestoreError> {
        self.put_bytes(self.seg_key(hash), data)
    }

    /// Idempotent PUT using `If-None-Match: *` (BtrLog §5.1, arXiv:2606.27051).
    ///
    /// S3 returns HTTP 412 when the key already exists; we translate that to
    /// `Ok(false)`. Any other error propagates as `Err(_)`.
    fn upload_if_absent(&self, hash: &[u8; 32], data: &[u8]) -> Result<bool, EdgestoreError> {
        let key = self.seg_key(hash);
        assert!(!key.is_empty(), "S3 key must not be empty");
        let result = self.block_on(async {
            self.client
                .put_object()
                .bucket(&self.bucket)
                .key(&key)
                .if_none_match("*")
                .body(ByteStream::from(data.to_vec()))
                .send()
                .await
        });
        match result {
            Ok(_) => Ok(true),
            Err(aws_sdk_s3::error::SdkError::ServiceError(service_err))
                if service_err.raw().status().as_u16() == 412 =>
            {
                Ok(false)
            }
            Err(e) => Err(EdgestoreError::ReplicationError(format!(
                "S3 upload_if_absent failed for {key}: {e}"
            ))),
        }
    }

    fn download(&self, hash: &[u8; 32]) -> Result<Vec<u8>, EdgestoreError> {
        self.get_bytes(self.seg_key(hash))
    }

    fn list(&self) -> Result<Vec<[u8; 32]>, EdgestoreError> {
        let prefix = format!("{}segments/", self.prefix);
        let mut hashes = Vec::new();
        let mut continuation_token: Option<String> = None;
        let mut pages = 0usize;

        loop {
            assert!(
                pages < MAX_LIST_PAGES,
                "S3 list exceeded MAX_LIST_PAGES={MAX_LIST_PAGES}"
            );
            pages += 1;

            let mut req = self
                .client
                .list_objects_v2()
                .bucket(&self.bucket)
                .prefix(&prefix);

            if let Some(token) = continuation_token {
                req = req.continuation_token(token);
            }

            let output = self.block_on(async {
                req.send()
                    .await
                    .map_err(|e| EdgestoreError::ReplicationError(format!("S3 list failed: {e}")))
            })?;

            if let Some(contents) = output.contents {
                for obj in contents {
                    if let Some(key) = obj.key {
                        let stem = key
                            .strip_prefix(&prefix)
                            .and_then(|s| s.strip_suffix(".dat"));
                        if let Some(stem) = stem {
                            if stem.len() == 64 {
                                let parsed: Option<[u8; 32]> = (0..32)
                                    .map(|i| u8::from_str_radix(&stem[i * 2..i * 2 + 2], 16).ok())
                                    .collect::<Option<Vec<u8>>>()
                                    .and_then(|v| v.try_into().ok());
                                if let Some(hash) = parsed {
                                    hashes.push(hash);
                                }
                            }
                        }
                    }
                }
            }

            if output.is_truncated.unwrap_or(false) {
                continuation_token = output.next_continuation_token;
            } else {
                break;
            }
        }

        assert!(pages <= MAX_LIST_PAGES, "pages must not exceed MAX_LIST_PAGES");
        Ok(hashes)
    }

    fn delete(&self, hash: &[u8; 32]) -> Result<(), EdgestoreError> {
        let key = self.seg_key(hash);
        self.block_on(async {
            self.client
                .delete_object()
                .bucket(&self.bucket)
                .key(&key)
                .send()
                .await
                .map(|_| ())
                .map_err(|e| {
                    EdgestoreError::ReplicationError(format!("S3 delete failed for {key}: {e}"))
                })
        })
    }

    fn upload_aux(&self, hash: &[u8; 32], ext: &str, data: &[u8]) -> Result<(), EdgestoreError> {
        Self::validate_ext(ext)?;
        self.put_bytes(self.aux_key(hash, ext), data)
    }

    fn download_aux(&self, hash: &[u8; 32], ext: &str) -> Result<Vec<u8>, EdgestoreError> {
        Self::validate_ext(ext)?;
        self.get_bytes(self.aux_key(hash, ext))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_store() -> Option<S3RemoteStore> {
        let endpoint = std::env::var("EDGESTORE_S3_ENDPOINT_URL").ok()?;
        let bucket =
            std::env::var("EDGESTORE_S3_BUCKET").unwrap_or_else(|_| "edgestore-test".to_string());
        let store = S3RemoteStore::new(&bucket, Some("test/"), Some(&endpoint)).ok()?;
        store.ensure_bucket().ok()?;
        Some(store)
    }

    #[test]
    fn test_upload_download_roundtrip() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let hash = [0xAAu8; 32];
        let data = b"hello edgestore s3";

        store.upload(&hash, data).expect("upload");
        let got = store.download(&hash).expect("download");
        assert_eq!(got, data);
    }

    #[test]
    fn test_upload_twice_no_error() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let hash = [0xBBu8; 32];
        store.upload(&hash, b"data").expect("first");
        store.upload(&hash, b"data").expect("second");
    }

    #[test]
    fn test_list_returns_uploaded_hashes() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let hash1 = [0x01u8; 32];
        let hash2 = [0x02u8; 32];
        let hash3 = [0x03u8; 32];

        store.upload(&hash1, b"a").expect("up1");
        store.upload(&hash2, b"b").expect("up2");
        store.upload(&hash3, b"c").expect("up3");

        let listed = store.list().expect("list");

        for h in [&hash1, &hash2, &hash3] {
            assert!(
                listed.contains(h),
                "listed should contain {}",
                hash_to_hex(h)
            );
        }
    }

    #[test]
    fn test_delete_removes_object() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let hash = [0xCCu8; 32];
        store.upload(&hash, b"segment data").expect("up");
        store.delete(&hash).expect("del");
        assert!(store.download(&hash).is_err());
    }

    #[test]
    fn test_download_not_found() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let hash = [0xDDu8; 32];
        assert!(store.download(&hash).is_err());
    }

    /// Regression: S3RemoteStore::new() must not panic when called from
    /// inside an existing Tokio runtime (e.g. #[tokio::main]).
    #[test]
    fn test_new_from_async_context() {
        let endpoint = match std::env::var("EDGESTORE_S3_ENDPOINT_URL") {
            Ok(u) => u,
            Err(_) => {
                eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
                return;
            }
        };
        let bucket =
            std::env::var("EDGESTORE_S3_BUCKET").unwrap_or_else(|_| "edgestore-test".to_string());

        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let _store = S3RemoteStore::new(&bucket, Some("async_test/"), Some(&endpoint))
                .expect("S3RemoteStore::new must succeed from async context");
        });
    }

    /// Content-addressing invariant: blake3(downloaded) == stored hash.
    /// Detects silent corruption in upload or download path.
    #[test]
    fn test_data_integrity_blake3_hash_matches() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let data = b"content-addressed segment data for integrity check";
        let hash: [u8; 32] = *blake3::hash(data).as_bytes();

        store.upload(&hash, data).expect("upload");
        let got = store.download(&hash).expect("download");

        assert_eq!(got, data, "downloaded bytes must equal uploaded bytes");
        let got_hash: [u8; 32] = *blake3::hash(&got).as_bytes();
        assert_eq!(
            got_hash, hash,
            "blake3(downloaded) must equal the stored key — data is corrupted"
        );
    }

    /// upload_if_absent must return false (not error) on a second call for
    /// the same hash, and must not overwrite the existing data.
    #[test]
    fn test_upload_if_absent_idempotent() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let data_first = b"first write - must survive";
        let data_second = b"second write - must be rejected";
        let hash: [u8; 32] = *blake3::hash(data_first).as_bytes();

        let inserted = store.upload_if_absent(&hash, data_first).expect("first upload_if_absent");
        assert!(inserted, "first call must return true");

        let replaced = store.upload_if_absent(&hash, data_second).expect("second upload_if_absent");
        assert!(!replaced, "second call must return false — object already exists");

        let got = store.download(&hash).expect("download after double write");
        assert_eq!(got, data_first, "data must not be overwritten by second upload_if_absent");
    }

    /// Large segment roundtrip: 1 MiB payload. Guards against body-size bugs
    /// or truncation in the streaming upload/download path.
    #[test]
    fn test_large_segment_roundtrip() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let data: Vec<u8> = (0u32..262_144).map(|i| (i.wrapping_mul(1664525).wrapping_add(1013904223) as u8)).collect();
        assert_eq!(data.len(), 262_144, "1 MiB test payload");
        let hash: [u8; 32] = *blake3::hash(&data).as_bytes();

        let t0 = std::time::Instant::now();
        store.upload(&hash, &data).expect("large upload");
        let upload_ms = t0.elapsed().as_millis();

        let t1 = std::time::Instant::now();
        let got = store.download(&hash).expect("large download");
        let download_ms = t1.elapsed().as_millis();

        let got_hash: [u8; 32] = *blake3::hash(&got).as_bytes();
        assert_eq!(got_hash, hash, "blake3 mismatch on large segment — data corrupted");
        assert_eq!(got.len(), data.len(), "length mismatch after large download");
        assert!(upload_ms < 5_000, "upload took {upload_ms}ms — expected <5s on localhost");
        assert!(download_ms < 5_000, "download took {download_ms}ms — expected <5s on localhost");
    }

    /// Sidecar (aux) roundtrip: upload_aux / download_aux must preserve bytes.
    #[test]
    fn test_aux_sidecar_roundtrip() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let seg_data = b"segment body";
        let hash: [u8; 32] = *blake3::hash(seg_data).as_bytes();
        let sidecar = b"sidecar index payload";

        store.upload(&hash, seg_data).expect("segment upload");
        store.upload_aux(&hash, "idx", sidecar).expect("aux upload");

        let got = store.download_aux(&hash, "idx").expect("aux download");
        assert_eq!(got, sidecar, "sidecar bytes must round-trip unchanged");
    }

    /// Concurrent uploads of the same hash from multiple threads must not
    /// panic, corrupt data, or leave the object missing.
    #[test]
    fn test_concurrent_upload_same_hash_no_corruption() {
        let Some(store) = make_store() else {
            eprintln!("skip: EDGESTORE_S3_ENDPOINT_URL not set");
            return;
        };

        let data = b"concurrent upload payload - all threads write the same bytes";
        let hash: [u8; 32] = *blake3::hash(data).as_bytes();

        let store = std::sync::Arc::new(store);
        let mut handles = Vec::new();
        for _ in 0..8 {
            let s = std::sync::Arc::clone(&store);
            let d = data;
            let h = hash;
            handles.push(std::thread::spawn(move || {
                s.upload(&h, d).expect("concurrent upload must not fail")
            }));
        }
        for handle in handles {
            handle.join().expect("thread must not panic");
        }

        let got = store.download(&hash).expect("download after concurrent uploads");
        let got_hash: [u8; 32] = *blake3::hash(&got).as_bytes();
        assert_eq!(
            got_hash, hash,
            "data corrupted after concurrent uploads — blake3 mismatch"
        );
        assert_eq!(got, data, "byte content must be unchanged after concurrent uploads");
    }
}