lance_table/io/
commit.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4//! Trait for commit implementations.
5//!
6//! In Lance, a transaction is committed by writing the next manifest file.
7//! However, care should be taken to ensure that the manifest file is written
8//! only once, even if there are concurrent writers. Different stores have
9//! different abilities to handle concurrent writes, so a trait is provided
10//! to allow for different implementations.
11//!
12//! The trait [CommitHandler] can be implemented to provide different commit
13//! strategies. The default implementation for most object stores is
14//! [RenameCommitHandler], which writes the manifest to a temporary path, then
15//! renames the temporary path to the final path if no object already exists
16//! at the final path. This is an atomic operation in most object stores, but
17//! not in AWS S3. So for AWS S3, the default commit handler is
18//! [UnsafeCommitHandler], which writes the manifest to the final path without
19//! any checks.
20//!
21//! When providing your own commit handler, most often you are implementing in
22//! terms of a lock. The trait [CommitLock] can be implemented as a simpler
23//! alternative to [CommitHandler].
24
25use std::io;
26use std::sync::atomic::AtomicBool;
27use std::sync::Arc;
28use std::{fmt::Debug, fs::DirEntry};
29
30use futures::{
31    future::{self, BoxFuture},
32    stream::BoxStream,
33    StreamExt, TryStreamExt,
34};
35use lance_io::object_writer::WriteResult;
36use log::warn;
37use object_store::PutOptions;
38use object_store::{path::Path, Error as ObjectStoreError, ObjectStore as OSObjectStore};
39use snafu::location;
40use url::Url;
41
42#[cfg(feature = "dynamodb")]
43pub mod dynamodb;
44pub mod external_manifest;
45
46use lance_core::{Error, Result};
47use lance_io::object_store::{ObjectStore, ObjectStoreExt, ObjectStoreParams};
48
49#[cfg(feature = "dynamodb")]
50use {
51    self::external_manifest::{ExternalManifestCommitHandler, ExternalManifestStore},
52    aws_credential_types::provider::error::CredentialsError,
53    aws_credential_types::provider::ProvideCredentials,
54    lance_io::object_store::{providers::aws::build_aws_credential, StorageOptions},
55    object_store::aws::AmazonS3ConfigKey,
56    object_store::aws::AwsCredentialProvider,
57    std::borrow::Cow,
58    std::time::{Duration, SystemTime},
59};
60
61use crate::format::{is_detached_version, Index, Manifest};
62
63const VERSIONS_DIR: &str = "_versions";
64const MANIFEST_EXTENSION: &str = "manifest";
65const DETACHED_VERSION_PREFIX: &str = "d";
66
67/// How manifest files should be named.
68#[derive(Clone, Copy, Debug, PartialEq, Eq)]
69pub enum ManifestNamingScheme {
70    /// `_versions/{version}.manifest`
71    V1,
72    /// `_manifests/{u64::MAX - version}.manifest`
73    ///
74    /// Zero-padded and reversed for O(1) lookup of latest version on object stores.
75    V2,
76}
77
78impl ManifestNamingScheme {
79    pub fn manifest_path(&self, base: &Path, version: u64) -> Path {
80        let directory = base.child(VERSIONS_DIR);
81        if is_detached_version(version) {
82            // Detached versions should never show up first in a list operation which
83            // means it needs to come lexicographically after all attached manifest
84            // files and so we add the prefix `d`.  There is no need to invert the
85            // version number since detached versions are not part of the version
86            let directory = base.child(VERSIONS_DIR);
87            directory.child(format!(
88                "{DETACHED_VERSION_PREFIX}{version}.{MANIFEST_EXTENSION}"
89            ))
90        } else {
91            match self {
92                Self::V1 => directory.child(format!("{version}.{MANIFEST_EXTENSION}")),
93                Self::V2 => {
94                    let inverted_version = u64::MAX - version;
95                    directory.child(format!("{inverted_version:020}.{MANIFEST_EXTENSION}"))
96                }
97            }
98        }
99    }
100
101    pub fn parse_version(&self, filename: &str) -> Option<u64> {
102        let file_number = filename
103            .split_once('.')
104            // Detached versions will fail the `parse` step, which is ok.
105            .and_then(|(version_str, _)| version_str.parse::<u64>().ok());
106        match self {
107            Self::V1 => file_number,
108            Self::V2 => file_number.map(|v| u64::MAX - v),
109        }
110    }
111
112    pub fn detect_scheme(filename: &str) -> Option<Self> {
113        if filename.starts_with(DETACHED_VERSION_PREFIX) {
114            // Currently, detached versions must imply V2
115            return Some(Self::V2);
116        }
117        if filename.ends_with(MANIFEST_EXTENSION) {
118            const V2_LEN: usize = 20 + 1 + MANIFEST_EXTENSION.len();
119            if filename.len() == V2_LEN {
120                Some(Self::V2)
121            } else {
122                Some(Self::V1)
123            }
124        } else {
125            None
126        }
127    }
128
129    pub fn detect_scheme_staging(filename: &str) -> Self {
130        // We shouldn't have to worry about detached versions here since there is no
131        // such thing as "detached" and "staged" at the same time.
132        if filename.chars().nth(20) == Some('.') {
133            Self::V2
134        } else {
135            Self::V1
136        }
137    }
138}
139
140/// Migrate all V1 manifests to V2 naming scheme.
141///
142/// This function will rename all V1 manifests to V2 naming scheme.
143///
144/// This function is idempotent, and can be run multiple times without
145/// changing the state of the object store.
146///
147/// However, it should not be run while other concurrent operations are happening.
148/// And it should also run until completion before resuming other operations.
149pub async fn migrate_scheme_to_v2(object_store: &ObjectStore, dataset_base: &Path) -> Result<()> {
150    object_store
151        .inner
152        .list(Some(&dataset_base.child(VERSIONS_DIR)))
153        .try_filter(|res| {
154            let res = if let Some(filename) = res.location.filename() {
155                ManifestNamingScheme::detect_scheme(filename) == Some(ManifestNamingScheme::V1)
156            } else {
157                false
158            };
159            future::ready(res)
160        })
161        .try_for_each_concurrent(object_store.io_parallelism(), |meta| async move {
162            let filename = meta.location.filename().unwrap();
163            let version = ManifestNamingScheme::V1.parse_version(filename).unwrap();
164            let path = ManifestNamingScheme::V2.manifest_path(dataset_base, version);
165            object_store.inner.rename(&meta.location, &path).await?;
166            Ok(())
167        })
168        .await?;
169
170    Ok(())
171}
172
173/// Function that writes the manifest to the object store.
174///
175/// Returns the size of the written manifest.
176pub type ManifestWriter = for<'a> fn(
177    object_store: &'a ObjectStore,
178    manifest: &'a mut Manifest,
179    indices: Option<Vec<Index>>,
180    path: &'a Path,
181) -> BoxFuture<'a, Result<WriteResult>>;
182
183#[derive(Debug)]
184pub struct ManifestLocation {
185    /// The version the manifest corresponds to.
186    pub version: u64,
187    /// Path of the manifest file, relative to the table root.
188    pub path: Path,
189    /// Size, in bytes, of the manifest file. If it is not known, this field should be `None`.
190    pub size: Option<u64>,
191    /// Naming scheme of the manifest file.
192    pub naming_scheme: ManifestNamingScheme,
193    /// Optional e-tag, used for integrity checks. Manifests should be immutable, so
194    /// if we detect a change in the e-tag, it means the manifest was tampered with.
195    /// This might happen if the dataset was deleted and then re-created.
196    pub e_tag: Option<String>,
197}
198
199impl TryFrom<object_store::ObjectMeta> for ManifestLocation {
200    type Error = Error;
201
202    fn try_from(meta: object_store::ObjectMeta) -> Result<Self> {
203        let filename = meta.location.filename().ok_or_else(|| Error::Internal {
204            message: "ObjectMeta location does not have a filename".to_string(),
205            location: location!(),
206        })?;
207        let scheme =
208            ManifestNamingScheme::detect_scheme(filename).ok_or_else(|| Error::Internal {
209                message: format!("Invalid manifest filename: '{}'", filename),
210                location: location!(),
211            })?;
212        let version = scheme
213            .parse_version(filename)
214            .ok_or_else(|| Error::Internal {
215                message: format!("Invalid manifest filename: '{}'", filename),
216                location: location!(),
217            })?;
218        Ok(Self {
219            version,
220            path: meta.location,
221            size: Some(meta.size as u64),
222            naming_scheme: scheme,
223            e_tag: meta.e_tag,
224        })
225    }
226}
227
228/// Get the latest manifest path
229async fn current_manifest_path(
230    object_store: &ObjectStore,
231    base: &Path,
232) -> Result<ManifestLocation> {
233    if object_store.is_local() {
234        if let Ok(Some(location)) = current_manifest_local(base) {
235            return Ok(location);
236        }
237    }
238
239    let manifest_files = object_store.list(Some(base.child(VERSIONS_DIR)));
240
241    let mut valid_manifests = manifest_files.try_filter_map(|res| {
242        if let Some(scheme) = ManifestNamingScheme::detect_scheme(res.location.filename().unwrap())
243        {
244            future::ready(Ok(Some((scheme, res))))
245        } else {
246            future::ready(Ok(None))
247        }
248    });
249
250    let first = valid_manifests.next().await.transpose()?;
251    match (first, object_store.list_is_lexically_ordered) {
252        // If the first valid manifest we see is V2, we can assume that we are using
253        // V2 naming scheme for all manifests.
254        (Some((scheme @ ManifestNamingScheme::V2, meta)), true) => {
255            let version = scheme
256                .parse_version(meta.location.filename().unwrap())
257                .unwrap();
258
259            // Sanity check: verify at least for the first 1k files that they are all V2
260            // and that the version numbers are decreasing. We use the first 1k because
261            // this is the typical size of an object store list endpoint response page.
262            for (scheme, meta) in valid_manifests.take(999).try_collect::<Vec<_>>().await? {
263                if scheme != ManifestNamingScheme::V2 {
264                    warn!(
265                        "Found V1 Manifest in a V2 directory. Use `migrate_manifest_paths_v2` \
266                         to migrate the directory."
267                    );
268                    break;
269                }
270                let next_version = scheme
271                    .parse_version(meta.location.filename().unwrap())
272                    .unwrap();
273                if next_version >= version {
274                    warn!(
275                        "List operation was expected to be lexically ordered, but was not. This \
276                         could mean a corrupt read. Please make a bug report on the lancedb/lance \
277                         GitHub repository."
278                    );
279                    break;
280                }
281            }
282
283            Ok(ManifestLocation {
284                version,
285                path: meta.location,
286                size: Some(meta.size as u64),
287                naming_scheme: scheme,
288                e_tag: meta.e_tag,
289            })
290        }
291        // If the first valid manifest we see if V1, assume for now that we are
292        // using V1 naming scheme for all manifests. Since we are listing the
293        // directory anyways, we will assert there aren't any V2 manifests.
294        (Some((scheme, meta)), _) => {
295            let mut current_version = scheme
296                .parse_version(meta.location.filename().unwrap())
297                .unwrap();
298            let mut current_meta = meta;
299
300            while let Some((scheme, meta)) = valid_manifests.next().await.transpose()? {
301                if matches!(scheme, ManifestNamingScheme::V2) {
302                    return Err(Error::Internal {
303                        message: "Found V2 manifest in a V1 manifest directory".to_string(),
304                        location: location!(),
305                    });
306                }
307                let version = scheme
308                    .parse_version(meta.location.filename().unwrap())
309                    .unwrap();
310                if version > current_version {
311                    current_version = version;
312                    current_meta = meta;
313                }
314            }
315            Ok(ManifestLocation {
316                version: current_version,
317                path: current_meta.location,
318                size: Some(current_meta.size as u64),
319                naming_scheme: scheme,
320                e_tag: current_meta.e_tag,
321            })
322        }
323        (None, _) => Err(Error::NotFound {
324            uri: base.child(VERSIONS_DIR).to_string(),
325            location: location!(),
326        }),
327    }
328}
329
330// This is an optimized function that searches for the latest manifest. In
331// object_store, list operations lookup metadata for each file listed. This
332// method only gets the metadata for the found latest manifest.
333fn current_manifest_local(base: &Path) -> std::io::Result<Option<ManifestLocation>> {
334    let path = lance_io::local::to_local_path(&base.child(VERSIONS_DIR));
335    let entries = std::fs::read_dir(path)?;
336
337    let mut latest_entry: Option<(u64, DirEntry)> = None;
338
339    let mut scheme: Option<ManifestNamingScheme> = None;
340
341    for entry in entries {
342        let entry = entry?;
343        let filename_raw = entry.file_name();
344        let filename = filename_raw.to_string_lossy();
345
346        let Some(entry_scheme) = ManifestNamingScheme::detect_scheme(&filename) else {
347            // Need to ignore temporary files, such as
348            // .tmp_7.manifest_9c100374-3298-4537-afc6-f5ee7913666d
349            continue;
350        };
351
352        if let Some(scheme) = scheme {
353            if scheme != entry_scheme {
354                return Err(io::Error::new(
355                    io::ErrorKind::InvalidData,
356                    format!(
357                        "Found multiple manifest naming schemes in the same directory: {:?} and {:?}",
358                        scheme, entry_scheme
359                    ),
360                ));
361            }
362        } else {
363            scheme = Some(entry_scheme);
364        }
365
366        let Some(version) = entry_scheme.parse_version(&filename) else {
367            continue;
368        };
369
370        if let Some((latest_version, _)) = &latest_entry {
371            if version > *latest_version {
372                latest_entry = Some((version, entry));
373            }
374        } else {
375            latest_entry = Some((version, entry));
376        }
377    }
378
379    if let Some((version, entry)) = latest_entry {
380        let path = Path::from_filesystem_path(entry.path())
381            .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err.to_string()))?;
382        let metadata = entry.metadata()?;
383        Ok(Some(ManifestLocation {
384            version,
385            path,
386            size: Some(metadata.len()),
387            naming_scheme: scheme.unwrap(),
388            e_tag: Some(get_etag(&metadata)),
389        }))
390    } else {
391        Ok(None)
392    }
393}
394
395// Based on object store's implementation.
396fn get_etag(metadata: &std::fs::Metadata) -> String {
397    let inode = get_inode(metadata);
398    let size = metadata.len();
399    let mtime = metadata
400        .modified()
401        .ok()
402        .and_then(|mtime| mtime.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
403        .unwrap_or_default()
404        .as_micros();
405
406    // Use an ETag scheme based on that used by many popular HTTP servers
407    // <https://httpd.apache.org/docs/2.2/mod/core.html#fileetag>
408    // <https://stackoverflow.com/questions/47512043/how-etags-are-generated-and-configured>
409    format!("{inode:x}-{mtime:x}-{size:x}")
410}
411
412#[cfg(unix)]
413/// We include the inode when available to yield an ETag more resistant to collisions
414/// and as used by popular web servers such as [Apache](https://httpd.apache.org/docs/2.2/mod/core.html#fileetag)
415fn get_inode(metadata: &std::fs::Metadata) -> u64 {
416    std::os::unix::fs::MetadataExt::ino(metadata)
417}
418
419#[cfg(not(unix))]
420/// On platforms where an inode isn't available, fallback to just relying on size and mtime
421fn get_inode(_metadata: &std::fs::Metadata) -> u64 {
422    0
423}
424
425async fn list_manifests<'a>(
426    base_path: &Path,
427    object_store: &'a dyn OSObjectStore,
428) -> Result<BoxStream<'a, Result<ManifestLocation>>> {
429    Ok(object_store
430        .read_dir_all(&base_path.child(VERSIONS_DIR), None)
431        .await?
432        .filter_map(|obj_meta| {
433            futures::future::ready(
434                obj_meta
435                    .map(|m| ManifestLocation::try_from(m).ok())
436                    .transpose(),
437            )
438        })
439        .boxed())
440}
441
442fn make_staging_manifest_path(base: &Path) -> Result<Path> {
443    let id = uuid::Uuid::new_v4().to_string();
444    Path::parse(format!("{base}-{id}")).map_err(|e| Error::IO {
445        source: Box::new(e),
446        location: location!(),
447    })
448}
449
450#[cfg(feature = "dynamodb")]
451const DDB_URL_QUERY_KEY: &str = "ddbTableName";
452
453/// Handle commits that prevent conflicting writes.
454///
455/// Commit implementations ensure that if there are multiple concurrent writers
456/// attempting to write the next version of a table, only one will win. In order
457/// to work, all writers must use the same commit handler type.
458/// This trait is also responsible for resolving where the manifests live.
459///
460// TODO: pub(crate)
461#[async_trait::async_trait]
462pub trait CommitHandler: Debug + Send + Sync {
463    async fn resolve_latest_location(
464        &self,
465        base_path: &Path,
466        object_store: &ObjectStore,
467    ) -> Result<ManifestLocation> {
468        Ok(current_manifest_path(object_store, base_path).await?)
469    }
470
471    async fn resolve_version_location(
472        &self,
473        base_path: &Path,
474        version: u64,
475        object_store: &dyn OSObjectStore,
476    ) -> Result<ManifestLocation> {
477        default_resolve_version(base_path, version, object_store).await
478    }
479
480    async fn list_manifest_locations<'a>(
481        &self,
482        base_path: &Path,
483        object_store: &'a dyn OSObjectStore,
484    ) -> Result<BoxStream<'a, Result<ManifestLocation>>> {
485        list_manifests(base_path, object_store).await
486    }
487
488    /// Commit a manifest.
489    ///
490    /// This function should return an [CommitError::CommitConflict] if another
491    /// transaction has already been committed to the path.
492    async fn commit(
493        &self,
494        manifest: &mut Manifest,
495        indices: Option<Vec<Index>>,
496        base_path: &Path,
497        object_store: &ObjectStore,
498        manifest_writer: ManifestWriter,
499        naming_scheme: ManifestNamingScheme,
500    ) -> std::result::Result<ManifestLocation, CommitError>;
501
502    /// Delete the recorded manifest information for a dataset at the base_path
503    async fn delete(&self, _base_path: &Path) -> Result<()> {
504        Ok(())
505    }
506}
507
508async fn default_resolve_version(
509    base_path: &Path,
510    version: u64,
511    object_store: &dyn OSObjectStore,
512) -> Result<ManifestLocation> {
513    if is_detached_version(version) {
514        return Ok(ManifestLocation {
515            version,
516            // Detached versions are not supported with V1 naming scheme.  If we need
517            // to support in the future we could use a different prefix (e.g. 'x' or something)
518            naming_scheme: ManifestNamingScheme::V2,
519            // Both V1 and V2 should give the same path for detached versions
520            path: ManifestNamingScheme::V2.manifest_path(base_path, version),
521            size: None,
522            e_tag: None,
523        });
524    }
525
526    // try V2, fallback to V1.
527    let scheme = ManifestNamingScheme::V2;
528    let path = scheme.manifest_path(base_path, version);
529    match object_store.head(&path).await {
530        Ok(meta) => Ok(ManifestLocation {
531            version,
532            path,
533            size: Some(meta.size as u64),
534            naming_scheme: scheme,
535            e_tag: meta.e_tag,
536        }),
537        Err(ObjectStoreError::NotFound { .. }) => {
538            // fallback to V1
539            let scheme = ManifestNamingScheme::V1;
540            Ok(ManifestLocation {
541                version,
542                path: scheme.manifest_path(base_path, version),
543                size: None,
544                naming_scheme: scheme,
545                e_tag: None,
546            })
547        }
548        Err(e) => Err(e.into()),
549    }
550}
551/// Adapt an object_store credentials into AWS SDK creds
552#[cfg(feature = "dynamodb")]
553#[derive(Debug)]
554struct OSObjectStoreToAwsCredAdaptor(AwsCredentialProvider);
555
556#[cfg(feature = "dynamodb")]
557impl ProvideCredentials for OSObjectStoreToAwsCredAdaptor {
558    fn provide_credentials<'a>(
559        &'a self,
560    ) -> aws_credential_types::provider::future::ProvideCredentials<'a>
561    where
562        Self: 'a,
563    {
564        aws_credential_types::provider::future::ProvideCredentials::new(async {
565            let creds = self
566                .0
567                .get_credential()
568                .await
569                .map_err(|e| CredentialsError::provider_error(Box::new(e)))?;
570            Ok(aws_credential_types::Credentials::new(
571                &creds.key_id,
572                &creds.secret_key,
573                creds.token.clone(),
574                Some(
575                    SystemTime::now()
576                        .checked_add(Duration::from_secs(
577                            60 * 10, //  10 min
578                        ))
579                        .expect("overflow"),
580                ),
581                "",
582            ))
583        })
584    }
585}
586
587#[cfg(feature = "dynamodb")]
588async fn build_dynamodb_external_store(
589    table_name: &str,
590    creds: AwsCredentialProvider,
591    region: &str,
592    endpoint: Option<String>,
593    app_name: &str,
594) -> Result<Arc<dyn ExternalManifestStore>> {
595    use super::commit::dynamodb::DynamoDBExternalManifestStore;
596    use aws_sdk_dynamodb::{
597        config::{IdentityCache, Region},
598        Client,
599    };
600
601    let mut dynamodb_config = aws_sdk_dynamodb::config::Builder::new()
602        .behavior_version_latest()
603        .region(Some(Region::new(region.to_string())))
604        .credentials_provider(OSObjectStoreToAwsCredAdaptor(creds))
605        // caching should be handled by passed AwsCredentialProvider
606        .identity_cache(IdentityCache::no_cache());
607
608    if let Some(endpoint) = endpoint {
609        dynamodb_config = dynamodb_config.endpoint_url(endpoint);
610    }
611    let client = Client::from_conf(dynamodb_config.build());
612
613    DynamoDBExternalManifestStore::new_external_store(client.into(), table_name, app_name).await
614}
615
616pub async fn commit_handler_from_url(
617    url_or_path: &str,
618    // This looks unused if dynamodb feature disabled
619    #[allow(unused_variables)] options: &Option<ObjectStoreParams>,
620) -> Result<Arc<dyn CommitHandler>> {
621    let url = match Url::parse(url_or_path) {
622        Ok(url) if url.scheme().len() == 1 && cfg!(windows) => {
623            // On Windows, the drive is parsed as a scheme
624            return Ok(Arc::new(RenameCommitHandler));
625        }
626        Ok(url) => url,
627        Err(_) => {
628            return Ok(Arc::new(RenameCommitHandler));
629        }
630    };
631
632    match url.scheme() {
633        "s3" | "gs" | "az" | "memory" | "file" | "file-object-store" => {
634            Ok(Arc::new(ConditionalPutCommitHandler))
635        }
636        #[cfg(not(feature = "dynamodb"))]
637        "s3+ddb" => Err(Error::InvalidInput {
638            source: "`s3+ddb://` scheme requires `dynamodb` feature to be enabled".into(),
639            location: location!(),
640        }),
641        #[cfg(feature = "dynamodb")]
642        "s3+ddb" => {
643            if url.query_pairs().count() != 1 {
644                return Err(Error::InvalidInput {
645                    source: "`s3+ddb://` scheme and expects exactly one query `ddbTableName`"
646                        .into(),
647                    location: location!(),
648                });
649            }
650            let table_name = match url.query_pairs().next() {
651                Some((Cow::Borrowed(key), Cow::Borrowed(table_name)))
652                    if key == DDB_URL_QUERY_KEY =>
653                {
654                    if table_name.is_empty() {
655                        return Err(Error::InvalidInput {
656                            source: "`s3+ddb://` scheme requires non empty dynamodb table name"
657                                .into(),
658                            location: location!(),
659                        });
660                    }
661                    table_name
662                }
663                _ => {
664                    return Err(Error::InvalidInput {
665                        source: "`s3+ddb://` scheme and expects exactly one query `ddbTableName`"
666                            .into(),
667                        location: location!(),
668                    });
669                }
670            };
671            let options = options.clone().unwrap_or_default();
672            let storage_options = StorageOptions(options.storage_options.unwrap_or_default());
673            let dynamo_endpoint = get_dynamodb_endpoint(&storage_options);
674            let storage_options = storage_options.as_s3_options();
675
676            let region = storage_options
677                .get(&AmazonS3ConfigKey::Region)
678                .map(|s| s.to_string());
679
680            let (aws_creds, region) = build_aws_credential(
681                options.s3_credentials_refresh_offset,
682                options.aws_credentials.clone(),
683                Some(&storage_options),
684                region,
685            )
686            .await?;
687
688            Ok(Arc::new(ExternalManifestCommitHandler {
689                external_manifest_store: build_dynamodb_external_store(
690                    table_name,
691                    aws_creds.clone(),
692                    &region,
693                    dynamo_endpoint,
694                    "lancedb",
695                )
696                .await?,
697            }))
698        }
699        _ => Ok(Arc::new(UnsafeCommitHandler)),
700    }
701}
702
703#[cfg(feature = "dynamodb")]
704fn get_dynamodb_endpoint(storage_options: &StorageOptions) -> Option<String> {
705    if let Some(endpoint) = storage_options.0.get("dynamodb_endpoint") {
706        Some(endpoint.to_string())
707    } else {
708        std::env::var("DYNAMODB_ENDPOINT").ok()
709    }
710}
711
712/// Errors that can occur when committing a manifest.
713#[derive(Debug)]
714pub enum CommitError {
715    /// Another transaction has already been written to the path
716    CommitConflict,
717    /// Something else went wrong
718    OtherError(Error),
719}
720
721impl From<Error> for CommitError {
722    fn from(e: Error) -> Self {
723        Self::OtherError(e)
724    }
725}
726
727impl From<CommitError> for Error {
728    fn from(e: CommitError) -> Self {
729        match e {
730            CommitError::CommitConflict => Self::Internal {
731                message: "Commit conflict".to_string(),
732                location: location!(),
733            },
734            CommitError::OtherError(e) => e,
735        }
736    }
737}
738
739/// Whether we have issued a warning about using the unsafe commit handler.
740static WARNED_ON_UNSAFE_COMMIT: AtomicBool = AtomicBool::new(false);
741
742/// A naive commit implementation that does not prevent conflicting writes.
743///
744/// This will log a warning the first time it is used.
745pub struct UnsafeCommitHandler;
746
747#[async_trait::async_trait]
748impl CommitHandler for UnsafeCommitHandler {
749    async fn commit(
750        &self,
751        manifest: &mut Manifest,
752        indices: Option<Vec<Index>>,
753        base_path: &Path,
754        object_store: &ObjectStore,
755        manifest_writer: ManifestWriter,
756        naming_scheme: ManifestNamingScheme,
757    ) -> std::result::Result<ManifestLocation, CommitError> {
758        // Log a one-time warning
759        if !WARNED_ON_UNSAFE_COMMIT.load(std::sync::atomic::Ordering::Relaxed) {
760            WARNED_ON_UNSAFE_COMMIT.store(true, std::sync::atomic::Ordering::Relaxed);
761            log::warn!(
762                "Using unsafe commit handler. Concurrent writes may result in data loss. \
763                 Consider providing a commit handler that prevents conflicting writes."
764            );
765        }
766
767        let version_path = naming_scheme.manifest_path(base_path, manifest.version);
768        // Write the manifest naively
769        let res = manifest_writer(object_store, manifest, indices, &version_path).await?;
770
771        Ok(ManifestLocation {
772            version: manifest.version,
773            size: Some(res.size as u64),
774            naming_scheme,
775            path: version_path,
776            e_tag: res.e_tag,
777        })
778    }
779}
780
781impl Debug for UnsafeCommitHandler {
782    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
783        f.debug_struct("UnsafeCommitHandler").finish()
784    }
785}
786
787/// A commit implementation that uses a lock to prevent conflicting writes.
788#[async_trait::async_trait]
789pub trait CommitLock: Debug {
790    type Lease: CommitLease;
791
792    /// Attempt to lock the table for the given version.
793    ///
794    /// If it is already locked by another transaction, wait until it is unlocked.
795    /// Once it is unlocked, return [CommitError::CommitConflict] if the version
796    /// has already been committed. Otherwise, return the lock.
797    ///
798    /// To prevent poisoned locks, it's recommended to set a timeout on the lock
799    /// of at least 30 seconds.
800    ///
801    /// It is not required that the lock tracks the version. It is provided in
802    /// case the locking is handled by a catalog service that needs to know the
803    /// current version of the table.
804    async fn lock(&self, version: u64) -> std::result::Result<Self::Lease, CommitError>;
805}
806
807#[async_trait::async_trait]
808pub trait CommitLease: Send + Sync {
809    /// Return the lease, indicating whether the commit was successful.
810    async fn release(&self, success: bool) -> std::result::Result<(), CommitError>;
811}
812
813#[async_trait::async_trait]
814impl<T: CommitLock + Send + Sync> CommitHandler for T {
815    async fn commit(
816        &self,
817        manifest: &mut Manifest,
818        indices: Option<Vec<Index>>,
819        base_path: &Path,
820        object_store: &ObjectStore,
821        manifest_writer: ManifestWriter,
822        naming_scheme: ManifestNamingScheme,
823    ) -> std::result::Result<ManifestLocation, CommitError> {
824        let path = naming_scheme.manifest_path(base_path, manifest.version);
825        // NOTE: once we have the lease we cannot use ? to return errors, since
826        // we must release the lease before returning.
827        let lease = self.lock(manifest.version).await?;
828
829        // Head the location and make sure it's not already committed
830        match object_store.inner.head(&path).await {
831            Ok(_) => {
832                // The path already exists, so it's already committed
833                // Release the lock
834                lease.release(false).await?;
835
836                return Err(CommitError::CommitConflict);
837            }
838            Err(ObjectStoreError::NotFound { .. }) => {}
839            Err(e) => {
840                // Something else went wrong
841                // Release the lock
842                lease.release(false).await?;
843
844                return Err(CommitError::OtherError(e.into()));
845            }
846        }
847        let res = manifest_writer(object_store, manifest, indices, &path).await;
848
849        // Release the lock
850        lease.release(res.is_ok()).await?;
851
852        let res = res?;
853        Ok(ManifestLocation {
854            version: manifest.version,
855            size: Some(res.size as u64),
856            naming_scheme,
857            path,
858            e_tag: res.e_tag,
859        })
860    }
861}
862
863#[async_trait::async_trait]
864impl<T: CommitLock + Send + Sync> CommitHandler for Arc<T> {
865    async fn commit(
866        &self,
867        manifest: &mut Manifest,
868        indices: Option<Vec<Index>>,
869        base_path: &Path,
870        object_store: &ObjectStore,
871        manifest_writer: ManifestWriter,
872        naming_scheme: ManifestNamingScheme,
873    ) -> std::result::Result<ManifestLocation, CommitError> {
874        self.as_ref()
875            .commit(
876                manifest,
877                indices,
878                base_path,
879                object_store,
880                manifest_writer,
881                naming_scheme,
882            )
883            .await
884    }
885}
886
887/// A commit implementation that uses a temporary path and renames the object.
888///
889/// This only works for object stores that support atomic rename if not exist.
890pub struct RenameCommitHandler;
891
892#[async_trait::async_trait]
893impl CommitHandler for RenameCommitHandler {
894    async fn commit(
895        &self,
896        manifest: &mut Manifest,
897        indices: Option<Vec<Index>>,
898        base_path: &Path,
899        object_store: &ObjectStore,
900        manifest_writer: ManifestWriter,
901        naming_scheme: ManifestNamingScheme,
902    ) -> std::result::Result<ManifestLocation, CommitError> {
903        // Create a temporary object, then use `rename_if_not_exists` to commit.
904        // If failed, clean up the temporary object.
905
906        let path = naming_scheme.manifest_path(base_path, manifest.version);
907        let tmp_path = make_staging_manifest_path(&path)?;
908
909        // Write the manifest to the temporary path
910        let res = manifest_writer(object_store, manifest, indices, &tmp_path).await?;
911
912        match object_store
913            .inner
914            .rename_if_not_exists(&tmp_path, &path)
915            .await
916        {
917            Ok(_) => {
918                // Successfully committed
919                Ok(ManifestLocation {
920                    version: manifest.version,
921                    path,
922                    size: Some(res.size as u64),
923                    naming_scheme,
924                    e_tag: None, // Re-name can change e-tag.
925                })
926            }
927            Err(ObjectStoreError::AlreadyExists { .. }) => {
928                // Another transaction has already been committed
929                // Attempt to clean up temporary object, but ignore errors if we can't
930                let _ = object_store.delete(&tmp_path).await;
931
932                return Err(CommitError::CommitConflict);
933            }
934            Err(e) => {
935                // Something else went wrong
936                return Err(CommitError::OtherError(e.into()));
937            }
938        }
939    }
940}
941
942impl Debug for RenameCommitHandler {
943    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
944        f.debug_struct("RenameCommitHandler").finish()
945    }
946}
947
948pub struct ConditionalPutCommitHandler;
949
950#[async_trait::async_trait]
951impl CommitHandler for ConditionalPutCommitHandler {
952    async fn commit(
953        &self,
954        manifest: &mut Manifest,
955        indices: Option<Vec<Index>>,
956        base_path: &Path,
957        object_store: &ObjectStore,
958        manifest_writer: ManifestWriter,
959        naming_scheme: ManifestNamingScheme,
960    ) -> std::result::Result<ManifestLocation, CommitError> {
961        let path = naming_scheme.manifest_path(base_path, manifest.version);
962
963        let memory_store = ObjectStore::memory();
964        let dummy_path = "dummy";
965        manifest_writer(&memory_store, manifest, indices, &dummy_path.into()).await?;
966        let dummy_data = memory_store.read_one_all(&dummy_path.into()).await?;
967        let size = dummy_data.len() as u64;
968        let res = object_store
969            .inner
970            .put_opts(
971                &path,
972                dummy_data.into(),
973                PutOptions {
974                    mode: object_store::PutMode::Create,
975                    ..Default::default()
976                },
977            )
978            .await
979            .map_err(|err| match err {
980                ObjectStoreError::AlreadyExists { .. } | ObjectStoreError::Precondition { .. } => {
981                    CommitError::CommitConflict
982                }
983                _ => CommitError::OtherError(err.into()),
984            })?;
985
986        Ok(ManifestLocation {
987            version: manifest.version,
988            path,
989            size: Some(size),
990            naming_scheme,
991            e_tag: res.e_tag,
992        })
993    }
994}
995
996impl Debug for ConditionalPutCommitHandler {
997    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
998        f.debug_struct("ConditionalPutCommitHandler").finish()
999    }
1000}
1001
1002#[derive(Debug, Clone)]
1003pub struct CommitConfig {
1004    pub num_retries: u32,
1005    // TODO: add isolation_level
1006}
1007
1008impl Default for CommitConfig {
1009    fn default() -> Self {
1010        Self { num_retries: 20 }
1011    }
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017
1018    #[test]
1019    fn test_manifest_naming_scheme() {
1020        let v1 = ManifestNamingScheme::V1;
1021        let v2 = ManifestNamingScheme::V2;
1022
1023        assert_eq!(
1024            v1.manifest_path(&Path::from("base"), 0),
1025            Path::from("base/_versions/0.manifest")
1026        );
1027        assert_eq!(
1028            v1.manifest_path(&Path::from("base"), 42),
1029            Path::from("base/_versions/42.manifest")
1030        );
1031
1032        assert_eq!(
1033            v2.manifest_path(&Path::from("base"), 0),
1034            Path::from("base/_versions/18446744073709551615.manifest")
1035        );
1036        assert_eq!(
1037            v2.manifest_path(&Path::from("base"), 42),
1038            Path::from("base/_versions/18446744073709551573.manifest")
1039        );
1040
1041        assert_eq!(v1.parse_version("0.manifest"), Some(0));
1042        assert_eq!(v1.parse_version("42.manifest"), Some(42));
1043        assert_eq!(
1044            v1.parse_version("42.manifest-cee4fbbb-eb19-4ea3-8ca7-54f5ec33dedc"),
1045            Some(42)
1046        );
1047
1048        assert_eq!(v2.parse_version("18446744073709551615.manifest"), Some(0));
1049        assert_eq!(v2.parse_version("18446744073709551573.manifest"), Some(42));
1050        assert_eq!(
1051            v2.parse_version("18446744073709551573.manifest-cee4fbbb-eb19-4ea3-8ca7-54f5ec33dedc"),
1052            Some(42)
1053        );
1054
1055        assert_eq!(ManifestNamingScheme::detect_scheme("0.manifest"), Some(v1));
1056        assert_eq!(
1057            ManifestNamingScheme::detect_scheme("18446744073709551615.manifest"),
1058            Some(v2)
1059        );
1060        assert_eq!(ManifestNamingScheme::detect_scheme("something else"), None);
1061    }
1062
1063    #[tokio::test]
1064    async fn test_manifest_naming_migration() {
1065        let object_store = ObjectStore::memory();
1066        let base = Path::from("base");
1067        let versions_dir = base.child(VERSIONS_DIR);
1068
1069        // Write two v1 files and one v1
1070        let original_files = vec![
1071            versions_dir.child("irrelevant"),
1072            ManifestNamingScheme::V1.manifest_path(&base, 0),
1073            ManifestNamingScheme::V2.manifest_path(&base, 1),
1074        ];
1075        for path in original_files {
1076            object_store.put(&path, b"".as_slice()).await.unwrap();
1077        }
1078
1079        migrate_scheme_to_v2(&object_store, &base).await.unwrap();
1080
1081        let expected_files = vec![
1082            ManifestNamingScheme::V2.manifest_path(&base, 1),
1083            ManifestNamingScheme::V2.manifest_path(&base, 0),
1084            versions_dir.child("irrelevant"),
1085        ];
1086        let actual_files = object_store
1087            .inner
1088            .list(Some(&versions_dir))
1089            .map_ok(|res| res.location)
1090            .try_collect::<Vec<_>>()
1091            .await
1092            .unwrap();
1093        assert_eq!(actual_files, expected_files);
1094    }
1095}