1use std::collections::HashMap;
7use std::ops::Range;
8use std::pin::Pin;
9use std::str::FromStr;
10use std::sync::Arc;
11use std::time::Duration;
12
13use async_trait::async_trait;
14use bytes::Bytes;
15use chrono::{DateTime, Utc};
16use deepsize::DeepSizeOf;
17use futures::{future, stream::BoxStream, StreamExt, TryStreamExt};
18use futures::{FutureExt, Stream};
19use lance_core::error::LanceOptionExt;
20use lance_core::utils::parse::str_is_truthy;
21use list_retry::ListRetryStream;
22#[cfg(feature = "aws")]
23use object_store::aws::AwsCredentialProvider;
24use object_store::DynObjectStore;
25use object_store::Error as ObjectStoreError;
26use object_store::{path::Path, ObjectMeta, ObjectStore as OSObjectStore};
27use providers::local::FileStoreProvider;
28use providers::memory::MemoryStoreProvider;
29use shellexpand::tilde;
30use snafu::location;
31use tokio::io::AsyncWriteExt;
32use url::Url;
33
34use super::local::LocalObjectReader;
35mod list_retry;
36pub mod providers;
37mod tracing;
38use crate::object_reader::SmallReader;
39use crate::object_writer::WriteResult;
40use crate::{object_reader::CloudObjectReader, object_writer::ObjectWriter, traits::Reader};
41use lance_core::{Error, Result};
42
43pub const DEFAULT_LOCAL_IO_PARALLELISM: usize = 8;
48pub const DEFAULT_CLOUD_IO_PARALLELISM: usize = 64;
50
51const DEFAULT_LOCAL_BLOCK_SIZE: usize = 4 * 1024; #[cfg(any(feature = "aws", feature = "gcp", feature = "azure"))]
53const DEFAULT_CLOUD_BLOCK_SIZE: usize = 64 * 1024; pub static DEFAULT_MAX_IOP_SIZE: std::sync::LazyLock<u64> = std::sync::LazyLock::new(|| {
56 std::env::var("LANCE_MAX_IOP_SIZE")
57 .map(|val| val.parse().unwrap())
58 .unwrap_or(16 * 1024 * 1024)
59});
60
61pub const DEFAULT_DOWNLOAD_RETRY_COUNT: usize = 3;
62
63pub use providers::{ObjectStoreProvider, ObjectStoreRegistry};
64
65#[async_trait]
66pub trait ObjectStoreExt {
67 async fn exists(&self, path: &Path) -> Result<bool>;
69
70 fn read_dir_all<'a, 'b>(
74 &'a self,
75 dir_path: impl Into<&'b Path> + Send,
76 unmodified_since: Option<DateTime<Utc>>,
77 ) -> BoxStream<'a, Result<ObjectMeta>>;
78}
79
80#[async_trait]
81impl<O: OSObjectStore + ?Sized> ObjectStoreExt for O {
82 fn read_dir_all<'a, 'b>(
83 &'a self,
84 dir_path: impl Into<&'b Path> + Send,
85 unmodified_since: Option<DateTime<Utc>>,
86 ) -> BoxStream<'a, Result<ObjectMeta>> {
87 let output = self.list(Some(dir_path.into())).map_err(|e| e.into());
88 if let Some(unmodified_since_val) = unmodified_since {
89 output
90 .try_filter(move |file| future::ready(file.last_modified < unmodified_since_val))
91 .boxed()
92 } else {
93 output.boxed()
94 }
95 }
96
97 async fn exists(&self, path: &Path) -> Result<bool> {
98 match self.head(path).await {
99 Ok(_) => Ok(true),
100 Err(object_store::Error::NotFound { path: _, source: _ }) => Ok(false),
101 Err(e) => Err(e.into()),
102 }
103 }
104}
105
106#[derive(Debug, Clone)]
108pub struct ObjectStore {
109 pub inner: Arc<dyn OSObjectStore>,
111 scheme: String,
112 block_size: usize,
113 max_iop_size: u64,
114 pub use_constant_size_upload_parts: bool,
117 pub list_is_lexically_ordered: bool,
120 io_parallelism: usize,
121 download_retry_count: usize,
123}
124
125impl DeepSizeOf for ObjectStore {
126 fn deep_size_of_children(&self, context: &mut deepsize::Context) -> usize {
127 self.scheme.deep_size_of_children(context) + self.block_size.deep_size_of_children(context)
132 }
133}
134
135impl std::fmt::Display for ObjectStore {
136 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137 write!(f, "ObjectStore({})", self.scheme)
138 }
139}
140
141pub trait WrappingObjectStore: std::fmt::Debug + Send + Sync {
142 fn wrap(&self, original: Arc<dyn OSObjectStore>) -> Arc<dyn OSObjectStore>;
143}
144
145#[derive(Debug, Clone)]
146pub struct ChainedWrappingObjectStore {
147 wrappers: Vec<Arc<dyn WrappingObjectStore>>,
148}
149
150impl ChainedWrappingObjectStore {
151 pub fn new(wrappers: Vec<Arc<dyn WrappingObjectStore>>) -> Self {
152 Self { wrappers }
153 }
154
155 pub fn add_wrapper(&mut self, wrapper: Arc<dyn WrappingObjectStore>) {
156 self.wrappers.push(wrapper);
157 }
158}
159
160impl WrappingObjectStore for ChainedWrappingObjectStore {
161 fn wrap(&self, original: Arc<dyn OSObjectStore>) -> Arc<dyn OSObjectStore> {
162 self.wrappers
163 .iter()
164 .fold(original, |acc, wrapper| wrapper.wrap(acc))
165 }
166}
167
168#[derive(Debug, Clone)]
171pub struct ObjectStoreParams {
172 pub block_size: Option<usize>,
173 #[deprecated(note = "Implement an ObjectStoreProvider instead")]
174 pub object_store: Option<(Arc<DynObjectStore>, Url)>,
175 pub s3_credentials_refresh_offset: Duration,
176 #[cfg(feature = "aws")]
177 pub aws_credentials: Option<AwsCredentialProvider>,
178 pub object_store_wrapper: Option<Arc<dyn WrappingObjectStore>>,
179 pub storage_options: Option<HashMap<String, String>>,
180 pub use_constant_size_upload_parts: bool,
185 pub list_is_lexically_ordered: Option<bool>,
186}
187
188impl Default for ObjectStoreParams {
189 fn default() -> Self {
190 #[allow(deprecated)]
191 Self {
192 object_store: None,
193 block_size: None,
194 s3_credentials_refresh_offset: Duration::from_secs(60),
195 #[cfg(feature = "aws")]
196 aws_credentials: None,
197 object_store_wrapper: None,
198 storage_options: None,
199 use_constant_size_upload_parts: false,
200 list_is_lexically_ordered: None,
201 }
202 }
203}
204
205impl std::hash::Hash for ObjectStoreParams {
207 #[allow(deprecated)]
208 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
209 self.block_size.hash(state);
211 if let Some((store, url)) = &self.object_store {
212 Arc::as_ptr(store).hash(state);
213 url.hash(state);
214 }
215 self.s3_credentials_refresh_offset.hash(state);
216 #[cfg(feature = "aws")]
217 if let Some(aws_credentials) = &self.aws_credentials {
218 Arc::as_ptr(aws_credentials).hash(state);
219 }
220 if let Some(wrapper) = &self.object_store_wrapper {
221 Arc::as_ptr(wrapper).hash(state);
222 }
223 if let Some(storage_options) = &self.storage_options {
224 for (key, value) in storage_options {
225 key.hash(state);
226 value.hash(state);
227 }
228 }
229 self.use_constant_size_upload_parts.hash(state);
230 self.list_is_lexically_ordered.hash(state);
231 }
232}
233
234impl Eq for ObjectStoreParams {}
236impl PartialEq for ObjectStoreParams {
237 #[allow(deprecated)]
238 fn eq(&self, other: &Self) -> bool {
239 self.block_size == other.block_size
241 && self
242 .object_store
243 .as_ref()
244 .map(|(store, url)| (Arc::as_ptr(store), url))
245 == other
246 .object_store
247 .as_ref()
248 .map(|(store, url)| (Arc::as_ptr(store), url))
249 && self.s3_credentials_refresh_offset == other.s3_credentials_refresh_offset
250 && self.aws_credentials.as_ref().map(Arc::as_ptr)
251 == other.aws_credentials.as_ref().map(Arc::as_ptr)
252 && self.object_store_wrapper.as_ref().map(Arc::as_ptr)
253 == other.object_store_wrapper.as_ref().map(Arc::as_ptr)
254 && self.storage_options == other.storage_options
255 && self.use_constant_size_upload_parts == other.use_constant_size_upload_parts
256 && self.list_is_lexically_ordered == other.list_is_lexically_ordered
257 }
258}
259
260fn uri_to_url(uri: &str) -> Result<Url> {
261 match Url::parse(uri) {
262 Ok(url) if url.scheme().len() == 1 && cfg!(windows) => {
263 local_path_to_url(uri)
265 }
266 Ok(url) => Ok(url),
267 Err(_) => local_path_to_url(uri),
268 }
269}
270
271fn expand_path(str_path: impl AsRef<str>) -> Result<std::path::PathBuf> {
272 let expanded = tilde(str_path.as_ref()).to_string();
273
274 let mut expanded_path = path_abs::PathAbs::new(expanded)
275 .unwrap()
276 .as_path()
277 .to_path_buf();
278 if let Some(s) = expanded_path.as_path().to_str() {
280 if s.is_empty() {
281 expanded_path = std::env::current_dir()?;
282 }
283 }
284
285 Ok(expanded_path)
286}
287
288fn local_path_to_url(str_path: &str) -> Result<Url> {
289 let expanded_path = expand_path(str_path)?;
290
291 Url::from_directory_path(expanded_path).map_err(|_| Error::InvalidInput {
292 source: format!("Invalid table location: '{}'", str_path).into(),
293 location: location!(),
294 })
295}
296
297impl ObjectStore {
298 pub async fn from_uri(uri: &str) -> Result<(Arc<Self>, Path)> {
306 let registry = Arc::new(ObjectStoreRegistry::default());
307
308 Self::from_uri_and_params(registry, uri, &ObjectStoreParams::default()).await
309 }
310
311 pub async fn from_uri_and_params(
315 registry: Arc<ObjectStoreRegistry>,
316 uri: &str,
317 params: &ObjectStoreParams,
318 ) -> Result<(Arc<Self>, Path)> {
319 #[allow(deprecated)]
320 if let Some((store, path)) = params.object_store.as_ref() {
321 let mut inner = store.clone();
322 if let Some(wrapper) = params.object_store_wrapper.as_ref() {
323 inner = wrapper.wrap(inner);
324 }
325 let store = Self {
326 inner,
327 scheme: path.scheme().to_string(),
328 block_size: params.block_size.unwrap_or(64 * 1024),
329 max_iop_size: *DEFAULT_MAX_IOP_SIZE,
330 use_constant_size_upload_parts: params.use_constant_size_upload_parts,
331 list_is_lexically_ordered: params.list_is_lexically_ordered.unwrap_or_default(),
332 io_parallelism: DEFAULT_CLOUD_IO_PARALLELISM,
333 download_retry_count: DEFAULT_DOWNLOAD_RETRY_COUNT,
334 };
335 let path = Path::from(path.path());
336 return Ok((Arc::new(store), path));
337 }
338 let url = uri_to_url(uri)?;
339 let store = registry.get_store(url.clone(), params).await?;
340 let provider = registry.get_provider(url.scheme()).expect_ok()?;
342 let path = provider.extract_path(&url);
343
344 Ok((store, path))
345 }
346
347 #[deprecated(note = "Use `from_uri` instead")]
348 pub fn from_path(str_path: &str) -> Result<(Arc<Self>, Path)> {
349 Self::from_uri_and_params(
350 Arc::new(ObjectStoreRegistry::default()),
351 str_path,
352 &Default::default(),
353 )
354 .now_or_never()
355 .unwrap()
356 }
357
358 pub fn local() -> Self {
360 let provider = FileStoreProvider;
361 provider
362 .new_store(Url::parse("file:///").unwrap(), &Default::default())
363 .now_or_never()
364 .unwrap()
365 .unwrap()
366 }
367
368 pub fn memory() -> Self {
370 let provider = MemoryStoreProvider;
371 provider
372 .new_store(Url::parse("memory:///").unwrap(), &Default::default())
373 .now_or_never()
374 .unwrap()
375 .unwrap()
376 }
377
378 pub fn is_local(&self) -> bool {
380 self.scheme == "file"
381 }
382
383 pub fn is_cloud(&self) -> bool {
384 self.scheme != "file" && self.scheme != "memory"
385 }
386
387 pub fn scheme(&self) -> &str {
388 &self.scheme
389 }
390
391 pub fn block_size(&self) -> usize {
392 self.block_size
393 }
394
395 pub fn max_iop_size(&self) -> u64 {
396 self.max_iop_size
397 }
398
399 pub fn io_parallelism(&self) -> usize {
400 std::env::var("LANCE_IO_THREADS")
401 .map(|val| val.parse::<usize>().unwrap())
402 .unwrap_or(self.io_parallelism)
403 }
404
405 pub async fn open(&self, path: &Path) -> Result<Box<dyn Reader>> {
410 match self.scheme.as_str() {
411 "file" => LocalObjectReader::open(path, self.block_size, None).await,
412 _ => Ok(Box::new(CloudObjectReader::new(
413 self.inner.clone(),
414 path.clone(),
415 self.block_size,
416 None,
417 self.download_retry_count,
418 )?)),
419 }
420 }
421
422 pub async fn open_with_size(&self, path: &Path, known_size: usize) -> Result<Box<dyn Reader>> {
428 if known_size <= self.block_size {
431 return Ok(Box::new(SmallReader::new(
432 self.inner.clone(),
433 path.clone(),
434 self.download_retry_count,
435 known_size,
436 )));
437 }
438
439 match self.scheme.as_str() {
440 "file" => LocalObjectReader::open(path, self.block_size, Some(known_size)).await,
441 _ => Ok(Box::new(CloudObjectReader::new(
442 self.inner.clone(),
443 path.clone(),
444 self.block_size,
445 Some(known_size),
446 self.download_retry_count,
447 )?)),
448 }
449 }
450
451 pub async fn create_local_writer(path: &std::path::Path) -> Result<ObjectWriter> {
453 let object_store = Self::local();
454 let absolute_path = expand_path(path.to_string_lossy())?;
455 let os_path = Path::from_absolute_path(absolute_path)?;
456 object_store.create(&os_path).await
457 }
458
459 pub async fn open_local(path: &std::path::Path) -> Result<Box<dyn Reader>> {
461 let object_store = Self::local();
462 let absolute_path = expand_path(path.to_string_lossy())?;
463 let os_path = Path::from_absolute_path(absolute_path)?;
464 object_store.open(&os_path).await
465 }
466
467 pub async fn create(&self, path: &Path) -> Result<ObjectWriter> {
469 ObjectWriter::new(self, path).await
470 }
471
472 pub async fn put(&self, path: &Path, content: &[u8]) -> Result<WriteResult> {
474 let mut writer = self.create(path).await?;
475 writer.write_all(content).await?;
476 writer.shutdown().await
477 }
478
479 pub async fn delete(&self, path: &Path) -> Result<()> {
480 self.inner.delete(path).await?;
481 Ok(())
482 }
483
484 pub async fn copy(&self, from: &Path, to: &Path) -> Result<()> {
485 if self.is_local() {
486 return super::local::copy_file(from, to);
488 }
489 Ok(self.inner.copy(from, to).await?)
490 }
491
492 pub async fn read_dir(&self, dir_path: impl Into<Path>) -> Result<Vec<String>> {
494 let path = dir_path.into();
495 let path = Path::parse(&path)?;
496 let output = self.inner.list_with_delimiter(Some(&path)).await?;
497 Ok(output
498 .common_prefixes
499 .iter()
500 .chain(output.objects.iter().map(|o| &o.location))
501 .map(|s| s.filename().unwrap().to_string())
502 .collect())
503 }
504
505 pub fn list(
506 &self,
507 path: Option<Path>,
508 ) -> Pin<Box<dyn Stream<Item = Result<ObjectMeta>> + Send>> {
509 Box::pin(ListRetryStream::new(self.inner.clone(), path, 5).map(|m| m.map_err(|e| e.into())))
510 }
511
512 pub fn read_dir_all<'a, 'b>(
516 &'a self,
517 dir_path: impl Into<&'b Path> + Send,
518 unmodified_since: Option<DateTime<Utc>>,
519 ) -> BoxStream<'a, Result<ObjectMeta>> {
520 self.inner.read_dir_all(dir_path, unmodified_since)
521 }
522
523 pub async fn remove_dir_all(&self, dir_path: impl Into<Path>) -> Result<()> {
525 let path = dir_path.into();
526 let path = Path::parse(&path)?;
527
528 if self.is_local() {
529 return super::local::remove_dir_all(&path);
531 }
532 let sub_entries = self
533 .inner
534 .list(Some(&path))
535 .map(|m| m.map(|meta| meta.location))
536 .boxed();
537 self.inner
538 .delete_stream(sub_entries)
539 .try_collect::<Vec<_>>()
540 .await?;
541 Ok(())
542 }
543
544 pub fn remove_stream<'a>(
545 &'a self,
546 locations: BoxStream<'a, Result<Path>>,
547 ) -> BoxStream<'a, Result<Path>> {
548 self.inner
549 .delete_stream(locations.err_into::<ObjectStoreError>().boxed())
550 .err_into::<Error>()
551 .boxed()
552 }
553
554 pub async fn exists(&self, path: &Path) -> Result<bool> {
556 match self.inner.head(path).await {
557 Ok(_) => Ok(true),
558 Err(object_store::Error::NotFound { path: _, source: _ }) => Ok(false),
559 Err(e) => Err(e.into()),
560 }
561 }
562
563 pub async fn size(&self, path: &Path) -> Result<u64> {
565 Ok(self.inner.head(path).await?.size)
566 }
567
568 pub async fn read_one_all(&self, path: &Path) -> Result<Bytes> {
570 let reader = self.open(path).await?;
571 Ok(reader.get_all().await?)
572 }
573
574 pub async fn read_one_range(&self, path: &Path, range: Range<usize>) -> Result<Bytes> {
579 let reader = self.open(path).await?;
580 Ok(reader.get_range(range).await?)
581 }
582}
583
584#[derive(PartialEq, Eq, Hash, Clone, Debug, Copy)]
586pub enum LanceConfigKey {
587 DownloadRetryCount,
589}
590
591impl FromStr for LanceConfigKey {
592 type Err = Error;
593
594 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
595 match s.to_ascii_lowercase().as_str() {
596 "download_retry_count" => Ok(Self::DownloadRetryCount),
597 _ => Err(Error::InvalidInput {
598 source: format!("Invalid LanceConfigKey: {}", s).into(),
599 location: location!(),
600 }),
601 }
602 }
603}
604
605#[derive(Clone, Debug, Default)]
606pub struct StorageOptions(pub HashMap<String, String>);
607
608impl StorageOptions {
609 pub fn new(options: HashMap<String, String>) -> Self {
611 let mut options = options;
612 if let Ok(value) = std::env::var("AZURE_STORAGE_ALLOW_HTTP") {
613 options.insert("allow_http".into(), value);
614 }
615 if let Ok(value) = std::env::var("AZURE_STORAGE_USE_HTTP") {
616 options.insert("allow_http".into(), value);
617 }
618 if let Ok(value) = std::env::var("AWS_ALLOW_HTTP") {
619 options.insert("allow_http".into(), value);
620 }
621 if let Ok(value) = std::env::var("OBJECT_STORE_CLIENT_MAX_RETRIES") {
622 options.insert("client_max_retries".into(), value);
623 }
624 if let Ok(value) = std::env::var("OBJECT_STORE_CLIENT_RETRY_TIMEOUT") {
625 options.insert("client_retry_timeout".into(), value);
626 }
627 Self(options)
628 }
629
630 pub fn allow_http(&self) -> bool {
632 self.0.iter().any(|(key, value)| {
633 key.to_ascii_lowercase().contains("allow_http") & str_is_truthy(value)
634 })
635 }
636
637 pub fn download_retry_count(&self) -> usize {
639 self.0
640 .iter()
641 .find(|(key, _)| key.eq_ignore_ascii_case("download_retry_count"))
642 .map(|(_, value)| value.parse::<usize>().unwrap_or(3))
643 .unwrap_or(3)
644 }
645
646 pub fn client_max_retries(&self) -> usize {
648 self.0
649 .iter()
650 .find(|(key, _)| key.eq_ignore_ascii_case("client_max_retries"))
651 .and_then(|(_, value)| value.parse::<usize>().ok())
652 .unwrap_or(10)
653 }
654
655 pub fn client_retry_timeout(&self) -> u64 {
657 self.0
658 .iter()
659 .find(|(key, _)| key.eq_ignore_ascii_case("client_retry_timeout"))
660 .and_then(|(_, value)| value.parse::<u64>().ok())
661 .unwrap_or(180)
662 }
663
664 pub fn get(&self, key: &str) -> Option<&String> {
665 self.0.get(key)
666 }
667}
668
669impl From<HashMap<String, String>> for StorageOptions {
670 fn from(value: HashMap<String, String>) -> Self {
671 Self::new(value)
672 }
673}
674
675impl ObjectStore {
676 #[allow(clippy::too_many_arguments)]
677 pub fn new(
678 store: Arc<DynObjectStore>,
679 location: Url,
680 block_size: Option<usize>,
681 wrapper: Option<Arc<dyn WrappingObjectStore>>,
682 use_constant_size_upload_parts: bool,
683 list_is_lexically_ordered: bool,
684 io_parallelism: usize,
685 download_retry_count: usize,
686 ) -> Self {
687 let scheme = location.scheme();
688 let block_size = block_size.unwrap_or_else(|| infer_block_size(scheme));
689
690 let store = match wrapper {
691 Some(wrapper) => wrapper.wrap(store),
692 None => store,
693 };
694
695 Self {
696 inner: store,
697 scheme: scheme.into(),
698 block_size,
699 max_iop_size: *DEFAULT_MAX_IOP_SIZE,
700 use_constant_size_upload_parts,
701 list_is_lexically_ordered,
702 io_parallelism,
703 download_retry_count,
704 }
705 }
706}
707
708fn infer_block_size(scheme: &str) -> usize {
709 match scheme {
713 "file" => 4 * 1024,
714 _ => 64 * 1024,
715 }
716}
717
718#[cfg(test)]
719mod tests {
720 use super::*;
721 use object_store::memory::InMemory;
722 use rstest::rstest;
723 use std::env::set_current_dir;
724 use std::fs::{create_dir_all, write};
725 use std::path::Path as StdPath;
726 use std::sync::atomic::{AtomicBool, Ordering};
727
728 fn write_to_file(path_str: &str, contents: &str) -> std::io::Result<()> {
730 let expanded = tilde(path_str).to_string();
731 let path = StdPath::new(&expanded);
732 std::fs::create_dir_all(path.parent().unwrap())?;
733 write(path, contents)
734 }
735
736 async fn read_from_store(store: &ObjectStore, path: &Path) -> Result<String> {
737 let test_file_store = store.open(path).await.unwrap();
738 let size = test_file_store.size().await.unwrap();
739 let bytes = test_file_store.get_range(0..size).await.unwrap();
740 let contents = String::from_utf8(bytes.to_vec()).unwrap();
741 Ok(contents)
742 }
743
744 #[tokio::test]
745 async fn test_absolute_paths() {
746 let tmp_dir = tempfile::tempdir().unwrap();
747 let tmp_path = tmp_dir.path().to_str().unwrap().to_owned();
748 write_to_file(
749 &format!("{tmp_path}/bar/foo.lance/test_file"),
750 "TEST_CONTENT",
751 )
752 .unwrap();
753
754 for uri in &[
756 format!("{tmp_path}/bar/foo.lance"),
757 format!("{tmp_path}/./bar/foo.lance"),
758 format!("{tmp_path}/bar/foo.lance/../foo.lance"),
759 ] {
760 let (store, path) = ObjectStore::from_uri(uri).await.unwrap();
761 let contents = read_from_store(store.as_ref(), &path.child("test_file"))
762 .await
763 .unwrap();
764 assert_eq!(contents, "TEST_CONTENT");
765 }
766 }
767
768 #[tokio::test]
769 async fn test_cloud_paths() {
770 let uri = "s3://bucket/foo.lance";
771 let (store, path) = ObjectStore::from_uri(uri).await.unwrap();
772 assert_eq!(store.scheme, "s3");
773 assert_eq!(path.to_string(), "foo.lance");
774
775 let (store, path) = ObjectStore::from_uri("s3+ddb://bucket/foo.lance")
776 .await
777 .unwrap();
778 assert_eq!(store.scheme, "s3");
779 assert_eq!(path.to_string(), "foo.lance");
780
781 let (store, path) = ObjectStore::from_uri("gs://bucket/foo.lance")
782 .await
783 .unwrap();
784 assert_eq!(store.scheme, "gs");
785 assert_eq!(path.to_string(), "foo.lance");
786 }
787
788 async fn test_block_size_used_test_helper(
789 uri: &str,
790 storage_options: Option<HashMap<String, String>>,
791 default_expected_block_size: usize,
792 ) {
793 let registry = Arc::new(ObjectStoreRegistry::default());
795 let params = ObjectStoreParams {
796 storage_options: storage_options.clone(),
797 ..ObjectStoreParams::default()
798 };
799 let (store, _) = ObjectStore::from_uri_and_params(registry, uri, ¶ms)
800 .await
801 .unwrap();
802 assert_eq!(store.block_size, default_expected_block_size);
803
804 let registry = Arc::new(ObjectStoreRegistry::default());
806 let params = ObjectStoreParams {
807 block_size: Some(1024),
808 storage_options: storage_options.clone(),
809 ..ObjectStoreParams::default()
810 };
811 let (store, _) = ObjectStore::from_uri_and_params(registry, uri, ¶ms)
812 .await
813 .unwrap();
814 assert_eq!(store.block_size, 1024);
815 }
816
817 #[rstest]
818 #[case("s3://bucket/foo.lance", None)]
819 #[case("gs://bucket/foo.lance", None)]
820 #[case("az://account/bucket/foo.lance",
821 Some(HashMap::from([
822 (String::from("account_name"), String::from("account")),
823 (String::from("container_name"), String::from("container"))
824 ])))]
825 #[tokio::test]
826 async fn test_block_size_used_cloud(
827 #[case] uri: &str,
828 #[case] storage_options: Option<HashMap<String, String>>,
829 ) {
830 test_block_size_used_test_helper(uri, storage_options, 64 * 1024).await;
831 }
832
833 #[rstest]
834 #[case("file")]
835 #[case("file-object-store")]
836 #[case("memory:///bucket/foo.lance")]
837 #[tokio::test]
838 async fn test_block_size_used_file(#[case] prefix: &str) {
839 let tmp_dir = tempfile::tempdir().unwrap();
840 let tmp_path = tmp_dir.path().to_str().unwrap().to_owned();
841 let path = format!("{tmp_path}/bar/foo.lance/test_file");
842 write_to_file(&path, "URL").unwrap();
843 let uri = format!("{prefix}:///{path}");
844 test_block_size_used_test_helper(&uri, None, 4 * 1024).await;
845 }
846
847 #[tokio::test]
848 async fn test_relative_paths() {
849 let tmp_dir = tempfile::tempdir().unwrap();
850 let tmp_path = tmp_dir.path().to_str().unwrap().to_owned();
851 write_to_file(
852 &format!("{tmp_path}/bar/foo.lance/test_file"),
853 "RELATIVE_URL",
854 )
855 .unwrap();
856
857 set_current_dir(StdPath::new(&tmp_path)).expect("Error changing current dir");
858 let (store, path) = ObjectStore::from_uri("./bar/foo.lance").await.unwrap();
859
860 let contents = read_from_store(store.as_ref(), &path.child("test_file"))
861 .await
862 .unwrap();
863 assert_eq!(contents, "RELATIVE_URL");
864 }
865
866 #[tokio::test]
867 async fn test_tilde_expansion() {
868 let uri = "~/foo.lance";
869 write_to_file(&format!("{uri}/test_file"), "TILDE").unwrap();
870 let (store, path) = ObjectStore::from_uri(uri).await.unwrap();
871 let contents = read_from_store(store.as_ref(), &path.child("test_file"))
872 .await
873 .unwrap();
874 assert_eq!(contents, "TILDE");
875 }
876
877 #[tokio::test]
878 async fn test_read_directory() {
879 let tmp_dir = tempfile::tempdir().unwrap();
880 let path = tmp_dir.path();
881 create_dir_all(path.join("foo").join("bar")).unwrap();
882 create_dir_all(path.join("foo").join("zoo")).unwrap();
883 create_dir_all(path.join("foo").join("zoo").join("abc")).unwrap();
884 write_to_file(
885 path.join("foo").join("test_file").to_str().unwrap(),
886 "read_dir",
887 )
888 .unwrap();
889 let (store, base) = ObjectStore::from_uri(path.to_str().unwrap()).await.unwrap();
890
891 let sub_dirs = store.read_dir(base.child("foo")).await.unwrap();
892 assert_eq!(sub_dirs, vec!["bar", "zoo", "test_file"]);
893 }
894
895 #[tokio::test]
896 async fn test_delete_directory() {
897 let tmp_dir = tempfile::tempdir().unwrap();
898 let path = tmp_dir.path();
899 create_dir_all(path.join("foo").join("bar")).unwrap();
900 create_dir_all(path.join("foo").join("zoo")).unwrap();
901 create_dir_all(path.join("foo").join("zoo").join("abc")).unwrap();
902 write_to_file(
903 path.join("foo")
904 .join("bar")
905 .join("test_file")
906 .to_str()
907 .unwrap(),
908 "delete",
909 )
910 .unwrap();
911 write_to_file(path.join("foo").join("top").to_str().unwrap(), "delete_top").unwrap();
912 let (store, base) = ObjectStore::from_uri(path.to_str().unwrap()).await.unwrap();
913 store.remove_dir_all(base.child("foo")).await.unwrap();
914
915 assert!(!path.join("foo").exists());
916 }
917
918 #[derive(Debug)]
919 struct TestWrapper {
920 called: AtomicBool,
921
922 return_value: Arc<dyn OSObjectStore>,
923 }
924
925 impl WrappingObjectStore for TestWrapper {
926 fn wrap(&self, _original: Arc<dyn OSObjectStore>) -> Arc<dyn OSObjectStore> {
927 self.called.store(true, Ordering::Relaxed);
928
929 self.return_value.clone()
931 }
932 }
933
934 impl TestWrapper {
935 fn called(&self) -> bool {
936 self.called.load(Ordering::Relaxed)
937 }
938 }
939
940 #[tokio::test]
941 async fn test_wrapping_object_store_option_is_used() {
942 let mock_inner_store: Arc<dyn OSObjectStore> = Arc::new(InMemory::new());
944 let registry = Arc::new(ObjectStoreRegistry::default());
945
946 assert_eq!(Arc::strong_count(&mock_inner_store), 1);
947
948 let wrapper = Arc::new(TestWrapper {
949 called: AtomicBool::new(false),
950 return_value: mock_inner_store.clone(),
951 });
952
953 let params = ObjectStoreParams {
954 object_store_wrapper: Some(wrapper.clone()),
955 ..ObjectStoreParams::default()
956 };
957
958 assert!(!wrapper.called());
960
961 let _ = ObjectStore::from_uri_and_params(registry, "memory:///", ¶ms)
962 .await
963 .unwrap();
964
965 assert!(wrapper.called());
967
968 assert_eq!(Arc::strong_count(&mock_inner_store), 2);
971 }
972
973 #[tokio::test]
974 async fn test_local_paths() {
975 let temp_dir = tempfile::tempdir().unwrap();
976
977 let file_path = temp_dir.path().join("test_file");
978 let mut writer = ObjectStore::create_local_writer(file_path.as_path())
979 .await
980 .unwrap();
981 writer.write_all(b"LOCAL").await.unwrap();
982 writer.shutdown().await.unwrap();
983
984 let reader = ObjectStore::open_local(file_path.as_path()).await.unwrap();
985 let buf = reader.get_range(0..5).await.unwrap();
986 assert_eq!(buf.as_ref(), b"LOCAL");
987 }
988
989 #[tokio::test]
990 async fn test_read_one() {
991 let temp_dir = tempfile::tempdir().unwrap();
992
993 let file_path = temp_dir.path().join("test_file");
994 let mut writer = ObjectStore::create_local_writer(file_path.as_path())
995 .await
996 .unwrap();
997 writer.write_all(b"LOCAL").await.unwrap();
998 writer.shutdown().await.unwrap();
999
1000 let file_path_os = object_store::path::Path::parse(file_path.to_str().unwrap()).unwrap();
1001 let obj_store = ObjectStore::local();
1002 let buf = obj_store.read_one_all(&file_path_os).await.unwrap();
1003 assert_eq!(buf.as_ref(), b"LOCAL");
1004
1005 let buf = obj_store.read_one_range(&file_path_os, 0..5).await.unwrap();
1006 assert_eq!(buf.as_ref(), b"LOCAL");
1007 }
1008
1009 #[tokio::test]
1010 #[cfg(windows)]
1011 async fn test_windows_paths() {
1012 use std::path::Component;
1013 use std::path::Prefix;
1014 use std::path::Prefix::*;
1015
1016 fn get_path_prefix(path: &StdPath) -> Prefix {
1017 match path.components().next().unwrap() {
1018 Component::Prefix(prefix_component) => prefix_component.kind(),
1019 _ => panic!(),
1020 }
1021 }
1022
1023 fn get_drive_letter(prefix: Prefix) -> String {
1024 match prefix {
1025 Disk(bytes) => String::from_utf8(vec![bytes]).unwrap(),
1026 _ => panic!(),
1027 }
1028 }
1029
1030 let tmp_dir = tempfile::tempdir().unwrap();
1031 let tmp_path = tmp_dir.path();
1032 let prefix = get_path_prefix(tmp_path);
1033 let drive_letter = get_drive_letter(prefix);
1034
1035 write_to_file(
1036 &(format!("{drive_letter}:/test_folder/test.lance") + "/test_file"),
1037 "WINDOWS",
1038 )
1039 .unwrap();
1040
1041 for uri in &[
1042 format!("{drive_letter}:/test_folder/test.lance"),
1043 format!("{drive_letter}:\\test_folder\\test.lance"),
1044 ] {
1045 let (store, base) = ObjectStore::from_uri(uri).await.unwrap();
1046 let contents = read_from_store(store.as_ref(), &base.child("test_file"))
1047 .await
1048 .unwrap();
1049 assert_eq!(contents, "WINDOWS");
1050 }
1051 }
1052
1053 #[tokio::test]
1054 async fn test_cross_filesystem_copy() {
1055 let source_dir = tempfile::tempdir().unwrap();
1057 let dest_dir = tempfile::tempdir().unwrap();
1058
1059 let source_file_name = "test_file.txt";
1061 let source_file = source_dir.path().join(source_file_name);
1062 std::fs::write(&source_file, b"test content").unwrap();
1063
1064 let (store, base_path) = ObjectStore::from_uri(source_dir.path().to_str().unwrap())
1066 .await
1067 .unwrap();
1068
1069 let from_path = base_path.child(source_file_name);
1071
1072 let dest_file = dest_dir.path().join("copied_file.txt");
1074 let dest_str = dest_file.to_str().unwrap();
1075 let to_path = object_store::path::Path::parse(dest_str).unwrap();
1076
1077 store.copy(&from_path, &to_path).await.unwrap();
1079
1080 assert!(dest_file.exists());
1082 let copied_content = std::fs::read(&dest_file).unwrap();
1083 assert_eq!(copied_content, b"test content");
1084 }
1085
1086 #[tokio::test]
1087 async fn test_copy_creates_parent_directories() {
1088 let source_dir = tempfile::tempdir().unwrap();
1089 let dest_dir = tempfile::tempdir().unwrap();
1090
1091 let source_file_name = "test_file.txt";
1093 let source_file = source_dir.path().join(source_file_name);
1094 std::fs::write(&source_file, b"test content").unwrap();
1095
1096 let (store, base_path) = ObjectStore::from_uri(source_dir.path().to_str().unwrap())
1098 .await
1099 .unwrap();
1100
1101 let from_path = base_path.child(source_file_name);
1103
1104 let dest_file = dest_dir
1106 .path()
1107 .join("nested")
1108 .join("dirs")
1109 .join("copied_file.txt");
1110 let dest_str = dest_file.to_str().unwrap();
1111 let to_path = object_store::path::Path::parse(dest_str).unwrap();
1112
1113 store.copy(&from_path, &to_path).await.unwrap();
1115
1116 assert!(dest_file.exists());
1118 assert!(dest_file.parent().unwrap().exists());
1119 let copied_content = std::fs::read(&dest_file).unwrap();
1120 assert_eq!(copied_content, b"test content");
1121 }
1122}