Repository navigation
Expand file tree
/
Copy pathobject_store.rs
More file actions
3291 lines (2980 loc) · 121 KB
/
Copy pathobject_store.rs
File metadata and controls
3291 lines (2980 loc) · 121 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
//! Extend [object_store::ObjectStore] functionalities
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use ::tracing::{Span, field::Empty, instrument};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures::{FutureExt, Stream};
use futures::{StreamExt, TryStreamExt, future, stream::BoxStream};
use lance_core::deepsize::DeepSizeOf;
use lance_core::error::LanceOptionExt;
use lance_core::utils::parse::{parse_env_as_bool, str_is_truthy};
use list_retry::ListRetryStream;
use object_store::DynObjectStore;
use object_store::ObjectStoreExt as OSObjectStoreExt;
#[cfg(feature = "aws")]
use object_store::aws::AwsCredentialProvider;
use object_store::list::PaginatedListStore;
#[cfg(any(feature = "aws", feature = "azure", feature = "gcp"))]
use object_store::{ClientOptions, HeaderMap, HeaderValue};
use object_store::{
ListResult, ObjectMeta, ObjectStore as OSObjectStore, PutMode, PutOptions, PutPayload,
path::Path,
};
use providers::local::FileStoreProvider;
use providers::memory::MemoryStoreProvider;
use tokio::io::AsyncWriteExt;
use url::Url;
use super::local::LocalObjectReader;
#[cfg(target_os = "linux")]
use crate::uring::{UringCurrentThreadReader, UringReader};
#[cfg(any(feature = "aws", feature = "azure", feature = "gcp"))]
pub(crate) mod dynamic_credentials;
#[cfg(any(feature = "oss", feature = "huggingface", feature = "tos"))]
pub(crate) mod dynamic_opendal;
mod list_retry;
#[cfg(feature = "metrics")]
pub mod metrics;
#[cfg(any(
feature = "aws",
feature = "gcp",
feature = "azure",
feature = "oss",
feature = "tencent",
feature = "huggingface",
feature = "tos",
feature = "goosefs",
))]
pub(crate) mod opendal_store;
pub mod providers;
pub(crate) mod read_dir;
pub mod storage_options;
#[cfg(test)]
pub(crate) mod test_utils;
pub mod throttle;
mod tracing;
use crate::object_reader::SmallReader;
use crate::object_writer::{LocalWriter, WriteResult};
use crate::traits::{WriteExt, Writer};
use crate::utils::tracking_store::{IOTracker, IoStats};
use crate::{object_reader::CloudObjectReader, object_writer::ObjectWriter, traits::Reader};
use lance_core::{Error, Result};
// Local disks tend to do fine with a few threads
// Note: the number of threads here also impacts the number of files
// we need to read in some situations. So keeping this at 8 keeps the
// RAM on our scanner down.
pub const DEFAULT_LOCAL_IO_PARALLELISM: usize = 8;
// Cloud disks often need many many threads to saturate the network
pub const DEFAULT_CLOUD_IO_PARALLELISM: usize = 64;
const SERVER_SIDE_COPY_ENABLED_ENV: &str = "LANCE_IO_SERVER_SIDE_COPY_ENABLED";
const DEFAULT_LOCAL_BLOCK_SIZE: usize = 4 * 1024; // 4KB block size
#[cfg(any(
feature = "aws",
feature = "gcp",
feature = "azure",
feature = "oss",
feature = "tencent",
feature = "huggingface",
feature = "tos",
feature = "goosefs",
))]
const DEFAULT_CLOUD_BLOCK_SIZE: usize = 64 * 1024; // 64KB block size
pub static DEFAULT_MAX_IOP_SIZE: std::sync::LazyLock<u64> = std::sync::LazyLock::new(|| {
std::env::var("LANCE_MAX_IOP_SIZE")
.map(|val| val.parse().unwrap())
.unwrap_or(16 * 1024 * 1024)
});
pub const DEFAULT_DOWNLOAD_RETRY_COUNT: usize = 3;
#[derive(Debug)]
struct StreamCopyError {
stage: &'static str,
source_path: String,
destination_path: String,
source: Box<dyn std::error::Error + Send + Sync>,
}
impl std::fmt::Display for StreamCopyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"multipart_stream_copy failed during {} from {} to {}: {}",
self.stage, self.source_path, self.destination_path, self.source
)
}
}
impl std::error::Error for StreamCopyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(self.source.as_ref())
}
}
fn stream_copy_error(
stage: &'static str,
source_path: &Path,
destination_path: &Path,
source: impl std::error::Error + Send + Sync + 'static,
) -> Error {
Error::io_source(Box::new(StreamCopyError {
stage,
source_path: source_path.to_string(),
destination_path: destination_path.to_string(),
source: Box::new(source),
}))
}
pub use providers::{ObjectStoreProvider, ObjectStoreRegistry};
pub use read_dir::ReadDirOptions;
pub use storage_options::{
BASE_SCOPED_OPTION_PREFIX, BaseScopedStorageOptionsProvider, EXPIRES_AT_MILLIS_KEY,
LanceNamespaceStorageOptionsProvider, REFRESH_OFFSET_MILLIS_KEY, StorageOptionsAccessor,
StorageOptionsProvider, has_base_scoped_options, parse_base_scoped_key,
resolve_base_scoped_options,
};
#[async_trait]
pub trait ObjectStoreExt {
/// Returns true if the file exists.
async fn exists(&self, path: &Path) -> Result<bool>;
/// Read all files (start from base directory) recursively
///
/// unmodified_since can be specified to only return files that have not been modified since the given time.
fn read_dir_all<'a, 'b>(
&'a self,
dir_path: impl Into<&'b Path> + Send,
unmodified_since: Option<DateTime<Utc>>,
) -> BoxStream<'a, Result<ObjectMeta>>;
}
#[async_trait]
pub(super) trait LocalDirOperations: std::fmt::Debug + Send + Sync {
async fn remove_dir_all(&self, path: &Path) -> Result<()>;
}
#[async_trait]
impl<O: OSObjectStore + ?Sized> ObjectStoreExt for O {
fn read_dir_all<'a, 'b>(
&'a self,
dir_path: impl Into<&'b Path> + Send,
unmodified_since: Option<DateTime<Utc>>,
) -> BoxStream<'a, Result<ObjectMeta>> {
let output = self.list(Some(dir_path.into())).map_err(|e| e.into());
if let Some(unmodified_since_val) = unmodified_since {
output
.try_filter(move |file| future::ready(file.last_modified <= unmodified_since_val))
.boxed()
} else {
output.boxed()
}
}
async fn exists(&self, path: &Path) -> Result<bool> {
match self.head(path).await {
Ok(_) => Ok(true),
Err(object_store::Error::NotFound { path: _, source: _ }) => Ok(false),
Err(e) => Err(e.into()),
}
}
}
/// Wraps [ObjectStore](object_store::ObjectStore)
#[derive(Clone)]
pub struct ObjectStore {
// Inner object store
pub inner: Arc<dyn OSObjectStore>,
// Provider-owned native directory operations for rooted local stores.
local_dir_operations: Option<Arc<dyn LocalDirOperations>>,
scheme: String,
block_size: usize,
max_iop_size: u64,
/// Whether to use constant size upload parts for multipart uploads. This
/// is only necessary for Cloudflare R2.
pub use_constant_size_upload_parts: bool,
/// Whether we can assume that the list of files is lexically ordered. This
/// is true for object stores, but not for local filesystems.
pub list_is_lexically_ordered: bool,
io_parallelism: usize,
/// Number of times to retry a failed download
download_retry_count: usize,
/// IO tracker for monitoring read/write operations
io_tracker: IOTracker,
/// The datastore prefix that uniquely identifies this object store. It encodes information
/// which usually cannot be found in the URL such as Azure account name. The prefix plus the
/// path uniquely identifies any object inside the store.
pub store_prefix: String,
/// The backend's paginated listing API, when it has one. `None` means
/// [`Self::read_dir_page`] has to list a directory in full to page through it.
pub(crate) paginated_lister: Option<Arc<dyn PaginatedListStore>>,
}
// Hand-written because `PaginatedListStore` is not `Debug`.
impl std::fmt::Debug for ObjectStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ObjectStore")
.field("inner", &self.inner)
.field("scheme", &self.scheme)
.field("block_size", &self.block_size)
.field("max_iop_size", &self.max_iop_size)
.field(
"use_constant_size_upload_parts",
&self.use_constant_size_upload_parts,
)
.field("list_is_lexically_ordered", &self.list_is_lexically_ordered)
.field("io_parallelism", &self.io_parallelism)
.field("download_retry_count", &self.download_retry_count)
.field("io_tracker", &self.io_tracker)
.field("store_prefix", &self.store_prefix)
.field("paginated_lister", &self.paginated_lister.is_some())
.finish()
}
}
impl DeepSizeOf for ObjectStore {
fn deep_size_of_children(&self, context: &mut lance_core::deepsize::Context) -> usize {
// We aren't counting `inner` here which is problematic but an ObjectStore
// shouldn't be too big. The only exception might be the write cache but, if
// the writer cache has data, it means we're using it somewhere else that isn't
// a cache and so that doesn't really count.
self.scheme.deep_size_of_children(context) + self.block_size.deep_size_of_children(context)
}
}
impl std::fmt::Display for ObjectStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ObjectStore({})", self.scheme)
}
}
pub trait WrappingObjectStore: std::fmt::Debug + Send + Sync {
/// Wrap an object store with additional functionality
///
/// The store_prefix is a string which uniquely identifies the object
/// store being wrapped.
fn wrap(&self, store_prefix: &str, original: Arc<dyn OSObjectStore>) -> Arc<dyn OSObjectStore>;
/// Wrap the paginated listing API that goes with the store, if it has one.
///
/// [`ObjectStore::read_dir_page`] pushes the page size and the resume position into
/// [`PaginatedListStore`], which is a separate trait from [`OSObjectStore`] and so cannot
/// be reached through the store [`Self::wrap`] returns. A listing that is pushed down
/// therefore does not pass through [`Self::wrap`], and this is where a wrapper says what
/// should happen instead:
///
/// - `Some(lister)` keeps the pushdown, wrapping the lister or handing back the one
/// given. Right for a wrapper that observes rather than intercepts — metering, caching,
/// mirroring writes.
/// - `None` gives up the pushdown, so listings go through [`Self::wrap`] as a full
/// directory read. Right for a wrapper that hides, rewrites or fails paths, which a
/// pushed-down listing would otherwise walk straight past.
///
/// A wrapper that keeps the pushdown must leave the listing itself alone: setting
/// [`offset`](object_store::list::PaginatedListOptions::offset) or changing the delimiter
/// breaks paging, since `read_dir_page` reads one directory level and resumes by the token
/// it got back.
///
/// There is deliberately no default: getting this wrong is either a silent loss of speed
/// or a silent loss of the wrapper, and neither announces itself.
fn wrap_paginated(
&self,
store_prefix: &str,
original: Arc<dyn PaginatedListStore>,
) -> Option<Arc<dyn PaginatedListStore>>;
}
#[derive(Debug, Clone)]
pub struct ChainedWrappingObjectStore {
wrappers: Vec<Arc<dyn WrappingObjectStore>>,
}
impl ChainedWrappingObjectStore {
pub fn new(wrappers: Vec<Arc<dyn WrappingObjectStore>>) -> Self {
Self { wrappers }
}
pub fn add_wrapper(&mut self, wrapper: Arc<dyn WrappingObjectStore>) {
self.wrappers.push(wrapper);
}
}
impl WrappingObjectStore for ChainedWrappingObjectStore {
fn wrap(&self, store_prefix: &str, original: Arc<dyn OSObjectStore>) -> Arc<dyn OSObjectStore> {
self.wrappers
.iter()
.fold(original, |acc, wrapper| wrapper.wrap(store_prefix, acc))
}
// One wrapper giving up the pushdown gives it up for the chain: the listing has to go
// through `wrap`, which is every wrapper in the chain at once.
fn wrap_paginated(
&self,
store_prefix: &str,
original: Arc<dyn PaginatedListStore>,
) -> Option<Arc<dyn PaginatedListStore>> {
self.wrappers.iter().try_fold(original, |acc, wrapper| {
wrapper.wrap_paginated(store_prefix, acc)
})
}
}
/// Parameters to create an [ObjectStore]
///
#[derive(Debug, Clone)]
pub struct ObjectStoreParams {
pub block_size: Option<usize>,
#[deprecated(note = "Implement an ObjectStoreProvider instead")]
pub object_store: Option<(Arc<DynObjectStore>, Url)>,
/// Refresh offset for AWS credentials when using the legacy AWS credentials path.
/// For StorageOptionsAccessor, use `refresh_offset_millis` storage option instead.
pub s3_credentials_refresh_offset: Duration,
#[cfg(feature = "aws")]
pub aws_credentials: Option<AwsCredentialProvider>,
pub object_store_wrapper: Option<Arc<dyn WrappingObjectStore>>,
/// Unified storage options accessor with caching and automatic refresh
///
/// Provides storage options and optionally a dynamic provider for automatic
/// credential refresh. Use `StorageOptionsAccessor::with_static_options()` for static
/// options or `StorageOptionsAccessor::with_initial_and_provider()` for dynamic refresh.
pub storage_options_accessor: Option<Arc<StorageOptionsAccessor>>,
/// Use constant size upload parts for multipart uploads. Only necessary
/// for Cloudflare R2, which doesn't support variable size parts. When this
/// is false, max upload size is 2.5TB. When this is true, the max size is
/// 50GB.
pub use_constant_size_upload_parts: bool,
pub list_is_lexically_ordered: Option<bool>,
}
impl Default for ObjectStoreParams {
fn default() -> Self {
#[allow(deprecated)]
Self {
object_store: None,
block_size: None,
s3_credentials_refresh_offset: Duration::from_secs(60),
#[cfg(feature = "aws")]
aws_credentials: None,
object_store_wrapper: None,
storage_options_accessor: None,
use_constant_size_upload_parts: false,
list_is_lexically_ordered: None,
}
}
}
impl ObjectStoreParams {
/// Get the StorageOptionsAccessor from the params
pub fn get_accessor(&self) -> Option<Arc<StorageOptionsAccessor>> {
self.storage_options_accessor.clone()
}
/// Get storage options from the accessor, if any
///
/// Returns the initial storage options from the accessor without triggering refresh.
pub fn storage_options(&self) -> Option<&HashMap<String, String>> {
self.storage_options_accessor
.as_ref()
.and_then(|a| a.initial_storage_options())
}
/// Resolve these params for a single base path scope.
///
/// Storage options may carry base-scoped entries (`base_<id>.<key>`) that
/// apply only to one registered base path; see
/// [`StorageOptionsAccessor::scoped_to_base`]. Returns the params unchanged
/// when the storage options contain no base-scoped entries.
pub fn scoped_to_base(&self, base_id: Option<u32>) -> Cow<'_, Self> {
let Some(accessor) = &self.storage_options_accessor else {
return Cow::Borrowed(self);
};
let scoped = accessor.scoped_to_base(base_id);
if Arc::ptr_eq(&scoped, accessor) {
Cow::Borrowed(self)
} else {
Cow::Owned(Self {
storage_options_accessor: Some(scoped),
..self.clone()
})
}
}
}
fn wrapper_allocation_ptr(wrapper: &Arc<dyn WrappingObjectStore>) -> *const () {
// Trait object pointers include vtable metadata, which is not stable across codegen units.
// Cache identity must follow the Arc allocation instead.
Arc::as_ptr(wrapper) as *const ()
}
// We implement hash for caching
impl std::hash::Hash for ObjectStoreParams {
#[allow(deprecated)]
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
// For hashing, we use pointer values for ObjectStore, S3 credentials, wrapper
self.block_size.hash(state);
if let Some((store, url)) = &self.object_store {
Arc::as_ptr(store).hash(state);
url.hash(state);
}
self.s3_credentials_refresh_offset.hash(state);
#[cfg(feature = "aws")]
if let Some(aws_credentials) = &self.aws_credentials {
Arc::as_ptr(aws_credentials).hash(state);
}
if let Some(wrapper) = &self.object_store_wrapper {
wrapper_allocation_ptr(wrapper).hash(state);
}
if let Some(accessor) = &self.storage_options_accessor {
accessor.accessor_id().hash(state);
}
self.use_constant_size_upload_parts.hash(state);
self.list_is_lexically_ordered.hash(state);
}
}
// We implement eq for caching
impl Eq for ObjectStoreParams {}
impl PartialEq for ObjectStoreParams {
#[allow(deprecated)]
fn eq(&self, other: &Self) -> bool {
#[cfg(feature = "aws")]
if self.aws_credentials.is_some() != other.aws_credentials.is_some() {
return false;
}
// For equality, we use pointer comparison for ObjectStore, S3 credentials, wrapper
// For accessor, we use accessor_id() for semantic equality
self.block_size == other.block_size
&& self
.object_store
.as_ref()
.map(|(store, url)| (Arc::as_ptr(store), url))
== other
.object_store
.as_ref()
.map(|(store, url)| (Arc::as_ptr(store), url))
&& self.s3_credentials_refresh_offset == other.s3_credentials_refresh_offset
&& self
.object_store_wrapper
.as_ref()
.map(wrapper_allocation_ptr)
== other
.object_store_wrapper
.as_ref()
.map(wrapper_allocation_ptr)
&& self
.storage_options_accessor
.as_ref()
.map(|a| a.accessor_id())
== other
.storage_options_accessor
.as_ref()
.map(|a| a.accessor_id())
&& self.use_constant_size_upload_parts == other.use_constant_size_upload_parts
&& self.list_is_lexically_ordered == other.list_is_lexically_ordered
}
}
/// Convert a URI string or local path to a URL
///
/// This function handles both proper URIs (with schemes like `file://`, `s3://`, etc.)
/// and plain local filesystem paths. On Windows, it correctly handles drive letters
/// that might be parsed as URL schemes.
///
/// # Examples
///
/// ```
/// # use lance_io::object_store::uri_to_url;
/// // URIs are preserved
/// let url = uri_to_url("s3://bucket/path").unwrap();
/// assert_eq!(url.scheme(), "s3");
///
/// // Local paths are converted to file:// URIs
/// # #[cfg(unix)]
/// let url = uri_to_url("/tmp/data").unwrap();
/// # #[cfg(unix)]
/// assert_eq!(url.scheme(), "file");
/// ```
pub fn uri_to_url(uri: &str) -> Result<Url> {
match Url::parse(uri) {
Ok(url) if url.scheme().len() == 1 && cfg!(windows) => {
// On Windows, the drive is parsed as a scheme
local_path_to_url(uri)
}
Ok(url) => Ok(url),
Err(_) => local_path_to_url(uri),
}
}
fn expand_path(str_path: impl AsRef<str>) -> Result<std::path::PathBuf> {
let str_path = str_path.as_ref();
let expanded = expand_tilde_path(str_path).unwrap_or_else(|| str_path.into());
let mut expanded_path = path_abs::PathAbs::new(expanded)
.unwrap()
.as_path()
.to_path_buf();
// path_abs::PathAbs::new(".") returns an empty string.
if let Some(s) = expanded_path.as_path().to_str()
&& s.is_empty()
{
expanded_path = std::env::current_dir()?;
}
Ok(expanded_path)
}
fn expand_tilde_path(path: &str) -> Option<std::path::PathBuf> {
let home_dir = std::env::home_dir()?;
if path == "~" {
return Some(home_dir);
}
if let Some(stripped) = path.strip_prefix("~/") {
return Some(home_dir.join(stripped));
}
#[cfg(windows)]
if let Some(stripped) = path.strip_prefix("~\\") {
return Some(home_dir.join(stripped));
}
None
}
fn local_path_to_url(str_path: &str) -> Result<Url> {
let expanded_path = expand_path(str_path)?;
Url::from_directory_path(expanded_path).map_err(|_| {
Error::invalid_input_source(format!("Invalid table location: '{}'", str_path).into())
})
}
#[cfg(feature = "huggingface")]
fn parse_hf_repo_id(url: &Url) -> Result<String> {
// Accept forms with repo type prefix (models/datasets/spaces) or legacy without.
let mut segments: Vec<String> = Vec::new();
if let Some(host) = url.host_str() {
segments.push(host.to_string());
}
segments.extend(
url.path()
.trim_start_matches('/')
.split('/')
.map(|s| s.to_string()),
);
if segments.len() < 2 {
return Err(Error::invalid_input(
"Huggingface URL must contain at least owner and repo",
));
}
let repo_type_candidates = ["models", "datasets", "spaces"];
let (owner, repo_with_rev) = if repo_type_candidates.contains(&segments[0].as_str()) {
if segments.len() < 3 {
return Err(Error::invalid_input(
"Huggingface URL missing owner/repo after repo type",
));
}
(segments[1].as_str(), segments[2].as_str())
} else {
(segments[0].as_str(), segments[1].as_str())
};
let repo = repo_with_rev
.split_once('@')
.map(|(r, _)| r)
.unwrap_or(repo_with_rev);
Ok(format!("{owner}/{repo}"))
}
impl ObjectStore {
/// Parse from a string URI.
///
/// Returns the ObjectStore instance and the absolute path to the object.
///
/// This uses the default [ObjectStoreRegistry] to find the object store. To
/// allow for potential re-use of object store instances, it's recommended to
/// create a shared [ObjectStoreRegistry] and pass that to [Self::from_uri_and_params].
pub async fn from_uri(uri: &str) -> Result<(Arc<Self>, Path)> {
let registry = Arc::new(ObjectStoreRegistry::default());
Self::from_uri_and_params(registry, uri, &ObjectStoreParams::default()).await
}
/// Parse from a string URI.
///
/// Returns the ObjectStore instance and the absolute path to the object.
pub async fn from_uri_and_params(
registry: Arc<ObjectStoreRegistry>,
uri: &str,
params: &ObjectStoreParams,
) -> Result<(Arc<Self>, Path)> {
Self::from_uri_and_params_impl(registry, uri, params, true).await
}
/// Parse a URI and build a fresh object store outside the registry cache.
///
/// The caller must retain the returned store for as long as its
/// provider-local state should be reused.
#[doc(hidden)]
pub async fn from_uri_and_params_uncached(
registry: Arc<ObjectStoreRegistry>,
uri: &str,
params: &ObjectStoreParams,
) -> Result<(Arc<Self>, Path)> {
Self::from_uri_and_params_impl(registry, uri, params, false).await
}
async fn from_uri_and_params_impl(
registry: Arc<ObjectStoreRegistry>,
uri: &str,
params: &ObjectStoreParams,
use_registry_cache: bool,
) -> Result<(Arc<Self>, Path)> {
#[allow(deprecated)]
if let Some((store, path)) = params.object_store.as_ref() {
let mut inner = store.clone();
let store_prefix =
registry.calculate_object_store_prefix(uri, params.storage_options())?;
let mut io_tracker = IOTracker::default();
meter_store(&mut inner, &mut io_tracker, &store_prefix);
if let Some(wrapper) = params.object_store_wrapper.as_ref() {
inner = wrapper.wrap(&store_prefix, inner);
}
// Always wrap with IO tracking
let tracked_store = io_tracker.wrap("", inner);
let store = Self {
inner: tracked_store,
local_dir_operations: None,
scheme: path.scheme().to_string(),
block_size: params.block_size.unwrap_or(64 * 1024),
max_iop_size: *DEFAULT_MAX_IOP_SIZE,
use_constant_size_upload_parts: params.use_constant_size_upload_parts,
list_is_lexically_ordered: params.list_is_lexically_ordered.unwrap_or_default(),
io_parallelism: DEFAULT_CLOUD_IO_PARALLELISM,
download_retry_count: DEFAULT_DOWNLOAD_RETRY_COUNT,
io_tracker,
store_prefix,
// Type-erased on the way in, so there is no telling if it can paginate.
paginated_lister: None,
};
let path = Path::parse(path.path())?;
return Ok((Arc::new(store), path));
}
let url = uri_to_url(uri)?;
let store = if use_registry_cache {
registry.get_store(url.clone(), params).await?
} else {
registry.new_store(url.clone(), params).await?
};
// We know the scheme is valid if we got a store back.
let provider = registry.get_provider(url.scheme()).expect_ok()?;
let path = provider.extract_path(&url)?;
Ok((store, path))
}
/// Extract the path component from a URI without initializing the object store.
///
/// This is a synchronous operation that only parses the URI and extracts the path,
/// without creating or initializing any object store instance.
///
/// # Arguments
///
/// * `registry` - The object store registry to get the provider
/// * `uri` - The URI to extract the path from
///
/// # Returns
///
/// The extracted path component
pub fn extract_path_from_uri(registry: Arc<ObjectStoreRegistry>, uri: &str) -> Result<Path> {
let url = uri_to_url(uri)?;
let provider = registry
.get_provider(url.scheme())
.ok_or_else(|| Error::invalid_input(format!("Unknown scheme: {}", url.scheme())))?;
provider.extract_path(&url)
}
#[deprecated(note = "Use `from_uri` instead")]
pub fn from_path(str_path: &str) -> Result<(Arc<Self>, Path)> {
Self::from_uri_and_params(
Arc::new(ObjectStoreRegistry::default()),
str_path,
&Default::default(),
)
.now_or_never()
.unwrap()
}
/// Local object store.
pub fn local() -> Self {
let provider = FileStoreProvider;
provider
.new_store(Url::parse("file:///").unwrap(), &Default::default())
.now_or_never()
.unwrap()
.unwrap()
}
/// Create a in-memory object store directly for testing.
pub fn memory() -> Self {
let provider = MemoryStoreProvider;
provider
.new_store(Url::parse("memory:///").unwrap(), &Default::default())
.now_or_never()
.unwrap()
.unwrap()
}
/// Returns true if the object store pointed to a local file system.
pub fn is_local(&self) -> bool {
self.scheme == "file" || self.scheme == "file+uring"
}
/// Returns true when object paths directly encode absolute local filesystem paths.
///
/// Local stores rooted below the filesystem root, such as UNC-backed stores, use
/// their inner object-store implementation instead of direct filesystem access.
pub fn has_direct_local_paths(&self) -> bool {
self.is_local() && self.store_prefix == self.scheme
}
pub fn is_cloud(&self) -> bool {
if self.is_local() || self.scheme == "memory" || self.scheme == "shared-memory" {
return false;
}
true
}
/// Whether this object store prefers the lite scheduler.
///
/// The lite scheduler is designed for backends like io_uring where
/// tasks should only be polled when the consumer polls them.
pub fn prefers_lite_scheduler(&self) -> bool {
self.scheme == "file+uring"
}
pub fn scheme(&self) -> &str {
&self.scheme
}
pub fn block_size(&self) -> usize {
self.block_size
}
pub fn max_iop_size(&self) -> u64 {
self.max_iop_size
}
/// The amount of parallelism to use for I/O operations.
///
/// Honors the `LANCE_IO_THREADS` override when set, otherwise the store's configured value.
/// Always at least 1: callers feed this straight into `buffered` / `buffer_unordered`, and a
/// window of 0 makes those streams never poll their input — e.g. a metadata-only `count_rows`
/// would hang rather than return.
pub fn io_parallelism(&self) -> usize {
std::env::var("LANCE_IO_THREADS")
.map(|val| val.parse::<usize>().unwrap())
.unwrap_or(self.io_parallelism)
.max(1)
}
/// Get the IO tracker for this object store
///
/// The IO tracker can be used to get statistics about read/write operations
/// performed on this object store.
pub fn io_tracker(&self) -> &IOTracker {
&self.io_tracker
}
/// Get a snapshot of current IO statistics without resetting counters
///
/// Returns the current IO statistics without modifying the internal state.
/// Use this when you need to check stats without resetting them.
pub fn io_stats_snapshot(&self) -> IoStats {
self.io_tracker.stats()
}
/// Get incremental IO statistics since the last call to this method
///
/// Returns the accumulated statistics since the last call and resets the
/// counters to zero. This is useful for tracking IO operations between
/// different stages of processing.
pub fn io_stats_incremental(&self) -> IoStats {
self.io_tracker.incremental_stats()
}
/// Apply a [`WrappingObjectStore`] to both `inner` and `paginated_lister` together.
///
/// Keeps both halves in sync: a wrapper returning `None` from
/// [`WrappingObjectStore::wrap_paginated`] clears the lister so that
/// [`Self::read_dir_page`] falls back through the (already-wrapped) `inner`.
pub fn apply_wrapper(&mut self, wrapper: &dyn WrappingObjectStore) {
self.inner = wrapper.wrap(&self.store_prefix, self.inner.clone());
self.paginated_lister = self
.paginated_lister
.take()
.and_then(|lister| wrapper.wrap_paginated(&self.store_prefix, lister));
}
/// Open a file for path.
///
/// Parameters
/// - ``path``: Absolute path to the file.
pub async fn open(&self, path: &Path) -> Result<Box<dyn Reader>> {
match self.scheme.as_str() {
"file" if self.has_direct_local_paths() => {
LocalObjectReader::open_with_tracker(
path,
self.block_size,
None,
Arc::new(self.io_tracker.clone()),
)
.await
}
#[cfg(target_os = "linux")]
"file+uring" => {
// Check if current-thread mode enabled
let use_current_thread = std::env::var("LANCE_URING_CURRENT_THREAD")
.map(|v| str_is_truthy(&v))
.unwrap_or(false);
if use_current_thread {
UringCurrentThreadReader::open(
path,
self.block_size,
None,
Arc::new(self.io_tracker.clone()),
)
.await
} else {
UringReader::open(
path,
self.block_size,
None,
Arc::new(self.io_tracker.clone()),
)
.await
}
}
_ => Ok(Box::new(
CloudObjectReader::new(
self.inner.clone(),
path.clone(),
self.block_size,
None,
self.download_retry_count,
)?
.with_io_parallelism(self.io_parallelism()),
)),
}
}
/// Open a reader for a file with known size.
///
/// This size may either have been retrieved from a list operation or
/// cached metadata. By passing in the known size, we can skip a HEAD / metadata
/// call.
pub async fn open_with_size(&self, path: &Path, known_size: usize) -> Result<Box<dyn Reader>> {
// If we know the file is really small, we can read the whole thing
// as a single request.
if known_size <= self.block_size {
return Ok(Box::new(SmallReader::new(
self.inner.clone(),
path.clone(),
self.download_retry_count,
known_size,
)));
}
match self.scheme.as_str() {
"file" if self.has_direct_local_paths() => {
LocalObjectReader::open_with_tracker(
path,
self.block_size,
Some(known_size),
Arc::new(self.io_tracker.clone()),
)
.await
}
#[cfg(target_os = "linux")]
"file+uring" => {
// Check if current-thread mode enabled
let use_current_thread = std::env::var("LANCE_URING_CURRENT_THREAD")
.map(|v| str_is_truthy(&v))
.unwrap_or(false);
if use_current_thread {
UringCurrentThreadReader::open(
path,
self.block_size,
Some(known_size),
Arc::new(self.io_tracker.clone()),
)
.await
} else {
UringReader::open(
path,
self.block_size,
Some(known_size),
Arc::new(self.io_tracker.clone()),
)
.await
}
}
_ => Ok(Box::new(
CloudObjectReader::new(
self.inner.clone(),
path.clone(),
self.block_size,
Some(known_size),
self.download_retry_count,
)?
.with_io_parallelism(self.io_parallelism()),
)),
}
}
/// Create an [ObjectWriter] from local [std::path::Path]
pub async fn create_local_writer(path: &std::path::Path) -> Result<ObjectWriter> {
let object_store = Self::local();
let absolute_path = expand_path(path.to_string_lossy())?;
let os_path = Path::from_absolute_path(absolute_path)?;
ObjectWriter::new(&object_store, &os_path).await
}
/// Open an [Reader] from local [std::path::Path]
pub async fn open_local(path: &std::path::Path) -> Result<Box<dyn Reader>> {
let object_store = Self::local();
let absolute_path = expand_path(path.to_string_lossy())?;
let os_path = Path::from_absolute_path(absolute_path)?;
object_store.open(&os_path).await
}
/// Create a new file.
pub async fn create(&self, path: &Path) -> Result<Box<dyn Writer>> {
match self.scheme.as_str() {
"file" if self.has_direct_local_paths() => {
let local_path = super::local::to_local_path(path);
let local_path = std::path::PathBuf::from(&local_path);
if let Some(parent) = local_path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let parent = local_path
.parent()
.expect("file path must have parent")
.to_owned();
let named_temp = tokio::task::spawn_blocking(move || {
#[cfg(unix)]
{
// NamedTempFile defaults to 0o600. Use ordinary file creation permissions so the published file honors the caller's umask.
tempfile::Builder::new()
.permissions(std::fs::Permissions::from_mode(0o666))
.tempfile_in(parent)
}
#[cfg(not(unix))]
tempfile::NamedTempFile::new_in(parent)
})