ch-database 0.1.0

Database and object storage primitives for SQLx, SpacetimeDB, and S3
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
use std::fmt;
use std::fs;
use std::path::PathBuf;
use std::sync::Arc;

use bytes::Bytes;
use object_store::aws::AmazonS3Builder;
use object_store::local::LocalFileSystem;
use object_store::path::Path as ObjectPath;
use object_store::{ObjectStore, ObjectStoreExt, PutPayload};
use url::Url;
use zeroize::Zeroizing;

/// Default maximum size collected by the convenience read methods.
pub const DEFAULT_MAX_BUFFERED_OBJECT_SIZE: u64 = 64 * 1024 * 1024;

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
/// Errors returned while configuring or accessing object storage.
pub enum ObjectStoreError {
    /// The supplied object-store settings are incomplete or inconsistent.
    #[error("{message}")]
    InvalidConfiguration {
        /// Description of the invalid setting.
        message: &'static str,
    },
    /// A local filesystem operation failed.
    #[error("{operation}: {source}")]
    Io {
        /// Operation that was attempted.
        operation: &'static str,
        #[source]
        /// Underlying filesystem error.
        source: std::io::Error,
    },
    /// The object-store backend returned an error.
    #[error("{operation}: {source}")]
    Store {
        /// Operation that was attempted.
        operation: &'static str,
        #[source]
        /// Underlying object-store error.
        source: object_store::Error,
    },
    /// The requested object does not exist.
    #[error("object storage read failed: object not found")]
    NotFound,
    /// An object key contains an unsupported path segment.
    #[error("{message}")]
    InvalidKey {
        /// Description of the invalid key.
        message: &'static str,
    },
    /// An object key could not be converted to a backend path.
    #[error("object storage key is invalid: {source}")]
    InvalidPath {
        #[source]
        /// Underlying path parser error.
        source: object_store::path::Error,
    },
    /// The object exceeds the caller's in-memory read limit.
    #[error("object storage read exceeds the {limit}-byte buffer limit ({actual} bytes)")]
    ObjectTooLarge {
        /// Configured maximum number of bytes.
        limit: u64,
        /// Object size reported by the backend.
        actual: u64,
    },
}

/// Result type used by object-store operations.
pub type ObjectStoreResult<T> = Result<T, ObjectStoreError>;

#[derive(Debug, PartialEq, Eq)]
/// Selects a local filesystem or S3-compatible object store.
pub enum ObjectStoreConfig {
    /// Stores objects below a local directory.
    Local(LocalObjectStoreConfig),
    /// Stores objects in an S3-compatible bucket.
    S3(S3ObjectStoreConfig),
}

#[derive(Debug, PartialEq, Eq)]
/// Configuration for a local filesystem object store.
pub struct LocalObjectStoreConfig {
    /// Root directory below which all objects are stored.
    pub root: PathBuf,
}

#[derive(PartialEq, Eq)]
/// Configuration for an S3-compatible object store.
pub struct S3ObjectStoreConfig {
    /// Bucket that receives objects.
    pub bucket: String,
    /// Optional custom endpoint for S3-compatible services.
    pub endpoint: Option<String>,
    /// Optional AWS region.
    pub region: Option<String>,
    /// Optional access key; must be paired with `secret_access_key`.
    pub access_key_id: Option<SecretString>,
    /// Optional secret key; must be paired with `access_key_id`.
    pub secret_access_key: Option<SecretString>,
    /// Allows plain HTTP endpoints, typically for local development.
    pub allow_http: bool,
    /// Uses virtual-hosted-style bucket addressing when enabled.
    pub virtual_hosted_style_request: bool,
}

impl fmt::Debug for S3ObjectStoreConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("S3ObjectStoreConfig")
            .field("bucket", &self.bucket)
            .field("endpoint", &self.endpoint)
            .field("region", &self.region)
            .field(
                "access_key_id",
                &self.access_key_id.as_ref().map(|_| "[REDACTED]"),
            )
            .field(
                "secret_access_key",
                &self.secret_access_key.as_ref().map(|_| "[REDACTED]"),
            )
            .field("allow_http", &self.allow_http)
            .field(
                "virtual_hosted_style_request",
                &self.virtual_hosted_style_request,
            )
            .finish()
    }
}

/// Heap-allocated secret that is redacted in diagnostics and cleared on drop.
#[derive(PartialEq, Eq)]
pub struct SecretString(Zeroizing<String>);

impl SecretString {
    /// Wraps a secret value.
    pub fn new(value: impl Into<String>) -> Self {
        Self(Zeroizing::new(value.into()))
    }

    /// Borrows the secret for an outbound provider request.
    pub fn expose_secret(&self) -> &str {
        self.0.as_str()
    }
}

impl fmt::Debug for SecretString {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("[REDACTED]")
    }
}

impl S3ObjectStoreConfig {
    /// Creates secure path-style settings for a MinIO-compatible endpoint.
    ///
    /// Plain HTTP remains disabled. Callers using an isolated local endpoint
    /// must opt in by setting [`Self::allow_http`] explicitly.
    pub fn minio(
        bucket: impl Into<String>,
        endpoint: impl Into<String>,
        access_key_id: impl Into<String>,
        secret_access_key: impl Into<String>,
    ) -> Self {
        let endpoint = endpoint.into();
        Self {
            bucket: bucket.into(),
            allow_http: false,
            endpoint: Some(endpoint),
            region: Some("us-east-1".to_string()),
            access_key_id: Some(SecretString::new(access_key_id)),
            secret_access_key: Some(SecretString::new(secret_access_key)),
            virtual_hosted_style_request: false,
        }
    }
}

#[derive(Clone, Debug)]
/// Cloneable client for local and S3-compatible object storage.
pub struct ObjectStoreClient {
    inner: Arc<dyn ObjectStore>,
    max_buffered_object_size: u64,
}

impl ObjectStoreClient {
    /// Creates a client from either supported configuration variant.
    pub fn from_config(config: ObjectStoreConfig) -> ObjectStoreResult<Self> {
        match config {
            ObjectStoreConfig::Local(config) => Self::local(config.root),
            ObjectStoreConfig::S3(config) => Self::s3(config),
        }
    }

    /// Creates a local filesystem store and ensures its root exists.
    pub fn local(root: impl Into<PathBuf>) -> ObjectStoreResult<Self> {
        let root = root.into();
        fs::create_dir_all(root.as_path()).map_err(|source| ObjectStoreError::Io {
            operation: "object storage root creation failed",
            source,
        })?;
        let store = LocalFileSystem::new_with_prefix(root.as_path()).map_err(|source| {
            ObjectStoreError::Store {
                operation: "local object store initialization failed",
                source,
            }
        })?;

        Ok(Self {
            inner: Arc::new(store),
            max_buffered_object_size: DEFAULT_MAX_BUFFERED_OBJECT_SIZE,
        })
    }

    /// Creates an S3-compatible store from validated settings.
    pub fn s3(config: S3ObjectStoreConfig) -> ObjectStoreResult<Self> {
        let bucket =
            non_empty(config.bucket.as_str()).ok_or(ObjectStoreError::InvalidConfiguration {
                message: "s3 object store bucket must not be empty",
            })?;

        let endpoint = non_empty_option(config.endpoint.as_deref());
        if let Some(endpoint) = endpoint.as_deref() {
            validate_endpoint(endpoint, config.allow_http)?;
        } else if config.allow_http {
            return Err(ObjectStoreError::InvalidConfiguration {
                message: "plain HTTP requires an explicit S3 endpoint",
            });
        }

        let mut builder = AmazonS3Builder::new()
            .with_bucket_name(bucket)
            .with_virtual_hosted_style_request(config.virtual_hosted_style_request)
            .with_allow_http(config.allow_http);

        if let Some(region) = non_empty_option(config.region.as_deref()) {
            builder = builder.with_region(region);
        }

        if let Some(endpoint) = endpoint {
            builder = builder.with_endpoint(endpoint);
        }

        match (
            non_empty_option(
                config
                    .access_key_id
                    .as_ref()
                    .map(SecretString::expose_secret),
            ),
            non_empty_option(
                config
                    .secret_access_key
                    .as_ref()
                    .map(SecretString::expose_secret),
            ),
        ) {
            (Some(access_key_id), Some(secret_access_key)) => {
                builder = builder
                    .with_access_key_id(access_key_id)
                    .with_secret_access_key(secret_access_key);
            }
            (None, None) => {}
            _ => {
                return Err(ObjectStoreError::InvalidConfiguration {
                    message: "s3 object store credentials require both access key id and secret access key",
                });
            }
        }

        let store = builder.build().map_err(|source| ObjectStoreError::Store {
            operation: "s3 object store build failed",
            source,
        })?;

        Ok(Self {
            inner: Arc::new(store),
            max_buffered_object_size: DEFAULT_MAX_BUFFERED_OBJECT_SIZE,
        })
    }

    /// Overrides the maximum size collected by [`Self::read_object`] and
    /// [`Self::read_object_optional`].
    #[must_use]
    pub fn with_max_buffered_object_size(mut self, limit: u64) -> Self {
        self.max_buffered_object_size = limit;
        self
    }

    /// Validates and converts an object key to a backend path.
    pub fn object_path(&self, key: &str) -> ObjectStoreResult<ObjectPath> {
        object_path(key)
    }

    /// Writes or replaces an object.
    pub async fn write_object(&self, key: &str, payload: &[u8]) -> ObjectStoreResult<()> {
        self.write_bytes(key, Bytes::copy_from_slice(payload)).await
    }

    /// Writes or replaces an object without copying an existing byte buffer.
    pub async fn write_bytes(&self, key: &str, payload: Bytes) -> ObjectStoreResult<()> {
        let path = self.object_path(key)?;
        self.inner
            .put(&path, PutPayload::from(payload))
            .await
            .map_err(|source| ObjectStoreError::Store {
                operation: "object storage write failed",
                source,
            })?;
        Ok(())
    }

    /// Reads an object or returns [`ObjectStoreError::NotFound`].
    pub async fn read_object(&self, key: &str) -> ObjectStoreResult<Vec<u8>> {
        self.read_object_optional(key)
            .await?
            .ok_or(ObjectStoreError::NotFound)
    }

    /// Reads an object, returning `None` when it does not exist.
    pub async fn read_object_optional(&self, key: &str) -> ObjectStoreResult<Option<Vec<u8>>> {
        self.read_object_optional_with_limit(key, self.max_buffered_object_size)
            .await
    }

    /// Reads an object into memory with a caller-selected size limit.
    pub async fn read_object_with_limit(
        &self,
        key: &str,
        limit: u64,
    ) -> ObjectStoreResult<Vec<u8>> {
        self.read_object_optional_with_limit(key, limit)
            .await?
            .ok_or(ObjectStoreError::NotFound)
    }

    /// Reads an optional object into memory with a caller-selected size limit.
    pub async fn read_object_optional_with_limit(
        &self,
        key: &str,
        limit: u64,
    ) -> ObjectStoreResult<Option<Vec<u8>>> {
        let Some(get_result) = self.get_object_optional(key, limit).await? else {
            return Ok(None);
        };
        let bytes = get_result
            .bytes()
            .await
            .map_err(|source| ObjectStoreError::Store {
                operation: "object storage byte read failed",
                source,
            })?;
        Ok(Some(bytes.to_vec()))
    }

    /// Returns the backend read result without collecting its payload.
    ///
    /// Consumers can stream `payload` directly; the backend-reported object
    /// size is checked before the result is returned.
    pub async fn get_object(
        &self,
        key: &str,
        limit: u64,
    ) -> ObjectStoreResult<object_store::GetResult> {
        self.get_object_optional(key, limit)
            .await?
            .ok_or(ObjectStoreError::NotFound)
    }

    /// Returns an optional backend read result without collecting its payload.
    pub async fn get_object_optional(
        &self,
        key: &str,
        limit: u64,
    ) -> ObjectStoreResult<Option<object_store::GetResult>> {
        let path = self.object_path(key)?;
        let get_result = match self.inner.get(&path).await {
            Ok(result) => result,
            Err(object_store::Error::NotFound { .. }) => return Ok(None),
            Err(source) => {
                return Err(ObjectStoreError::Store {
                    operation: "object storage read failed",
                    source,
                });
            }
        };
        if get_result.meta.size > limit {
            return Err(ObjectStoreError::ObjectTooLarge {
                limit,
                actual: get_result.meta.size,
            });
        }
        Ok(Some(get_result))
    }

    /// Deletes an object; missing objects are treated as already deleted.
    pub async fn delete_object(&self, key: &str) -> ObjectStoreResult<()> {
        let path = self.object_path(key)?;
        match self.inner.delete(&path).await {
            Ok(()) => Ok(()),
            Err(object_store::Error::NotFound { .. }) => Ok(()),
            Err(source) => Err(ObjectStoreError::Store {
                operation: "object storage delete failed",
                source,
            }),
        }
    }
}

fn object_path(key: &str) -> ObjectStoreResult<ObjectPath> {
    let mut segments = Vec::new();
    for segment in key.split('/') {
        let trimmed = segment.trim();
        if trimmed != segment
            || segment.is_empty()
            || segment == "."
            || segment == ".."
            || segment.contains('\\')
            || segment.contains(':')
        {
            return Err(ObjectStoreError::InvalidKey {
                message: "object storage key contains an invalid segment",
            });
        }
        segments.push(segment);
    }
    if segments.is_empty() {
        return Err(ObjectStoreError::InvalidKey {
            message: "object storage key must not be empty",
        });
    }

    ObjectPath::parse(segments.join("/")).map_err(|source| ObjectStoreError::InvalidPath { source })
}

fn non_empty(value: &str) -> Option<String> {
    let trimmed = value.trim();
    (!trimmed.is_empty()).then(|| trimmed.to_string())
}

fn non_empty_option(value: Option<&str>) -> Option<String> {
    value.and_then(non_empty)
}

fn validate_endpoint(endpoint: &str, allow_http: bool) -> ObjectStoreResult<()> {
    let endpoint = Url::parse(endpoint).map_err(|_| ObjectStoreError::InvalidConfiguration {
        message: "s3 object store endpoint must be an absolute URL",
    })?;
    if !endpoint.username().is_empty() || endpoint.password().is_some() {
        return Err(ObjectStoreError::InvalidConfiguration {
            message: "s3 object store endpoint must not contain credentials",
        });
    }
    match endpoint.scheme() {
        "https" => Ok(()),
        "http" if allow_http => Ok(()),
        "http" => Err(ObjectStoreError::InvalidConfiguration {
            message: "plain HTTP S3 endpoints require an explicit allow_http opt-in",
        }),
        _ => Err(ObjectStoreError::InvalidConfiguration {
            message: "s3 object store endpoint must use HTTP or HTTPS",
        }),
    }
}

#[cfg(test)]
mod tests {
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::*;

    fn temp_store() -> ObjectStoreClient {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        ObjectStoreClient::local(std::env::temp_dir().join(format!("s3-local-store-{unique}")))
            .expect("local object store")
    }

    #[test]
    fn object_store_rejects_unsafe_keys() {
        let store = temp_store();

        assert!(store.object_path("").is_err());
        assert!(store.object_path("../asset").is_err());
        assert!(store.object_path("media/../asset").is_err());
        assert!(store.object_path("media\\asset").is_err());
        assert!(store.object_path("media/c:asset").is_err());
        assert!(store.object_path("media/ asset").is_err());
    }

    #[tokio::test]
    async fn local_object_store_writes_reads_and_deletes_objects() {
        let store = temp_store();
        let key = "media/account/asset/original";

        store
            .write_object(key, b"payload")
            .await
            .expect("write object");

        assert_eq!(
            store.read_object(key).await.expect("read object"),
            b"payload"
        );
        assert_eq!(
            store
                .read_object_optional(key)
                .await
                .expect("optional read object"),
            Some(b"payload".to_vec())
        );

        store.delete_object(key).await.expect("delete object");

        assert!(store.read_object(key).await.is_err());
        assert_eq!(
            store
                .read_object_optional(key)
                .await
                .expect("missing object should be optional"),
            None
        );
    }

    #[test]
    fn s3_config_requires_credentials_as_a_pair() {
        let config = S3ObjectStoreConfig {
            bucket: "library".to_string(),
            endpoint: Some("http://127.0.0.1:9000".to_string()),
            region: Some("us-east-1".to_string()),
            access_key_id: Some(SecretString::new("minio")),
            secret_access_key: None,
            allow_http: true,
            virtual_hosted_style_request: false,
        };

        let error = ObjectStoreClient::s3(config).expect_err("missing secret must fail");

        assert!(
            error
                .to_string()
                .contains("both access key id and secret access key")
        );
    }

    #[test]
    fn minio_config_uses_path_style_http_endpoint() {
        let config =
            S3ObjectStoreConfig::minio("library", "http://127.0.0.1:9000", "minio", "minio-secret");

        assert_eq!(config.bucket, "library");
        assert_eq!(config.endpoint.as_deref(), Some("http://127.0.0.1:9000"));
        assert_eq!(config.region.as_deref(), Some("us-east-1"));
        assert!(!config.allow_http);
        assert!(!config.virtual_hosted_style_request);
    }

    #[test]
    fn s3_debug_output_redacts_credentials() {
        let config = S3ObjectStoreConfig::minio(
            "library",
            "http://127.0.0.1:9000",
            "visible-access-key",
            "visible-secret-key",
        );

        let debug = format!("{config:?}");

        assert!(!debug.contains("visible-access-key"));
        assert!(!debug.contains("visible-secret-key"));
        assert_eq!(debug.matches("[REDACTED]").count(), 2);
    }

    #[tokio::test]
    async fn buffered_reads_enforce_the_configured_limit() {
        let store = temp_store();
        store.write_object("media/large", b"12345").await.unwrap();
        assert!(matches!(
            store.read_object_with_limit("media/large", 4).await,
            Err(ObjectStoreError::ObjectTooLarge {
                limit: 4,
                actual: 5
            })
        ));
    }
}