CTTY commented on code in PR #3165: URL: https://github.com/apache/iceberg-rust/pull/3165#discussion_r4702332099
########## crates/storage/object_store/src/lib.rs: ########## @@ -0,0 +1,1517 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `object_store`-based storage implementation for Apache Iceberg. +//! +//! This crate provides [`ObjectStoreStorage`] and [`ObjectStoreStorageFactory`], +//! which implement the [`Storage`] and +//! [`StorageFactory`] traits from the `iceberg` crate +//! using the [`object_store`](https://docs.rs/object_store) crate as the backend. +//! +//! Currently only S3 storage is supported (via the `object_store-s3` feature flag, +//! enabled by default). + +#[cfg(feature = "object_store-s3")] +mod s3; + +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use bytes::{Bytes, BytesMut}; +use dashmap::DashMap; +use futures::stream::BoxStream; +use futures::{StreamExt, TryStreamExt}; +use iceberg::io::{ + FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, + StorageFactory, +}; +#[cfg(feature = "object_store-s3")] +use iceberg::io::{S3_DELETE_BATCH_SIZE, S3_MULTIPART_PART_SIZE_BYTES, S3Config}; +use iceberg::{Error, ErrorKind, Result}; +use object_store::path::Path as ObjectStorePath; +use object_store::{MultipartUpload, ObjectStore, ObjectStoreExt, PutPayload}; +#[cfg(feature = "object_store-s3")] +use s3::{S3RetrySettings, build_s3_store, parse_s3_url}; +use serde::{Deserialize, Serialize}; +use tokio::task::JoinSet; + +/// Convert an `object_store::Error` into an `iceberg::Error`, +/// dispatching known variants to their corresponding `ErrorKind`. +fn from_object_store_error(e: object_store::Error) -> Error { + let (kind, msg) = match &e { + object_store::Error::NotFound { path, .. } => { + (ErrorKind::Unexpected, format!("Object not found: {path}")) + } + object_store::Error::AlreadyExists { path, .. } => ( + ErrorKind::Unexpected, + format!("Object already exists: {path}"), + ), + object_store::Error::PermissionDenied { path, .. } => { + (ErrorKind::Unexpected, format!("Permission denied: {path}")) + } + object_store::Error::Unauthenticated { path, .. } => { + (ErrorKind::Unexpected, format!("Unauthenticated: {path}")) + } + object_store::Error::NotSupported { .. } => ( + ErrorKind::FeatureUnsupported, + "Operation not supported".to_string(), + ), + _ => ( + ErrorKind::Unexpected, + "Failure in doing io operation".to_string(), + ), + }; + Error::new(kind, msg).with_source(e) +} + +/// Default batch size for S3 bulk deletions (matches Iceberg Java specification). +pub(crate) const DEFAULT_DELETE_BATCH_SIZE: usize = 250; +/// Maximum batch size allowed by the AWS S3 DeleteObjects API specification. +pub(crate) const S3_MAX_DELETE_BATCH_SIZE: usize = 1000; +/// Default part size for S3 multipart uploads (32 MiB, matches Iceberg Java specification). +pub(crate) const DEFAULT_PART_SIZE_BYTES: usize = 32 * 1024 * 1024; +/// Minimum part size allowed by the AWS S3 MultipartUpload API specification (5 MiB). +pub(crate) const MIN_PART_SIZE_BYTES: usize = 5 * 1024 * 1024; + +fn parse_delete_batch_size(config: &StorageConfig) -> Result<usize> { + let Some(val) = config.get(S3_DELETE_BATCH_SIZE) else { + return Ok(DEFAULT_DELETE_BATCH_SIZE); + }; + let batch_size = val.parse::<usize>().map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_DELETE_BATCH_SIZE}: {val}: {e}"), + ) + })?; + if batch_size == 0 { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_DELETE_BATCH_SIZE}: batch size must be greater than 0"), + )); + } + Ok(batch_size.clamp(1, S3_MAX_DELETE_BATCH_SIZE)) +} + +fn default_delete_batch_size() -> usize { + DEFAULT_DELETE_BATCH_SIZE +} + +fn parse_part_size_bytes(config: &StorageConfig) -> Result<usize> { + let Some(val) = config.get(S3_MULTIPART_PART_SIZE_BYTES) else { + return Ok(DEFAULT_PART_SIZE_BYTES); + }; + let part_size = val.parse::<usize>().map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {val}: {e}"), + ) + })?; + if part_size < MIN_PART_SIZE_BYTES { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {part_size} bytes is below the S3 minimum part size of 5 MiB" + ), + )); + } + if part_size > i32::MAX as usize { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {part_size} bytes is above the maximum allowed by Java spec" + ), + )); + } + Ok(part_size) +} + +fn default_part_size_bytes() -> usize { + DEFAULT_PART_SIZE_BYTES +} + +/// Convert `object_store::ObjectMeta` into `iceberg::io::FileMetadata`. +fn to_file_metadata(meta: object_store::ObjectMeta) -> FileMetadata { + FileMetadata { size: meta.size } +} + +/// `object_store`-based storage factory. +/// +/// Use this factory with `FileIOBuilder::new(factory)` to create FileIO instances +/// backed by the `object_store` crate. +#[non_exhaustive] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum ObjectStoreStorageFactory { + /// S3 storage factory. + #[cfg(feature = "object_store-s3")] + S3, +} + +#[typetag::serde(name = "ObjectStoreStorageFactory")] +impl StorageFactory for ObjectStoreStorageFactory { + #[allow(unused_variables)] + fn build(&self, config: &StorageConfig) -> Result<Arc<dyn Storage>> { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorageFactory::S3 => { + let s3_config = S3Config::try_from(config)?; + s3::validate_s3_config(&s3_config)?; + let delete_batch_size = parse_delete_batch_size(config)?; + let part_size_bytes = parse_part_size_bytes(config)?; + let retry_settings = S3RetrySettings::parse(config)?; + Ok(Arc::new(ObjectStoreStorage::S3(S3Storage { + config: Arc::new(s3_config), + delete_batch_size, + part_size_bytes, + retry_settings, + store_cache: Arc::new(DashMap::new()), + }))) + } + } + } +} + +type StoreCache = Arc<DashMap<String, Arc<dyn ObjectStore>>>; + +/// `object_store` S3 storage state. +#[derive(Clone, Serialize, Deserialize)] +pub struct S3Storage { + config: Arc<S3Config>, + #[serde(default = "default_delete_batch_size")] + delete_batch_size: usize, + #[serde(default = "default_part_size_bytes")] + part_size_bytes: usize, + #[serde(default)] + retry_settings: S3RetrySettings, + #[serde(skip, default)] + store_cache: StoreCache, +} + +impl std::fmt::Debug for S3Storage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("S3Storage") + .field("endpoint", &self.config.endpoint) + .field("region", &self.config.region) + .field("access_key_id", &self.config.access_key_id) + .field( + "secret_access_key", + &self.config.secret_access_key.as_ref().map(|_| "[REDACTED]"), + ) + .field( + "session_token", + &self.config.session_token.as_ref().map(|_| "[REDACTED]"), + ) + .field( + "server_side_encryption_customer_key", + &self + .config + .server_side_encryption_customer_key + .as_ref() + .map(|_| "[REDACTED]"), + ) + .field("delete_batch_size", &self.delete_batch_size) + .field("part_size_bytes", &self.part_size_bytes) + .finish_non_exhaustive() + } +} + +/// `object_store`-based storage implementation. +/// +/// Stores are cached per bucket to avoid rebuilding the client on every operation. +#[non_exhaustive] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum ObjectStoreStorage { + /// S3 storage variant. + #[cfg(feature = "object_store-s3")] + S3(S3Storage), +} + +#[derive(Debug)] +struct StoreAndPath { + bucket: String, + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, +} + +/// Helper for batching deletions per bucket. +struct BucketBatch { + store: Arc<dyn ObjectStore>, + locations: Vec<ObjectStorePath>, +} + +impl ObjectStoreStorage { + fn delete_batch_size(&self) -> usize { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => s3.delete_batch_size.clamp(1, S3_MAX_DELETE_BATCH_SIZE), + } + } + + fn part_size_bytes(&self) -> usize { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => s3.part_size_bytes.max(MIN_PART_SIZE_BYTES), + } + } + + /// Get or create a cached store and extract the relative `ObjectStorePath`. + fn get_store_and_path(&self, path: &str) -> Result<StoreAndPath> { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => { + let parsed = parse_s3_url(path)?; Review Comment: I noticed that although `parse_s3_url()` preserves consecutive slashes, we subsequently pass the relative path to `ObjectStorePath::parse()`, which strips leading/trailing slashes and rejects empty path segments. This means distinct S3 object keys could resolve to the same object, which is particularly concerning for delete operations. Could we explicitly reject paths that cannot be represented losslessly by `object_store::path::Path`, and add tests at the storage layer rather than only testing URL parsing? ########## crates/storage/object_store/src/lib.rs: ########## @@ -0,0 +1,1517 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `object_store`-based storage implementation for Apache Iceberg. +//! +//! This crate provides [`ObjectStoreStorage`] and [`ObjectStoreStorageFactory`], +//! which implement the [`Storage`] and +//! [`StorageFactory`] traits from the `iceberg` crate +//! using the [`object_store`](https://docs.rs/object_store) crate as the backend. +//! +//! Currently only S3 storage is supported (via the `object_store-s3` feature flag, +//! enabled by default). + +#[cfg(feature = "object_store-s3")] +mod s3; + +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use bytes::{Bytes, BytesMut}; +use dashmap::DashMap; +use futures::stream::BoxStream; +use futures::{StreamExt, TryStreamExt}; +use iceberg::io::{ + FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, + StorageFactory, +}; +#[cfg(feature = "object_store-s3")] +use iceberg::io::{S3_DELETE_BATCH_SIZE, S3_MULTIPART_PART_SIZE_BYTES, S3Config}; +use iceberg::{Error, ErrorKind, Result}; +use object_store::path::Path as ObjectStorePath; +use object_store::{MultipartUpload, ObjectStore, ObjectStoreExt, PutPayload}; +#[cfg(feature = "object_store-s3")] +use s3::{S3RetrySettings, build_s3_store, parse_s3_url}; +use serde::{Deserialize, Serialize}; +use tokio::task::JoinSet; + +/// Convert an `object_store::Error` into an `iceberg::Error`, +/// dispatching known variants to their corresponding `ErrorKind`. +fn from_object_store_error(e: object_store::Error) -> Error { + let (kind, msg) = match &e { + object_store::Error::NotFound { path, .. } => { + (ErrorKind::Unexpected, format!("Object not found: {path}")) + } + object_store::Error::AlreadyExists { path, .. } => ( + ErrorKind::Unexpected, + format!("Object already exists: {path}"), + ), + object_store::Error::PermissionDenied { path, .. } => { + (ErrorKind::Unexpected, format!("Permission denied: {path}")) + } + object_store::Error::Unauthenticated { path, .. } => { + (ErrorKind::Unexpected, format!("Unauthenticated: {path}")) + } + object_store::Error::NotSupported { .. } => ( + ErrorKind::FeatureUnsupported, + "Operation not supported".to_string(), + ), + _ => ( + ErrorKind::Unexpected, + "Failure in doing io operation".to_string(), + ), + }; + Error::new(kind, msg).with_source(e) +} + +/// Default batch size for S3 bulk deletions (matches Iceberg Java specification). +pub(crate) const DEFAULT_DELETE_BATCH_SIZE: usize = 250; +/// Maximum batch size allowed by the AWS S3 DeleteObjects API specification. +pub(crate) const S3_MAX_DELETE_BATCH_SIZE: usize = 1000; +/// Default part size for S3 multipart uploads (32 MiB, matches Iceberg Java specification). +pub(crate) const DEFAULT_PART_SIZE_BYTES: usize = 32 * 1024 * 1024; +/// Minimum part size allowed by the AWS S3 MultipartUpload API specification (5 MiB). +pub(crate) const MIN_PART_SIZE_BYTES: usize = 5 * 1024 * 1024; + +fn parse_delete_batch_size(config: &StorageConfig) -> Result<usize> { + let Some(val) = config.get(S3_DELETE_BATCH_SIZE) else { + return Ok(DEFAULT_DELETE_BATCH_SIZE); + }; + let batch_size = val.parse::<usize>().map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_DELETE_BATCH_SIZE}: {val}: {e}"), + ) + })?; + if batch_size == 0 { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_DELETE_BATCH_SIZE}: batch size must be greater than 0"), + )); + } + Ok(batch_size.clamp(1, S3_MAX_DELETE_BATCH_SIZE)) +} + +fn default_delete_batch_size() -> usize { + DEFAULT_DELETE_BATCH_SIZE +} + +fn parse_part_size_bytes(config: &StorageConfig) -> Result<usize> { + let Some(val) = config.get(S3_MULTIPART_PART_SIZE_BYTES) else { + return Ok(DEFAULT_PART_SIZE_BYTES); + }; + let part_size = val.parse::<usize>().map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {val}: {e}"), + ) + })?; + if part_size < MIN_PART_SIZE_BYTES { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {part_size} bytes is below the S3 minimum part size of 5 MiB" + ), + )); + } + if part_size > i32::MAX as usize { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {part_size} bytes is above the maximum allowed by Java spec" + ), + )); + } + Ok(part_size) +} + +fn default_part_size_bytes() -> usize { + DEFAULT_PART_SIZE_BYTES +} + +/// Convert `object_store::ObjectMeta` into `iceberg::io::FileMetadata`. +fn to_file_metadata(meta: object_store::ObjectMeta) -> FileMetadata { + FileMetadata { size: meta.size } +} + +/// `object_store`-based storage factory. +/// +/// Use this factory with `FileIOBuilder::new(factory)` to create FileIO instances +/// backed by the `object_store` crate. +#[non_exhaustive] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum ObjectStoreStorageFactory { + /// S3 storage factory. + #[cfg(feature = "object_store-s3")] + S3, +} + +#[typetag::serde(name = "ObjectStoreStorageFactory")] +impl StorageFactory for ObjectStoreStorageFactory { + #[allow(unused_variables)] + fn build(&self, config: &StorageConfig) -> Result<Arc<dyn Storage>> { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorageFactory::S3 => { + let s3_config = S3Config::try_from(config)?; + s3::validate_s3_config(&s3_config)?; + let delete_batch_size = parse_delete_batch_size(config)?; + let part_size_bytes = parse_part_size_bytes(config)?; + let retry_settings = S3RetrySettings::parse(config)?; + Ok(Arc::new(ObjectStoreStorage::S3(S3Storage { + config: Arc::new(s3_config), + delete_batch_size, + part_size_bytes, + retry_settings, + store_cache: Arc::new(DashMap::new()), + }))) + } + } + } +} + +type StoreCache = Arc<DashMap<String, Arc<dyn ObjectStore>>>; + +/// `object_store` S3 storage state. +#[derive(Clone, Serialize, Deserialize)] +pub struct S3Storage { + config: Arc<S3Config>, + #[serde(default = "default_delete_batch_size")] + delete_batch_size: usize, + #[serde(default = "default_part_size_bytes")] + part_size_bytes: usize, + #[serde(default)] + retry_settings: S3RetrySettings, + #[serde(skip, default)] + store_cache: StoreCache, +} + +impl std::fmt::Debug for S3Storage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("S3Storage") + .field("endpoint", &self.config.endpoint) + .field("region", &self.config.region) + .field("access_key_id", &self.config.access_key_id) + .field( + "secret_access_key", + &self.config.secret_access_key.as_ref().map(|_| "[REDACTED]"), + ) + .field( + "session_token", + &self.config.session_token.as_ref().map(|_| "[REDACTED]"), + ) + .field( + "server_side_encryption_customer_key", + &self + .config + .server_side_encryption_customer_key + .as_ref() + .map(|_| "[REDACTED]"), + ) + .field("delete_batch_size", &self.delete_batch_size) + .field("part_size_bytes", &self.part_size_bytes) + .finish_non_exhaustive() + } +} + +/// `object_store`-based storage implementation. +/// +/// Stores are cached per bucket to avoid rebuilding the client on every operation. +#[non_exhaustive] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum ObjectStoreStorage { + /// S3 storage variant. + #[cfg(feature = "object_store-s3")] + S3(S3Storage), +} + +#[derive(Debug)] +struct StoreAndPath { + bucket: String, + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, +} + +/// Helper for batching deletions per bucket. +struct BucketBatch { + store: Arc<dyn ObjectStore>, + locations: Vec<ObjectStorePath>, +} + +impl ObjectStoreStorage { + fn delete_batch_size(&self) -> usize { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => s3.delete_batch_size.clamp(1, S3_MAX_DELETE_BATCH_SIZE), + } + } + + fn part_size_bytes(&self) -> usize { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => s3.part_size_bytes.max(MIN_PART_SIZE_BYTES), + } + } + + /// Get or create a cached store and extract the relative `ObjectStorePath`. + fn get_store_and_path(&self, path: &str) -> Result<StoreAndPath> { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => { + let parsed = parse_s3_url(path)?; + + let store = s3 + .store_cache + .entry(parsed.bucket.clone()) + .or_try_insert_with(|| { + build_s3_store(&s3.config, &s3.retry_settings, &parsed.bucket) + })? + .value() + .clone(); + + let object_path = + ObjectStorePath::parse(parsed.relative.as_str()).map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid relative path: {}", parsed.relative), + ) + .with_source(e) + })?; + + Ok(StoreAndPath { + bucket: parsed.bucket, + store, + path: object_path, + }) + } + } + } +} + +#[typetag::serde(name = "ObjectStoreStorage")] +#[async_trait] +impl Storage for ObjectStoreStorage { + async fn exists(&self, path: &str) -> Result<bool> { + let target = self.get_store_and_path(path)?; + match target.store.head(&target.path).await { + Ok(_) => Ok(true), + Err(object_store::Error::NotFound { .. }) => Ok(false), + Err(e) => Err(from_object_store_error(e)), + } + } + + async fn metadata(&self, path: &str) -> Result<FileMetadata> { + let target = self.get_store_and_path(path)?; + let meta = target + .store + .head(&target.path) + .await + .map_err(from_object_store_error)?; + Ok(to_file_metadata(meta)) + } + + async fn read(&self, path: &str) -> Result<Bytes> { + let target = self.get_store_and_path(path)?; + let result = target + .store + .get(&target.path) + .await + .map_err(from_object_store_error)?; + result.bytes().await.map_err(from_object_store_error) + } + + async fn reader(&self, path: &str) -> Result<Box<dyn FileRead>> { + let target = self.get_store_and_path(path)?; + Ok(Box::new(ObjectStoreReader { + store: target.store, + path: target.path, + })) + } + + async fn write(&self, path: &str, bs: Bytes) -> Result<()> { + let target = self.get_store_and_path(path)?; + target + .store + .put(&target.path, PutPayload::from_bytes(bs)) + .await + .map_err(from_object_store_error)?; + Ok(()) + } + + async fn writer(&self, path: &str) -> Result<Box<dyn FileWrite>> { + let target = self.get_store_and_path(path)?; + Ok(Box::new(ObjectStoreWriter::new( + target.store, + target.path, + self.part_size_bytes(), + ))) + } + + async fn delete(&self, path: &str) -> Result<()> { + let target = self.get_store_and_path(path)?; + target + .store + .delete(&target.path) + .await + .map_err(from_object_store_error)?; + Ok(()) + } + + async fn delete_prefix(&self, path: &str) -> Result<()> { + let target = self.get_store_and_path(path)?; + let locations = target + .store + .list(Some(&target.path)) + .map_ok(|m| m.location) + .boxed(); + target + .store + .delete_stream(locations) + .try_for_each(|_| async { Ok(()) }) + .await + .map_err(from_object_store_error)?; + Ok(()) + } + + async fn delete_stream(&self, paths: BoxStream<'static, String>) -> Result<()> { + let batch_size = self.delete_batch_size(); + let mut chunk_stream = paths.chunks(batch_size); + + while let Some(chunk) = chunk_stream.next().await { + let mut batches: std::collections::HashMap<String, BucketBatch> = + std::collections::HashMap::new(); + + for path in chunk { + let target = self.get_store_and_path(&path)?; + batches + .entry(target.bucket) + .or_insert_with(|| BucketBatch { + store: target.store, + locations: Vec::new(), + }) + .locations + .push(target.path); + } + + for (_bucket, batch) in batches { + let location_stream = + futures::stream::iter(batch.locations.into_iter().map(Ok)).boxed(); + batch + .store + .delete_stream(location_stream) + .try_for_each(|_| async { Ok(()) }) + .await + .map_err(from_object_store_error)?; + } + } + Ok(()) + } + + fn new_input(&self, path: &str) -> Result<InputFile> { + Ok(InputFile::new(Arc::new(self.clone()), path.to_string())) + } + + fn new_output(&self, path: &str) -> Result<OutputFile> { + Ok(OutputFile::new(Arc::new(self.clone()), path.to_string())) + } +} + +/// Reader that implements `FileRead` using `object_store`. +struct ObjectStoreReader { + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, +} + +#[async_trait] +impl FileRead for ObjectStoreReader { + async fn read(&self, range: Range<u64>) -> Result<Bytes> { + if range.is_empty() { + return Ok(Bytes::new()); + } + let opts = object_store::GetOptions { + range: Some((range.start..range.end).into()), + ..Default::default() + }; + let result = self + .store + .get_opts(&self.path, opts) + .await + .map_err(from_object_store_error)?; + result.bytes().await.map_err(from_object_store_error) + } +} + +/// Default maximum concurrent in-flight part uploads. +const MAX_CONCURRENT_PART_UPLOADS: usize = 8; + +/// Writer that implements `FileWrite` using `object_store` multipart upload. +struct ObjectStoreWriter { + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, + upload: Option<Box<dyn MultipartUpload>>, + buffer: BytesMut, + tasks: JoinSet<object_store::Result<()>>, + parts_submitted: usize, + bytes_written: u64, + part_size_bytes: usize, + closed: bool, +} + +impl ObjectStoreWriter { + fn new(store: Arc<dyn ObjectStore>, path: ObjectStorePath, part_size_bytes: usize) -> Self { + Self { + store, + path, + upload: None, + buffer: BytesMut::new(), + tasks: JoinSet::new(), + parts_submitted: 0, + bytes_written: 0, + part_size_bytes, + closed: false, + } + } + + #[cfg(test)] + fn with_mock_upload(upload: Box<dyn MultipartUpload>, part_size_bytes: usize) -> Self { + Self { + store: Arc::new(object_store::memory::InMemory::new()), + path: ObjectStorePath::from("mock_test"), + upload: Some(upload), + buffer: BytesMut::new(), + tasks: JoinSet::new(), + parts_submitted: 0, + bytes_written: 0, + part_size_bytes, + closed: false, + } + } + + /// Aborts all in-flight task uploads, drains the join set to ensure no + /// requests race the abort call, and then aborts the multipart upload session. + async fn drain_and_abort( + tasks: &mut JoinSet<object_store::Result<()>>, + upload: &mut Box<dyn MultipartUpload>, + context: &'static str, + ) { + tasks.abort_all(); + while tasks.join_next().await.is_some() {} + + if let Err(abort_err) = upload.abort().await { + tracing::warn!( + error = %abort_err, + "Failed to abort multipart upload after {context}" + ); + } + } + + /// Best-effort abort on upload error, converting the underlying + /// object_store error to an iceberg Error while logging abort failures. + async fn abort_and_wrap( + tasks: &mut JoinSet<object_store::Result<()>>, + upload: &mut Box<dyn MultipartUpload>, + e: object_store::Error, + context: &'static str, + ) -> Error { + Self::drain_and_abort(tasks, upload, context).await; + from_object_store_error(e) + } + + /// Drains in-flight tasks down below `MAX_CONCURRENT_PART_UPLOADS`. + async fn drain_capacity( + tasks: &mut JoinSet<object_store::Result<()>>, + upload: &mut Box<dyn MultipartUpload>, + ) -> Result<()> { + while tasks.len() >= MAX_CONCURRENT_PART_UPLOADS { + if let Some(res) = tasks.join_next().await { + match res { + Ok(Err(e)) => { + return Err( + Self::abort_and_wrap(tasks, upload, e, "part upload failure").await, + ); + } + Err(join_err) => { + Self::drain_and_abort(tasks, upload, "task panic").await; + return Err( + Error::new(ErrorKind::Unexpected, "Part upload task panicked") + .with_source(join_err), + ); + } + Ok(Ok(())) => {} + } + } + } + Ok(()) + } + + fn check_tokio_runtime() -> Result<()> { + tokio::runtime::Handle::try_current() + .map(|_| ()) + .map_err(|e| { + Error::new( + ErrorKind::Unexpected, + "Tokio runtime not found for async task execution", + ) + .with_source(e) + }) + } + + /// Flushes any buffered bytes as an in-flight part upload to S3, + /// throttling concurrency so that at most `MAX_CONCURRENT_PART_UPLOADS` + /// uploads are in flight at any given time. + async fn flush_buffer( + buffer: &mut BytesMut, + tasks: &mut JoinSet<object_store::Result<()>>, + parts_submitted: &mut usize, + upload: &mut Box<dyn MultipartUpload>, + ) -> Result<()> { + if !buffer.is_empty() { + Self::drain_capacity(tasks, upload).await?; + + Self::check_tokio_runtime()?; + let part_data = std::mem::take(buffer).freeze(); + let part_fut = upload.put_part(PutPayload::from_bytes(part_data)); + tasks.spawn(part_fut); + *parts_submitted += 1; + } + Ok(()) + } + + /// Accumulates bytes into `buffer`, flushing parts when the configured part size is reached. + async fn append_bytes( + buffer: &mut BytesMut, + tasks: &mut JoinSet<object_store::Result<()>>, + parts_submitted: &mut usize, + part_size_bytes: usize, + mut bs: Bytes, + upload: &mut Box<dyn MultipartUpload>, + ) -> Result<()> { + while !bs.is_empty() { + let remaining = part_size_bytes.saturating_sub(buffer.len()); + if remaining == 0 { + Self::flush_buffer(buffer, tasks, parts_submitted, upload).await?; + continue; + } + + if bs.len() < remaining { + buffer.extend_from_slice(&bs); + return Ok(()); + } + let chunk = bs.split_to(remaining); + buffer.extend_from_slice(&chunk); + Self::flush_buffer(buffer, tasks, parts_submitted, upload).await?; + } + Ok(()) + } +} + +impl Drop for ObjectStoreWriter { + fn drop(&mut self) { + if let Some(mut upload) = self.upload.take() { + if Self::check_tokio_runtime().is_ok() { + tokio::runtime::Handle::current().spawn(async move { + if let Err(e) = upload.abort().await { + tracing::warn!( + error = %e, + "Failed to abort multipart upload on drop" + ); + } + }); + } else { + tracing::warn!( + "ObjectStoreWriter dropped outside a Tokio runtime; multipart upload abort skipped" + ); + } + } + } +} + +#[async_trait] +impl FileWrite for ObjectStoreWriter { + async fn write(&mut self, bs: Bytes) -> Result<()> { + if self.closed { + return Err(Error::new( + ErrorKind::PreconditionFailed, + "Writer has already been closed", + )); + } + self.bytes_written += bs.len() as u64; + + if self.upload.is_none() { + if self.buffer.len() + bs.len() < self.part_size_bytes { + self.buffer.extend_from_slice(&bs); + return Ok(()); + } + + // Exceeded threshold: initialize multipart upload session + let upload = self + .store + .put_multipart(&self.path) + .await + .map_err(from_object_store_error)?; + self.upload = Some(upload); + } + + let upload = self.upload.as_mut().unwrap(); + if let Err(e) = Self::append_bytes( + &mut self.buffer, + &mut self.tasks, + &mut self.parts_submitted, + self.part_size_bytes, + bs, + upload, + ) + .await + { + let _ = self.upload.take(); Review Comment: Could we explicitly transition the writer into a failed state when a multipart upload fails? Currently, we clear `self.upload` but leave the writer open. A subsequent `close()` would take the single-PUT path and potentially publish only the remaining buffered bytes while returning the original `bytes_written` as the file size. I think both `write()` and `close()` should reject further operations once the writer has encountered an unrecoverable error. A regression test would be helpful here. ########## crates/storage/object_store/src/lib.rs: ########## @@ -0,0 +1,1517 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! `object_store`-based storage implementation for Apache Iceberg. +//! +//! This crate provides [`ObjectStoreStorage`] and [`ObjectStoreStorageFactory`], +//! which implement the [`Storage`] and +//! [`StorageFactory`] traits from the `iceberg` crate +//! using the [`object_store`](https://docs.rs/object_store) crate as the backend. +//! +//! Currently only S3 storage is supported (via the `object_store-s3` feature flag, +//! enabled by default). + +#[cfg(feature = "object_store-s3")] +mod s3; + +use std::ops::Range; +use std::sync::Arc; + +use async_trait::async_trait; +use bytes::{Bytes, BytesMut}; +use dashmap::DashMap; +use futures::stream::BoxStream; +use futures::{StreamExt, TryStreamExt}; +use iceberg::io::{ + FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, + StorageFactory, +}; +#[cfg(feature = "object_store-s3")] +use iceberg::io::{S3_DELETE_BATCH_SIZE, S3_MULTIPART_PART_SIZE_BYTES, S3Config}; +use iceberg::{Error, ErrorKind, Result}; +use object_store::path::Path as ObjectStorePath; +use object_store::{MultipartUpload, ObjectStore, ObjectStoreExt, PutPayload}; +#[cfg(feature = "object_store-s3")] +use s3::{S3RetrySettings, build_s3_store, parse_s3_url}; +use serde::{Deserialize, Serialize}; +use tokio::task::JoinSet; + +/// Convert an `object_store::Error` into an `iceberg::Error`, +/// dispatching known variants to their corresponding `ErrorKind`. +fn from_object_store_error(e: object_store::Error) -> Error { + let (kind, msg) = match &e { + object_store::Error::NotFound { path, .. } => { + (ErrorKind::Unexpected, format!("Object not found: {path}")) + } + object_store::Error::AlreadyExists { path, .. } => ( + ErrorKind::Unexpected, + format!("Object already exists: {path}"), + ), + object_store::Error::PermissionDenied { path, .. } => { + (ErrorKind::Unexpected, format!("Permission denied: {path}")) + } + object_store::Error::Unauthenticated { path, .. } => { + (ErrorKind::Unexpected, format!("Unauthenticated: {path}")) + } + object_store::Error::NotSupported { .. } => ( + ErrorKind::FeatureUnsupported, + "Operation not supported".to_string(), + ), + _ => ( + ErrorKind::Unexpected, + "Failure in doing io operation".to_string(), + ), + }; + Error::new(kind, msg).with_source(e) +} + +/// Default batch size for S3 bulk deletions (matches Iceberg Java specification). +pub(crate) const DEFAULT_DELETE_BATCH_SIZE: usize = 250; +/// Maximum batch size allowed by the AWS S3 DeleteObjects API specification. +pub(crate) const S3_MAX_DELETE_BATCH_SIZE: usize = 1000; +/// Default part size for S3 multipart uploads (32 MiB, matches Iceberg Java specification). +pub(crate) const DEFAULT_PART_SIZE_BYTES: usize = 32 * 1024 * 1024; +/// Minimum part size allowed by the AWS S3 MultipartUpload API specification (5 MiB). +pub(crate) const MIN_PART_SIZE_BYTES: usize = 5 * 1024 * 1024; + +fn parse_delete_batch_size(config: &StorageConfig) -> Result<usize> { + let Some(val) = config.get(S3_DELETE_BATCH_SIZE) else { + return Ok(DEFAULT_DELETE_BATCH_SIZE); + }; + let batch_size = val.parse::<usize>().map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_DELETE_BATCH_SIZE}: {val}: {e}"), + ) + })?; + if batch_size == 0 { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_DELETE_BATCH_SIZE}: batch size must be greater than 0"), + )); + } + Ok(batch_size.clamp(1, S3_MAX_DELETE_BATCH_SIZE)) +} + +fn default_delete_batch_size() -> usize { + DEFAULT_DELETE_BATCH_SIZE +} + +fn parse_part_size_bytes(config: &StorageConfig) -> Result<usize> { + let Some(val) = config.get(S3_MULTIPART_PART_SIZE_BYTES) else { + return Ok(DEFAULT_PART_SIZE_BYTES); + }; + let part_size = val.parse::<usize>().map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {val}: {e}"), + ) + })?; + if part_size < MIN_PART_SIZE_BYTES { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {part_size} bytes is below the S3 minimum part size of 5 MiB" + ), + )); + } + if part_size > i32::MAX as usize { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "Invalid {S3_MULTIPART_PART_SIZE_BYTES}: {part_size} bytes is above the maximum allowed by Java spec" + ), + )); + } + Ok(part_size) +} + +fn default_part_size_bytes() -> usize { + DEFAULT_PART_SIZE_BYTES +} + +/// Convert `object_store::ObjectMeta` into `iceberg::io::FileMetadata`. +fn to_file_metadata(meta: object_store::ObjectMeta) -> FileMetadata { + FileMetadata { size: meta.size } +} + +/// `object_store`-based storage factory. +/// +/// Use this factory with `FileIOBuilder::new(factory)` to create FileIO instances +/// backed by the `object_store` crate. +#[non_exhaustive] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum ObjectStoreStorageFactory { + /// S3 storage factory. + #[cfg(feature = "object_store-s3")] + S3, +} + +#[typetag::serde(name = "ObjectStoreStorageFactory")] +impl StorageFactory for ObjectStoreStorageFactory { + #[allow(unused_variables)] + fn build(&self, config: &StorageConfig) -> Result<Arc<dyn Storage>> { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorageFactory::S3 => { + let s3_config = S3Config::try_from(config)?; + s3::validate_s3_config(&s3_config)?; + let delete_batch_size = parse_delete_batch_size(config)?; + let part_size_bytes = parse_part_size_bytes(config)?; + let retry_settings = S3RetrySettings::parse(config)?; + Ok(Arc::new(ObjectStoreStorage::S3(S3Storage { + config: Arc::new(s3_config), + delete_batch_size, + part_size_bytes, + retry_settings, + store_cache: Arc::new(DashMap::new()), + }))) + } + } + } +} + +type StoreCache = Arc<DashMap<String, Arc<dyn ObjectStore>>>; + +/// `object_store` S3 storage state. +#[derive(Clone, Serialize, Deserialize)] +pub struct S3Storage { + config: Arc<S3Config>, + #[serde(default = "default_delete_batch_size")] + delete_batch_size: usize, + #[serde(default = "default_part_size_bytes")] + part_size_bytes: usize, + #[serde(default)] + retry_settings: S3RetrySettings, + #[serde(skip, default)] + store_cache: StoreCache, +} + +impl std::fmt::Debug for S3Storage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("S3Storage") + .field("endpoint", &self.config.endpoint) + .field("region", &self.config.region) + .field("access_key_id", &self.config.access_key_id) + .field( + "secret_access_key", + &self.config.secret_access_key.as_ref().map(|_| "[REDACTED]"), + ) + .field( + "session_token", + &self.config.session_token.as_ref().map(|_| "[REDACTED]"), + ) + .field( + "server_side_encryption_customer_key", + &self + .config + .server_side_encryption_customer_key + .as_ref() + .map(|_| "[REDACTED]"), + ) + .field("delete_batch_size", &self.delete_batch_size) + .field("part_size_bytes", &self.part_size_bytes) + .finish_non_exhaustive() + } +} + +/// `object_store`-based storage implementation. +/// +/// Stores are cached per bucket to avoid rebuilding the client on every operation. +#[non_exhaustive] +#[derive(Clone, Debug, Serialize, Deserialize)] +pub enum ObjectStoreStorage { + /// S3 storage variant. + #[cfg(feature = "object_store-s3")] + S3(S3Storage), +} + +#[derive(Debug)] +struct StoreAndPath { + bucket: String, + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, +} + +/// Helper for batching deletions per bucket. +struct BucketBatch { + store: Arc<dyn ObjectStore>, + locations: Vec<ObjectStorePath>, +} + +impl ObjectStoreStorage { + fn delete_batch_size(&self) -> usize { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => s3.delete_batch_size.clamp(1, S3_MAX_DELETE_BATCH_SIZE), + } + } + + fn part_size_bytes(&self) -> usize { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => s3.part_size_bytes.max(MIN_PART_SIZE_BYTES), + } + } + + /// Get or create a cached store and extract the relative `ObjectStorePath`. + fn get_store_and_path(&self, path: &str) -> Result<StoreAndPath> { + match self { + #[cfg(feature = "object_store-s3")] + ObjectStoreStorage::S3(s3) => { + let parsed = parse_s3_url(path)?; + + let store = s3 + .store_cache + .entry(parsed.bucket.clone()) + .or_try_insert_with(|| { + build_s3_store(&s3.config, &s3.retry_settings, &parsed.bucket) + })? + .value() + .clone(); + + let object_path = + ObjectStorePath::parse(parsed.relative.as_str()).map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid relative path: {}", parsed.relative), + ) + .with_source(e) + })?; + + Ok(StoreAndPath { + bucket: parsed.bucket, + store, + path: object_path, + }) + } + } + } +} + +#[typetag::serde(name = "ObjectStoreStorage")] +#[async_trait] +impl Storage for ObjectStoreStorage { + async fn exists(&self, path: &str) -> Result<bool> { + let target = self.get_store_and_path(path)?; + match target.store.head(&target.path).await { + Ok(_) => Ok(true), + Err(object_store::Error::NotFound { .. }) => Ok(false), + Err(e) => Err(from_object_store_error(e)), + } + } + + async fn metadata(&self, path: &str) -> Result<FileMetadata> { + let target = self.get_store_and_path(path)?; + let meta = target + .store + .head(&target.path) + .await + .map_err(from_object_store_error)?; + Ok(to_file_metadata(meta)) + } + + async fn read(&self, path: &str) -> Result<Bytes> { + let target = self.get_store_and_path(path)?; + let result = target + .store + .get(&target.path) + .await + .map_err(from_object_store_error)?; + result.bytes().await.map_err(from_object_store_error) + } + + async fn reader(&self, path: &str) -> Result<Box<dyn FileRead>> { + let target = self.get_store_and_path(path)?; + Ok(Box::new(ObjectStoreReader { + store: target.store, + path: target.path, + })) + } + + async fn write(&self, path: &str, bs: Bytes) -> Result<()> { + let target = self.get_store_and_path(path)?; + target + .store + .put(&target.path, PutPayload::from_bytes(bs)) + .await + .map_err(from_object_store_error)?; + Ok(()) + } + + async fn writer(&self, path: &str) -> Result<Box<dyn FileWrite>> { + let target = self.get_store_and_path(path)?; + Ok(Box::new(ObjectStoreWriter::new( + target.store, + target.path, + self.part_size_bytes(), + ))) + } + + async fn delete(&self, path: &str) -> Result<()> { + let target = self.get_store_and_path(path)?; + target + .store + .delete(&target.path) + .await + .map_err(from_object_store_error)?; + Ok(()) + } + + async fn delete_prefix(&self, path: &str) -> Result<()> { + let target = self.get_store_and_path(path)?; + let locations = target + .store + .list(Some(&target.path)) + .map_ok(|m| m.location) + .boxed(); + target + .store + .delete_stream(locations) + .try_for_each(|_| async { Ok(()) }) + .await + .map_err(from_object_store_error)?; + Ok(()) + } + + async fn delete_stream(&self, paths: BoxStream<'static, String>) -> Result<()> { + let batch_size = self.delete_batch_size(); + let mut chunk_stream = paths.chunks(batch_size); + + while let Some(chunk) = chunk_stream.next().await { + let mut batches: std::collections::HashMap<String, BucketBatch> = + std::collections::HashMap::new(); + + for path in chunk { + let target = self.get_store_and_path(&path)?; + batches + .entry(target.bucket) + .or_insert_with(|| BucketBatch { + store: target.store, + locations: Vec::new(), + }) + .locations + .push(target.path); + } + + for (_bucket, batch) in batches { + let location_stream = + futures::stream::iter(batch.locations.into_iter().map(Ok)).boxed(); + batch + .store + .delete_stream(location_stream) + .try_for_each(|_| async { Ok(()) }) + .await + .map_err(from_object_store_error)?; + } + } + Ok(()) + } + + fn new_input(&self, path: &str) -> Result<InputFile> { + Ok(InputFile::new(Arc::new(self.clone()), path.to_string())) + } + + fn new_output(&self, path: &str) -> Result<OutputFile> { + Ok(OutputFile::new(Arc::new(self.clone()), path.to_string())) + } +} + +/// Reader that implements `FileRead` using `object_store`. +struct ObjectStoreReader { + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, +} + +#[async_trait] +impl FileRead for ObjectStoreReader { + async fn read(&self, range: Range<u64>) -> Result<Bytes> { + if range.is_empty() { + return Ok(Bytes::new()); + } + let opts = object_store::GetOptions { + range: Some((range.start..range.end).into()), + ..Default::default() + }; + let result = self + .store + .get_opts(&self.path, opts) + .await + .map_err(from_object_store_error)?; + result.bytes().await.map_err(from_object_store_error) + } +} + +/// Default maximum concurrent in-flight part uploads. +const MAX_CONCURRENT_PART_UPLOADS: usize = 8; + +/// Writer that implements `FileWrite` using `object_store` multipart upload. +struct ObjectStoreWriter { + store: Arc<dyn ObjectStore>, + path: ObjectStorePath, + upload: Option<Box<dyn MultipartUpload>>, + buffer: BytesMut, + tasks: JoinSet<object_store::Result<()>>, + parts_submitted: usize, + bytes_written: u64, + part_size_bytes: usize, + closed: bool, +} + +impl ObjectStoreWriter { + fn new(store: Arc<dyn ObjectStore>, path: ObjectStorePath, part_size_bytes: usize) -> Self { + Self { + store, + path, + upload: None, + buffer: BytesMut::new(), + tasks: JoinSet::new(), + parts_submitted: 0, + bytes_written: 0, + part_size_bytes, + closed: false, + } + } + + #[cfg(test)] + fn with_mock_upload(upload: Box<dyn MultipartUpload>, part_size_bytes: usize) -> Self { + Self { + store: Arc::new(object_store::memory::InMemory::new()), + path: ObjectStorePath::from("mock_test"), + upload: Some(upload), + buffer: BytesMut::new(), + tasks: JoinSet::new(), + parts_submitted: 0, + bytes_written: 0, + part_size_bytes, + closed: false, + } + } + + /// Aborts all in-flight task uploads, drains the join set to ensure no + /// requests race the abort call, and then aborts the multipart upload session. + async fn drain_and_abort( + tasks: &mut JoinSet<object_store::Result<()>>, + upload: &mut Box<dyn MultipartUpload>, + context: &'static str, + ) { + tasks.abort_all(); + while tasks.join_next().await.is_some() {} + + if let Err(abort_err) = upload.abort().await { + tracing::warn!( + error = %abort_err, + "Failed to abort multipart upload after {context}" + ); + } + } + + /// Best-effort abort on upload error, converting the underlying + /// object_store error to an iceberg Error while logging abort failures. + async fn abort_and_wrap( + tasks: &mut JoinSet<object_store::Result<()>>, + upload: &mut Box<dyn MultipartUpload>, + e: object_store::Error, + context: &'static str, + ) -> Error { + Self::drain_and_abort(tasks, upload, context).await; + from_object_store_error(e) + } + + /// Drains in-flight tasks down below `MAX_CONCURRENT_PART_UPLOADS`. + async fn drain_capacity( + tasks: &mut JoinSet<object_store::Result<()>>, + upload: &mut Box<dyn MultipartUpload>, + ) -> Result<()> { + while tasks.len() >= MAX_CONCURRENT_PART_UPLOADS { + if let Some(res) = tasks.join_next().await { + match res { + Ok(Err(e)) => { + return Err( + Self::abort_and_wrap(tasks, upload, e, "part upload failure").await, + ); + } + Err(join_err) => { + Self::drain_and_abort(tasks, upload, "task panic").await; + return Err( + Error::new(ErrorKind::Unexpected, "Part upload task panicked") + .with_source(join_err), + ); + } + Ok(Ok(())) => {} + } + } + } + Ok(()) + } + + fn check_tokio_runtime() -> Result<()> { + tokio::runtime::Handle::try_current() + .map(|_| ()) + .map_err(|e| { + Error::new( + ErrorKind::Unexpected, + "Tokio runtime not found for async task execution", + ) + .with_source(e) + }) + } + + /// Flushes any buffered bytes as an in-flight part upload to S3, + /// throttling concurrency so that at most `MAX_CONCURRENT_PART_UPLOADS` + /// uploads are in flight at any given time. + async fn flush_buffer( + buffer: &mut BytesMut, + tasks: &mut JoinSet<object_store::Result<()>>, + parts_submitted: &mut usize, + upload: &mut Box<dyn MultipartUpload>, + ) -> Result<()> { + if !buffer.is_empty() { + Self::drain_capacity(tasks, upload).await?; + + Self::check_tokio_runtime()?; + let part_data = std::mem::take(buffer).freeze(); + let part_fut = upload.put_part(PutPayload::from_bytes(part_data)); + tasks.spawn(part_fut); Review Comment: Could we reuse `drain_and_abort()` in the `Drop` implementation as well? The current implementation spawns the abort task without first cancelling and draining the in-flight part uploads. This appears to reintroduce the race that `drain_and_abort()` was intended to address. We could move the `JoinSet` into the cleanup task using `std::mem::take(&mut self.tasks)` and reuse the existing helper. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
