diff --git a/Cargo.lock b/Cargo.lock index 77228bd..87427b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6139,6 +6139,7 @@ dependencies = [ "parking_lot", "sequins-arrow-schema", "sequins-companion-index", + "sequins-object-store", "sequins-series-index", "sequins-types", "sequins-vortex-indexed-layout", @@ -6149,7 +6150,6 @@ dependencies = [ "tokio", "tokio-stream", "tracing", - "url", "uuid", "vortex", "vortex-datafusion", @@ -6330,6 +6330,19 @@ dependencies = [ "tracing", ] +[[package]] +name = "sequins-object-store" +version = "0.4.0" +dependencies = [ + "bytes", + "object_store", + "serde", + "tempfile", + "thiserror 1.0.69", + "tokio", + "url", +] + [[package]] name = "sequins-otlp" version = "0.4.0" diff --git a/Cargo.toml b/Cargo.toml index cbce53a..f0a1320 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ members = [ "crates/sequins-live-query", "crates/sequins-batch-chain", "crates/sequins-hot-tier", + "crates/sequins-object-store", "crates/sequins-cold-tier", "crates/sequins-storage", "crates/sequins-datafusion-backend", @@ -53,6 +54,7 @@ sequins-companion-index = { path = "crates/sequins-companion-index" } sequins-vortex-indexed-layout = { path = "crates/sequins-vortex-indexed-layout" } sequins-attribute-codec = { path = "crates/sequins-attribute-codec" } sequins-series-index = { path = "crates/sequins-series-index" } +sequins-object-store = { path = "crates/sequins-object-store" } sequins-types = { path = "crates/sequins-types" } sequins-otlp = { path = "crates/sequins-otlp" } sequins-query = { path = "crates/sequins-query" } diff --git a/crates/sequins-cold-tier/Cargo.toml b/crates/sequins-cold-tier/Cargo.toml index 154dcfa..0fe46a3 100644 --- a/crates/sequins-cold-tier/Cargo.toml +++ b/crates/sequins-cold-tier/Cargo.toml @@ -13,6 +13,7 @@ sequins-arrow-schema = { workspace = true } sequins-types = { workspace = true } sequins-companion-index = { workspace = true } sequins-series-index = { workspace = true } +sequins-object-store = { workspace = true } sequins-vortex-indexed-layout = { workspace = true } # Arrow / DataFusion @@ -41,7 +42,6 @@ serde_json = { workspace = true } # Utilities chrono = { workspace = true } uuid = { workspace = true } -url = { workspace = true } hex = { workspace = true } base64 = { workspace = true } bytes = { workspace = true } diff --git a/crates/sequins-cold-tier/src/cold_tier.rs b/crates/sequins-cold-tier/src/cold_tier.rs index b25e543..0cfa5a6 100644 --- a/crates/sequins-cold-tier/src/cold_tier.rs +++ b/crates/sequins-cold-tier/src/cold_tier.rs @@ -107,132 +107,15 @@ impl ColdTier { /// Create an object store from the cold-tier config. /// - /// Supports: - /// - Local filesystem: `file:///path` or `/path` - /// - AWS S3 (and S3-compatibles): `s3://bucket/path` - /// - Google Cloud Storage: `gs://bucket/path` - /// - Azure Blob Storage: `az://container/path` or `azure://container/path` - /// - /// Connection settings for cloud stores (region, endpoint, HTTP, addressing, - /// optional static credentials) come from [`ColdTierConfig::object_store`]. - /// Credentials default to the provider's standard chain — instance profile, - /// IRSA / workload identity — so a properly-configured pod needs no static - /// credentials in config. + /// Delegates to [`sequins_object_store::build`], which is shared with other + /// subsystems that need their own bucket or prefix. Connection settings come + /// from [`ColdTierConfig::object_store`]; credentials default to the + /// provider's standard chain. fn create_store(config: &ColdTierConfig) -> Result> { - use object_store::local::LocalFileSystem; - - let uri = config.uri.as_str(); - let os = &config.object_store; - - // Local filesystem - if uri.starts_with("file://") || uri.starts_with('/') { - let path = uri.strip_prefix("file://").unwrap_or(uri); - - // Create the directory if it doesn't exist - std::fs::create_dir_all(path).map_err(|e| { - Error::Storage(format!("Failed to create storage directory: {}", e)) - })?; - - // Use LocalFileSystem without prefix - we'll use full paths in queries - let store = LocalFileSystem::new(); - return Ok(Arc::new(store)); - } - - // AWS S3 - if uri.starts_with("s3://") { - use object_store::aws::AmazonS3Builder; - - let url = url::Url::parse(uri) - .map_err(|e| Error::Config(format!("Invalid S3 URI '{}': {}", uri, e)))?; - - let bucket = url - .host_str() - .ok_or_else(|| Error::Config(format!("S3 URI missing bucket name: {}", uri)))?; - - // Base on `from_env` so the default AWS credential chain (instance - // profile, IRSA / web-identity, the credentials injected by the - // platform) is picked up with no configuration. Connection settings - // come from the cold-tier config, not the environment. - let mut builder = AmazonS3Builder::from_env().with_bucket_name(bucket); - if let Some(region) = &os.region { - builder = builder.with_region(region); - } - if let Some(endpoint) = &os.endpoint { - builder = builder.with_endpoint(endpoint); - } - if os.allow_http { - builder = builder.with_allow_http(true); - } - if let Some(vhost) = os.virtual_hosted_style { - builder = builder.with_virtual_hosted_style_request(vhost); - } - if let (Some(key), Some(secret)) = (&os.access_key_id, &os.secret_access_key) { - builder = builder - .with_access_key_id(key) - .with_secret_access_key(secret); - } - - let store = builder - .build() - .map_err(|e| Error::Config(format!("Failed to create S3 store: {}", e)))?; - - return Ok(Arc::new(store)); - } - - // Google Cloud Storage - if uri.starts_with("gs://") { - use object_store::gcp::GoogleCloudStorageBuilder; - - let url = url::Url::parse(uri) - .map_err(|e| Error::Config(format!("Invalid GCS URI '{}': {}", uri, e)))?; - - let bucket = url - .host_str() - .ok_or_else(|| Error::Config(format!("GCS URI missing bucket name: {}", uri)))?; - - // `from_env` picks up GOOGLE_APPLICATION_CREDENTIALS and the default - // workload-identity credential chain; the bucket comes from the URI. - let store = GoogleCloudStorageBuilder::from_env() - .with_bucket_name(bucket) - .build() - .map_err(|e| Error::Config(format!("Failed to create GCS store: {}", e)))?; - - return Ok(Arc::new(store)); - } - - // Azure Blob Storage - if uri.starts_with("az://") || uri.starts_with("azure://") { - use object_store::azure::MicrosoftAzureBuilder; - - let stripped_uri = uri - .strip_prefix("az://") - .or_else(|| uri.strip_prefix("azure://")) - .unwrap(); - - let url = url::Url::parse(&format!("https://{}", stripped_uri)) - .map_err(|e| Error::Config(format!("Invalid Azure URI '{}': {}", uri, e)))?; - - let container = url.host_str().ok_or_else(|| { - Error::Config(format!("Azure URI missing container name: {}", uri)) - })?; - - // `from_env` picks up AZURE_STORAGE_* and the default credential chain - // (managed / workload identity); the container comes from the URI. - let mut builder = MicrosoftAzureBuilder::from_env().with_container_name(container); - if os.allow_http { - builder = builder.with_allow_http(true); - } - let store = builder - .build() - .map_err(|e| Error::Config(format!("Failed to create Azure store: {}", e)))?; - - return Ok(Arc::new(store)); - } - - Err(Error::Config(format!( - "Unsupported object store URI: {}. Supported: file://, s3://, gs://, az://", - uri - ))) + Ok(sequins_object_store::build( + &config.uri, + &config.object_store, + )?) } /// Dispatch a hot-tier flush to the appropriate per-signal write path. diff --git a/crates/sequins-cold-tier/src/config.rs b/crates/sequins-cold-tier/src/config.rs index 9ffab29..6e3257c 100644 --- a/crates/sequins-cold-tier/src/config.rs +++ b/crates/sequins-cold-tier/src/config.rs @@ -72,34 +72,12 @@ impl Default for ColdTierConfig { } } -/// Connection options for cloud object stores. All fields are optional; unset -/// values fall back to the object-store provider's defaults (including the -/// standard credential chain — instance profile, IRSA / workload identity). -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub struct ObjectStoreConfig { - /// Region (e.g. `us-east-1`). Unset uses the provider default. - pub region: Option, - - /// Custom endpoint URL for S3-compatible stores (MinIO, Ceph RGW, a gateway). - pub endpoint: Option, - - /// Allow plain-HTTP endpoints. Required for a local MinIO served over http - /// (object stores reject non-https endpoints otherwise). - #[serde(default)] - pub allow_http: bool, - - /// Force path-style addressing (`endpoint/bucket`) instead of virtual-hosted - /// (`bucket.endpoint`). Most S3-compatibles (MinIO) need path-style. - pub virtual_hosted_style: Option, - - /// Static access key id. Prefer the credential chain (IRSA / instance - /// profile) in production; set this only for local/dev (e.g. MinIO). - pub access_key_id: Option, - - /// Static secret access key (paired with `access_key_id`). - pub secret_access_key: Option, -} +/// Connection options for cloud object stores. +/// +/// Defined in [`sequins_object_store`] and re-exported here so it can be shared +/// with other subsystems that need their own bucket or prefix without depending +/// on the cold tier. +pub use sequins_object_store::ObjectStoreConfig; /// Companion index configuration #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/sequins-cold-tier/src/error.rs b/crates/sequins-cold-tier/src/error.rs index 1fc4c03..a759454 100644 --- a/crates/sequins-cold-tier/src/error.rs +++ b/crates/sequins-cold-tier/src/error.rs @@ -44,6 +44,18 @@ pub enum Error { SeriesIndex(#[from] sequins_series_index::error::Error), } +/// Flatten store-construction failures onto the existing variants so the +/// messages callers already match on are unchanged by the move to +/// `sequins-object-store`. +impl From for Error { + fn from(err: sequins_object_store::Error) -> Self { + match err { + sequins_object_store::Error::Config(msg) => Error::Config(msg), + io @ sequins_object_store::Error::Io(_) => Error::Storage(io.to_string()), + } + } +} + impl Error { /// True if this batch can never be written to cold (a permanent schema /// incompatibility), so it should be dropped rather than retried — otherwise it diff --git a/crates/sequins-object-store/Cargo.toml b/crates/sequins-object-store/Cargo.toml new file mode 100644 index 0000000..d1a25ef --- /dev/null +++ b/crates/sequins-object-store/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "sequins-object-store" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "Shared object-store construction for Sequins storage tiers" + +[dependencies] +object_store = { workspace = true } + +serde = { workspace = true, features = ["derive"] } +url = { workspace = true } + +thiserror = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt"] } +bytes = { workspace = true } diff --git a/crates/sequins-object-store/src/lib.rs b/crates/sequins-object-store/src/lib.rs new file mode 100644 index 0000000..fa5bfef --- /dev/null +++ b/crates/sequins-object-store/src/lib.rs @@ -0,0 +1,436 @@ +//! Shared object-store construction for Sequins. +//! +//! One place that turns a storage URI plus [`ObjectStoreConfig`] into an +//! [`ObjectStore`]. The cold tier uses it for telemetry partitions; other +//! subsystems that need their own bucket or prefix use the same entry point so +//! credential handling, endpoint overrides, and S3-compatible quirks stay +//! consistent rather than being reimplemented per subsystem. +//! +//! Deliberately dependency-light — `object_store` and nothing from the Arrow, +//! DataFusion, or Vortex stack — so a caller that only needs a store does not +//! pull in the columnar engine. +//! +//! # Conditional writes +//! +//! Two conditional modes matter, and they are not equally portable: +//! +//! - **`PutMode::Create`** (atomic create-if-absent) works on *every* backend, +//! including `LocalFileSystem`, which implements it with `link(2)`. +//! - **`PutMode::Update`** (compare-and-swap on an existing object) works on +//! S3, GCS, and Azure but **not** `LocalFileSystem`, which returns +//! `Error::NotImplemented`. +//! +//! **`Update` is the right primitive for a mutable pointer, and deployments +//! that have it should use it.** A single conditional write advances the +//! pointer, and one read returns the current value — no probing, no scan. Build +//! the production path on that. +//! +//! `LocalFileSystem` cannot, so a caller that needs a mutable pointer supplies +//! a second, cheaper path for `file://` — serialising its own read-modify-write +//! rather than relying on the store. Local deployments are single-node and +//! low-traffic, so the weaker guarantee is an acceptable trade there and only +//! there. `file://` must keep working; it does not have to be fast or +//! multi-writer safe. +//! +//! Use [`conditional_write_support`] to choose between the two. Note the +//! distinction is *only* about mutable pointers: immutable content-addressed +//! objects use `Create` everywhere and need no fallback. + +use std::sync::Arc; + +use object_store::ObjectStore; +use serde::{Deserialize, Serialize}; + +/// Errors raised while constructing a store. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The URI was malformed, named an unsupported scheme, or the provider + /// rejected the resulting configuration. + #[error("{0}")] + Config(String), + + /// Creating the backing directory for a `file://` store failed. + #[error("Failed to create storage directory: {0}")] + Io(#[from] std::io::Error), +} + +pub type Result = std::result::Result; + +/// Connection options for cloud object stores. All fields are optional; unset +/// values fall back to the object-store provider's defaults (including the +/// standard credential chain — instance profile, IRSA / workload identity). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub struct ObjectStoreConfig { + /// Region (e.g. `us-east-1`). Unset uses the provider default. + pub region: Option, + + /// Custom endpoint URL for S3-compatible stores (MinIO, Ceph RGW, a gateway). + pub endpoint: Option, + + /// Allow plain-HTTP endpoints. Required for a local MinIO served over http + /// (object stores reject non-https endpoints otherwise). + #[serde(default)] + pub allow_http: bool, + + /// Force path-style addressing (`endpoint/bucket`) instead of virtual-hosted + /// (`bucket.endpoint`). Most S3-compatibles (MinIO) need path-style. + pub virtual_hosted_style: Option, + + /// Static access key id. Prefer the credential chain (IRSA / instance + /// profile) in production; set this only for local/dev (e.g. MinIO). + pub access_key_id: Option, + + /// Static secret access key (paired with `access_key_id`). + pub secret_access_key: Option, +} + +/// Build an object store for `uri`. +/// +/// Supports: +/// - Local filesystem: `file:///path` or `/path` +/// - AWS S3 (and S3-compatibles): `s3://bucket/path` +/// - Google Cloud Storage: `gs://bucket/path` +/// - Azure Blob Storage: `az://container/path` or `azure://container/path` +/// +/// Cloud credentials default to the provider's standard chain — instance +/// profile, IRSA / workload identity — so a properly-configured pod needs no +/// static credentials in config. `config` supplies connection settings only. +/// +/// For a `file://` URI the target directory is created if it does not exist. +pub fn build(uri: &str, config: &ObjectStoreConfig) -> Result> { + if uri.starts_with("file://") || uri.starts_with('/') { + return build_local(uri); + } + if uri.starts_with("s3://") { + return build_s3(uri, config); + } + if uri.starts_with("gs://") { + return build_gcs(uri); + } + if uri.starts_with("az://") || uri.starts_with("azure://") { + return build_azure(uri, config); + } + + Err(Error::Config(format!( + "Unsupported object store URI: {}. Supported: file://, s3://, gs://, az://", + uri + ))) +} + +/// Which conditional write modes a store built for `uri` supports. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConditionalWriteSupport { + /// Atomic create-if-absent (`PutMode::Create`): the write succeeds only if + /// no object exists at the key, and concurrent attempts produce exactly one + /// winner with the rest receiving `Error::AlreadyExists`. + /// + /// True for every supported backend. `LocalFileSystem` implements it with + /// `link(2)`, which is atomic on POSIX. Immutable content-addressed writes + /// can therefore use `Create` everywhere without a fallback. + pub create: bool, + + /// Compare-and-swap against an existing object (`PutMode::Update`). + /// + /// True for S3 (`If-Match` on the ETag), GCS + /// (`x-goog-if-generation-match`), and Azure. **False for + /// `LocalFileSystem`**, which returns `Error::NotImplemented`. + /// + /// When true, preserve **both** `e_tag` and `version` from the + /// [`object_store::PutResult`] when building the next `UpdateVersion`: S3 + /// matches on the ETag while GCS requires `version` and fails with + /// `MissingVersion` without it. + pub update: bool, +} + +/// Report the conditional write modes available for `uri`. +/// +/// Use this to *select an implementation*, never to reject a store. +/// +/// A caller maintaining a mutable pointer should take the `update` path when it +/// is available — that is the correct mechanism, and it is what production +/// deployments will run. When `update` is false the caller supplies its own +/// serialisation for `file://`, accepting weaker concurrency guarantees on a +/// backend where that does not matter. +pub fn conditional_write_support(uri: &str) -> ConditionalWriteSupport { + let is_local = uri.starts_with("file://") || uri.starts_with('/'); + ConditionalWriteSupport { + create: true, + update: !is_local, + } +} + +fn build_local(uri: &str) -> Result> { + use object_store::local::LocalFileSystem; + + let path = uri.strip_prefix("file://").unwrap_or(uri); + std::fs::create_dir_all(path)?; + + // No prefix — callers address objects with full paths. + Ok(Arc::new(LocalFileSystem::new())) +} + +fn build_s3(uri: &str, config: &ObjectStoreConfig) -> Result> { + use object_store::aws::AmazonS3Builder; + + let bucket = bucket_from(uri, "S3")?; + + // Base on `from_env` so the default AWS credential chain (instance profile, + // IRSA / web-identity, the credentials injected by the platform) is picked + // up with no configuration. Connection settings come from `config`, not the + // environment. + let mut builder = AmazonS3Builder::from_env().with_bucket_name(bucket); + if let Some(region) = &config.region { + builder = builder.with_region(region); + } + if let Some(endpoint) = &config.endpoint { + builder = builder.with_endpoint(endpoint); + } + if config.allow_http { + builder = builder.with_allow_http(true); + } + if let Some(vhost) = config.virtual_hosted_style { + builder = builder.with_virtual_hosted_style_request(vhost); + } + if let (Some(key), Some(secret)) = (&config.access_key_id, &config.secret_access_key) { + builder = builder + .with_access_key_id(key) + .with_secret_access_key(secret); + } + + let store = builder + .build() + .map_err(|e| Error::Config(format!("Failed to create S3 store: {}", e)))?; + + Ok(Arc::new(store)) +} + +fn build_gcs(uri: &str) -> Result> { + use object_store::gcp::GoogleCloudStorageBuilder; + + let bucket = bucket_from(uri, "GCS")?; + + // `from_env` picks up GOOGLE_APPLICATION_CREDENTIALS and the default + // workload-identity credential chain; the bucket comes from the URI. + let store = GoogleCloudStorageBuilder::from_env() + .with_bucket_name(bucket) + .build() + .map_err(|e| Error::Config(format!("Failed to create GCS store: {}", e)))?; + + Ok(Arc::new(store)) +} + +fn build_azure(uri: &str, config: &ObjectStoreConfig) -> Result> { + use object_store::azure::MicrosoftAzureBuilder; + + let stripped = uri + .strip_prefix("az://") + .or_else(|| uri.strip_prefix("azure://")) + .expect("caller checked the scheme"); + + let url = url::Url::parse(&format!("https://{}", stripped)) + .map_err(|e| Error::Config(format!("Invalid Azure URI '{}': {}", uri, e)))?; + let container = url + .host_str() + .ok_or_else(|| Error::Config(format!("Azure URI missing container name: {}", uri)))?; + + // `from_env` picks up AZURE_STORAGE_* and the default credential chain + // (managed / workload identity); the container comes from the URI. + let mut builder = MicrosoftAzureBuilder::from_env().with_container_name(container); + if config.allow_http { + builder = builder.with_allow_http(true); + } + let store = builder + .build() + .map_err(|e| Error::Config(format!("Failed to create Azure store: {}", e)))?; + + Ok(Arc::new(store)) +} + +/// Extract the bucket (URI host) from a `scheme://bucket/path` URI. +fn bucket_from<'a>(uri: &'a str, label: &str) -> Result<&'a str> { + let rest = uri + .split_once("://") + .map(|(_, rest)| rest) + .ok_or_else(|| Error::Config(format!("Invalid {} URI '{}'", label, uri)))?; + + let bucket = rest.split('/').next().unwrap_or(""); + if bucket.is_empty() { + return Err(Error::Config(format!( + "{} URI missing bucket name: {}", + label, uri + ))); + } + Ok(bucket) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unsupported_scheme_is_rejected() { + let err = build("ftp://host/path", &ObjectStoreConfig::default()).unwrap_err(); + assert!(matches!(err, Error::Config(_)), "got {err:?}"); + assert!(err.to_string().contains("Unsupported object store URI")); + } + + #[test] + fn bucket_is_parsed_from_uri() { + assert_eq!( + bucket_from("s3://my-bucket/a/b", "S3").unwrap(), + "my-bucket" + ); + assert_eq!(bucket_from("s3://my-bucket", "S3").unwrap(), "my-bucket"); + assert!(bucket_from("s3:///a/b", "S3").is_err()); + assert!(bucket_from("my-bucket/a", "S3").is_err()); + } + + #[test] + fn local_uri_creates_the_directory() { + let tmp = tempfile::tempdir().unwrap(); + let target = tmp.path().join("nested/created"); + let uri = format!("file://{}", target.display()); + + build(&uri, &ObjectStoreConfig::default()).unwrap(); + + assert!( + target.is_dir(), + "build() should create the target directory" + ); + } + + #[test] + fn every_backend_supports_create_only_local_lacks_update() { + for uri in ["s3://b/x", "gs://b/x", "az://c/x", "azure://c/x"] { + let s = conditional_write_support(uri); + assert!(s.create, "{uri} should support Create"); + assert!(s.update, "{uri} should support Update"); + } + for uri in ["file:///tmp/x", "/tmp/x"] { + let s = conditional_write_support(uri); + assert!( + s.create, + "{uri} must support Create — local CAS depends on it" + ); + assert!( + !s.update, + "LocalFileSystem returns NotImplemented for Update" + ); + } + } + + /// Pins the local backend's Update gap. If `object_store` ever implements + /// it, this fails and [`conditional_write_support`] should be updated — + /// but nothing should start *depending* on Update as a result. + #[tokio::test] + async fn local_update_is_unimplemented() { + use object_store::{path::Path, Error as OsError, PutMode, PutOptions, UpdateVersion}; + + let tmp = tempfile::tempdir().unwrap(); + let uri = format!("file://{}", tmp.path().display()); + let store = build(&uri, &ObjectStoreConfig::default()).unwrap(); + let path = Path::from(format!("{}/pointer", tmp.path().display())); + + let put = store + .put_opts( + &path, + bytes::Bytes::from_static(b"v1").into(), + PutOptions { + mode: PutMode::Create, + ..Default::default() + }, + ) + .await + .unwrap(); + + let update = store + .put_opts( + &path, + bytes::Bytes::from_static(b"v2").into(), + PutOptions { + mode: PutMode::Update(UpdateVersion { + e_tag: put.e_tag.clone(), + version: put.version.clone(), + }), + ..Default::default() + }, + ) + .await; + assert!( + matches!(update, Err(OsError::NotImplemented { .. })), + "expected local Update to be unimplemented, got {update:?}" + ); + } + + /// Immutable content-addressed writes rely on `Create` being atomic on + /// every backend: when writers race to publish the same key, one wins and + /// the rest are told so rather than silently clobbering it. Verified on the + /// local backend because that is the one whose atomicity is easiest to + /// doubt — it goes through `link(2)` rather than a server-side condition. + #[tokio::test(flavor = "multi_thread", worker_threads = 8)] + async fn concurrent_create_has_exactly_one_winner_locally() { + use object_store::{path::Path, Error as OsError, ObjectStoreExt, PutMode, PutOptions}; + + let tmp = tempfile::tempdir().unwrap(); + let uri = format!("file://{}", tmp.path().display()); + let store = build(&uri, &ObjectStoreConfig::default()).unwrap(); + let path = Path::from(format!("{}/generations/000042", tmp.path().display())); + + const RACERS: usize = 32; + let barrier = Arc::new(tokio::sync::Barrier::new(RACERS)); + + let mut tasks = Vec::with_capacity(RACERS); + for racer in 0..RACERS { + let store = Arc::clone(&store); + let path = path.clone(); + let barrier = Arc::clone(&barrier); + tasks.push(tokio::spawn(async move { + // Line every writer up so the claims genuinely overlap. + barrier.wait().await; + store + .put_opts( + &path, + bytes::Bytes::from(format!("claimed-by-{racer}")).into(), + PutOptions { + mode: PutMode::Create, + ..Default::default() + }, + ) + .await + .map(|_| racer) + })); + } + + let mut winners = Vec::new(); + let mut losers = 0usize; + for task in tasks { + match task.await.expect("task should not panic") { + Ok(racer) => winners.push(racer), + Err(OsError::AlreadyExists { .. }) => losers += 1, + Err(other) => panic!("losers must see AlreadyExists, got {other:?}"), + } + } + + assert_eq!( + winners.len(), + 1, + "exactly one writer should win, got {winners:?}" + ); + assert_eq!( + losers, + RACERS - 1, + "every other writer should see AlreadyExists" + ); + + // The stored value must belong to the writer that was told it won — + // a loser silently overwriting the winner is the failure that would + // make generation pointers unsafe. + let stored = store.get(&path).await.unwrap().bytes().await.unwrap(); + assert_eq!( + stored, + bytes::Bytes::from(format!("claimed-by-{}", winners[0])), + "the winner's bytes must be the ones that persisted" + ); + } +} diff --git a/crates/sequins-object-store/tests/conditional_put_s3.rs b/crates/sequins-object-store/tests/conditional_put_s3.rs new file mode 100644 index 0000000..993909f --- /dev/null +++ b/crates/sequins-object-store/tests/conditional_put_s3.rs @@ -0,0 +1,228 @@ +//! Conditional-write smoke test against a real S3-compatible endpoint. +//! +//! Skipped unless `SEQUINS_TEST_S3_URI` is set, so an ordinary `cargo test` on a +//! machine with no object store still passes. Point it at AWS S3 or a local +//! MinIO: +//! +//! ```text +//! docker run -d --rm -p 19000:9000 \ +//! -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin \ +//! minio/minio:latest server /data +//! docker run --rm --entrypoint sh minio/mc:latest -c \ +//! "mc alias set t http://host.docker.internal:19000 minioadmin minioadmin \ +//! && mc mb --ignore-existing t/sequins-test" +//! +//! SEQUINS_TEST_S3_URI=s3://sequins-test \ +//! SEQUINS_TEST_S3_ENDPOINT=http://127.0.0.1:19000 \ +//! SEQUINS_TEST_S3_ACCESS_KEY_ID=minioadmin \ +//! SEQUINS_TEST_S3_SECRET_ACCESS_KEY=minioadmin \ +//! cargo test -p sequins-object-store --test conditional_put_s3 +//! ``` +//! +//! This is the compare-and-swap behaviour that a generation pointer depends on, +//! so it is worth exercising against a real endpoint rather than trusting that +//! `S3ConditionalPut::ETagMatch` is wired up. + +use object_store::{ + path::Path, Error as OsError, ObjectStoreExt, PutMode, PutOptions, UpdateVersion, +}; +use sequins_object_store::{build, ObjectStoreConfig}; + +/// Read the endpoint config from the environment, or `None` to skip. +fn config_from_env() -> Option<(String, ObjectStoreConfig)> { + let uri = std::env::var("SEQUINS_TEST_S3_URI").ok()?; + let config = ObjectStoreConfig { + region: std::env::var("SEQUINS_TEST_S3_REGION") + .ok() + .or_else(|| Some("us-east-1".to_string())), + endpoint: std::env::var("SEQUINS_TEST_S3_ENDPOINT").ok(), + // A local MinIO is served over plain HTTP and needs path-style addressing. + allow_http: true, + virtual_hosted_style: Some(false), + access_key_id: std::env::var("SEQUINS_TEST_S3_ACCESS_KEY_ID").ok(), + secret_access_key: std::env::var("SEQUINS_TEST_S3_SECRET_ACCESS_KEY").ok(), + }; + Some((uri, config)) +} + +/// A distinct key per run so repeat runs against a persistent bucket don't +/// collide on the `Create` assertion. +fn unique_key(label: &str) -> Path { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("system clock before epoch") + .as_nanos(); + Path::from(format!("conditional-put-test/{label}-{nanos}.json")) +} + +#[tokio::test] +async fn create_conflicts_and_update_enforces_the_etag() { + let Some((uri, config)) = config_from_env() else { + eprintln!("SEQUINS_TEST_S3_URI unset — skipping S3 conditional-put test"); + return; + }; + + let support = sequins_object_store::conditional_write_support(&uri); + assert!( + support.create && support.update, + "{uri} should support both modes" + ); + + let store = build(&uri, &config).expect("store should build"); + let path = unique_key("generation"); + + let create = || PutOptions { + mode: PutMode::Create, + ..Default::default() + }; + + // First Create wins and yields the version we must present to update. + let first = store + .put_opts(&path, bytes::Bytes::from_static(b"gen-1").into(), create()) + .await + .expect("first Create should succeed"); + + // A racing writer that assumes the object is absent must lose. + let conflict = store + .put_opts(&path, bytes::Bytes::from_static(b"gen-1'").into(), create()) + .await; + assert!( + matches!(conflict, Err(OsError::AlreadyExists { .. })), + "second Create should conflict, got {conflict:?}" + ); + + // A writer holding a stale version must lose rather than clobber. + let rejected = store + .put_opts( + &path, + bytes::Bytes::from_static(b"gen-2-from-stale").into(), + PutOptions { + mode: PutMode::Update(UpdateVersion { + e_tag: Some("\"0000000000000000000000000000dead\"".to_string()), + version: None, + }), + ..Default::default() + }, + ) + .await; + assert!( + matches!(rejected, Err(OsError::Precondition { .. })), + "Update with a stale ETag should be rejected, got {rejected:?}" + ); + + // The holder of the current version advances the generation. + // Carry both e_tag and version: S3 matches the ETag, GCS needs the version. + let second = store + .put_opts( + &path, + bytes::Bytes::from_static(b"gen-2").into(), + PutOptions { + mode: PutMode::Update(UpdateVersion { + e_tag: first.e_tag.clone(), + version: first.version.clone(), + }), + ..Default::default() + }, + ) + .await + .expect("Update with the current ETag should succeed"); + + let bytes = store.get(&path).await.unwrap().bytes().await.unwrap(); + assert_eq!(&bytes[..], b"gen-2", "the winning write should be visible"); + + // The superseded version must not be reusable — otherwise a lagging writer + // could resurrect an old generation. + let replayed = store + .put_opts( + &path, + bytes::Bytes::from_static(b"gen-3-replay").into(), + PutOptions { + mode: PutMode::Update(UpdateVersion { + e_tag: first.e_tag.clone(), + version: first.version.clone(), + }), + ..Default::default() + }, + ) + .await; + assert!( + matches!(replayed, Err(OsError::Precondition { .. })), + "replaying the superseded version should be rejected, got {replayed:?}" + ); + + assert_ne!( + first.e_tag, second.e_tag, + "each generation should get a distinct ETag" + ); + + store.delete(&path).await.ok(); +} + +/// The same one-winner property the local backend proves in the unit tests, +/// against a real S3-compatible endpoint. Immutable content-addressed writes +/// depend on it on every backend, so it is worth confirming the remote +/// implementation agrees with the local one. +#[tokio::test(flavor = "multi_thread", worker_threads = 8)] +async fn concurrent_create_has_exactly_one_winner() { + let Some((uri, config)) = config_from_env() else { + eprintln!("SEQUINS_TEST_S3_URI unset — skipping S3 create-race test"); + return; + }; + + let store = build(&uri, &config).expect("store should build"); + let path = unique_key("race"); + + const RACERS: usize = 16; + let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(RACERS)); + + let mut tasks = Vec::with_capacity(RACERS); + for racer in 0..RACERS { + let store = std::sync::Arc::clone(&store); + let path = path.clone(); + let barrier = std::sync::Arc::clone(&barrier); + tasks.push(tokio::spawn(async move { + barrier.wait().await; + store + .put_opts( + &path, + bytes::Bytes::from(format!("claimed-by-{racer}")).into(), + PutOptions { + mode: PutMode::Create, + ..Default::default() + }, + ) + .await + .map(|_| racer) + })); + } + + let mut winners = Vec::new(); + let mut losers = 0usize; + for task in tasks { + match task.await.expect("task should not panic") { + Ok(racer) => winners.push(racer), + Err(OsError::AlreadyExists { .. }) => losers += 1, + Err(other) => panic!("losers must see AlreadyExists, got {other:?}"), + } + } + + assert_eq!( + winners.len(), + 1, + "exactly one writer should win, got {winners:?}" + ); + assert_eq!( + losers, + RACERS - 1, + "every other writer should see AlreadyExists" + ); + + let stored = store.get(&path).await.unwrap().bytes().await.unwrap(); + assert_eq!( + stored, + bytes::Bytes::from(format!("claimed-by-{}", winners[0])), + "the winner's bytes must be the ones that persisted" + ); + + store.delete(&path).await.ok(); +}