1use std::{
5 collections::HashMap,
6 sync::{
7 Arc, RwLock, Weak,
8 atomic::{AtomicU64, Ordering},
9 },
10};
11
12use object_store::path::Path;
13use url::Url;
14
15use crate::object_store::WrappingObjectStore;
16use crate::object_store::uri_to_url;
17
18use super::{ObjectStore, ObjectStoreParams, tracing::ObjectStoreTracingExt};
19use lance_core::error::{Error, LanceOptionExt, Result};
20
21#[cfg(feature = "aws")]
22pub mod aws;
23#[cfg(feature = "azure")]
24pub mod azure;
25#[cfg(feature = "gcp")]
26pub mod gcp;
27#[cfg(feature = "goosefs")]
28pub mod goosefs;
29#[cfg(feature = "huggingface")]
30pub mod huggingface;
31pub mod local;
32pub mod memory;
33#[cfg(feature = "oss")]
34pub mod oss;
35pub mod shared_memory;
36#[cfg(feature = "tencent")]
37pub mod tencent;
38#[cfg(feature = "tos")]
39pub mod tos;
40
41#[async_trait::async_trait]
42pub trait ObjectStoreProvider: std::fmt::Debug + Sync + Send {
43 async fn new_store(&self, base_path: Url, params: &ObjectStoreParams) -> Result<ObjectStore>;
44
45 fn extract_path(&self, url: &Url) -> Result<Path> {
53 Path::from_url_path(url.path()).map_err(|e| {
58 Error::invalid_input(format!("Invalid path in URL '{}': {}", url.path(), e))
59 })
60 }
61
62 fn calculate_object_store_prefix(
75 &self,
76 url: &Url,
77 _storage_options: Option<&HashMap<String, String>>,
78 ) -> Result<String> {
79 Ok(format!("{}${}", url.scheme(), url.authority()))
80 }
81}
82
83#[derive(Debug, Clone, Default)]
85pub struct ObjectStoreRegistryStats {
86 pub hits: u64,
88 pub misses: u64,
90 pub active_stores: usize,
92}
93
94#[derive(Debug)]
116pub struct ObjectStoreRegistry {
117 providers: RwLock<HashMap<String, Arc<dyn ObjectStoreProvider>>>,
118 active_stores: RwLock<HashMap<(String, ObjectStoreParams), Weak<ObjectStore>>>,
122 hits: AtomicU64,
124 misses: AtomicU64,
125}
126
127impl ObjectStoreRegistry {
128 pub fn empty() -> Self {
133 Self {
134 providers: RwLock::new(HashMap::new()),
135 active_stores: RwLock::new(HashMap::new()),
136 hits: AtomicU64::new(0),
137 misses: AtomicU64::new(0),
138 }
139 }
140
141 pub fn get_provider(&self, scheme: &str) -> Option<Arc<dyn ObjectStoreProvider>> {
143 self.providers
144 .read()
145 .expect("ObjectStoreRegistry lock poisoned")
146 .get(scheme)
147 .cloned()
148 }
149
150 pub fn active_stores(&self) -> Vec<Arc<ObjectStore>> {
155 let mut found_inactive = false;
156 let output = self
157 .active_stores
158 .read()
159 .expect("ObjectStoreRegistry lock poisoned")
160 .values()
161 .filter_map(|weak| match weak.upgrade() {
162 Some(store) => Some(store),
163 None => {
164 found_inactive = true;
165 None
166 }
167 })
168 .collect();
169
170 if found_inactive {
171 let mut cache_lock = self
173 .active_stores
174 .write()
175 .expect("ObjectStoreRegistry lock poisoned");
176 cache_lock.retain(|_, weak| weak.upgrade().is_some());
177 }
178 output
179 }
180
181 pub fn stats(&self) -> ObjectStoreRegistryStats {
187 let active_stores = self
188 .active_stores
189 .read()
190 .map(|s| s.values().filter(|w| w.strong_count() > 0).count())
191 .unwrap_or(0);
192 ObjectStoreRegistryStats {
193 hits: self.hits.load(Ordering::Relaxed),
194 misses: self.misses.load(Ordering::Relaxed),
195 active_stores,
196 }
197 }
198
199 fn scheme_not_found_error(&self, scheme: &str) -> Error {
200 let mut message = format!("No object store provider found for scheme: '{}'", scheme);
201 if let Ok(providers) = self.providers.read() {
202 let valid_schemes = providers.keys().cloned().collect::<Vec<_>>().join(", ");
203 message.push_str(&format!("\nValid schemes: {}", valid_schemes));
204 }
205 Error::invalid_input(message)
206 }
207
208 async fn build_store(
209 &self,
210 provider: Arc<dyn ObjectStoreProvider>,
211 base_path: Url,
212 params: &ObjectStoreParams,
213 store_prefix: &str,
214 ) -> Result<Arc<ObjectStore>> {
215 let mut store = provider.new_store(base_path, params).await?;
216
217 store.inner = store.inner.traced();
218
219 crate::object_store::meter_store(&mut store.inner, &mut store.io_tracker, store_prefix);
222
223 if let Some(wrapper) = ¶ms.object_store_wrapper {
224 store.apply_wrapper(wrapper.as_ref());
225 }
226
227 store.inner = store.io_tracker.wrap("", store.inner);
229
230 Ok(Arc::new(store))
231 }
232
233 #[doc(hidden)]
238 pub async fn new_store(
239 &self,
240 base_path: Url,
241 params: &ObjectStoreParams,
242 ) -> Result<Arc<ObjectStore>> {
243 let params = params.scoped_to_base(None);
247 let params = params.as_ref();
248 let scheme = base_path.scheme();
249 let Some(provider) = self.get_provider(scheme) else {
250 return Err(self.scheme_not_found_error(scheme));
251 };
252 let store_prefix =
253 provider.calculate_object_store_prefix(&base_path, params.storage_options())?;
254
255 self.build_store(provider, base_path, params, &store_prefix)
256 .await
257 }
258
259 pub async fn get_store(
265 &self,
266 base_path: Url,
267 params: &ObjectStoreParams,
268 ) -> Result<Arc<ObjectStore>> {
269 let params = params.scoped_to_base(None);
274 let params = params.as_ref();
275 let scheme = base_path.scheme();
276 let Some(provider) = self.get_provider(scheme) else {
277 return Err(self.scheme_not_found_error(scheme));
278 };
279
280 let cache_path =
281 provider.calculate_object_store_prefix(&base_path, params.storage_options())?;
282 let cache_key = (cache_path.clone(), params.clone());
283
284 {
286 let maybe_store = self
287 .active_stores
288 .read()
289 .ok()
290 .expect_ok()?
291 .get(&cache_key)
292 .cloned();
293 if let Some(store) = maybe_store {
294 if let Some(store) = store.upgrade() {
295 self.hits.fetch_add(1, Ordering::Relaxed);
296 return Ok(store);
297 } else {
298 let mut cache_lock = self
300 .active_stores
301 .write()
302 .expect("ObjectStoreRegistry lock poisoned");
303 if let Some(store) = cache_lock.get(&cache_key)
304 && store.upgrade().is_none()
305 {
306 cache_lock.remove(&cache_key);
308 }
309 }
310 }
311 }
312
313 self.misses.fetch_add(1, Ordering::Relaxed);
314
315 let store = self
316 .build_store(provider, base_path, params, &cache_path)
317 .await?;
318
319 {
320 let mut cache_lock = self.active_stores.write().ok().expect_ok()?;
322 cache_lock.insert(cache_key, Arc::downgrade(&store));
323 }
324
325 Ok(store)
326 }
327
328 pub fn calculate_object_store_prefix(
331 &self,
332 uri: &str,
333 storage_options: Option<&HashMap<String, String>>,
334 ) -> Result<String> {
335 let url = uri_to_url(uri)?;
336 match self.get_provider(url.scheme()) {
337 None => {
338 if url.scheme() == "file" || url.scheme().len() == 1 {
339 Ok("file".to_string())
340 } else {
341 Err(self.scheme_not_found_error(url.scheme()))
342 }
343 }
344 Some(provider) => provider.calculate_object_store_prefix(&url, storage_options),
345 }
346 }
347}
348
349impl Default for ObjectStoreRegistry {
350 fn default() -> Self {
351 let mut providers: HashMap<String, Arc<dyn ObjectStoreProvider>> = HashMap::new();
352
353 providers.insert("memory".into(), Arc::new(memory::MemoryStoreProvider));
354 providers.insert(
355 "shared-memory".into(),
356 Arc::new(shared_memory::SharedMemoryStoreProvider::default()),
357 );
358 providers.insert("file".into(), Arc::new(local::FileStoreProvider));
359 providers.insert(
365 "file-object-store".into(),
366 Arc::new(local::FileStoreProvider),
367 );
368 #[cfg(target_os = "linux")]
369 providers.insert("file+uring".into(), Arc::new(local::FileStoreProvider));
370
371 #[cfg(feature = "aws")]
372 {
373 let aws = Arc::new(aws::AwsStoreProvider);
374 providers.insert("s3".into(), aws.clone());
375 providers.insert("s3+ddb".into(), aws);
376 }
377 #[cfg(feature = "azure")]
378 {
379 let azure = Arc::new(azure::AzureBlobStoreProvider);
380 providers.insert("az".into(), azure.clone());
381 providers.insert("abfss".into(), azure);
382 }
383 #[cfg(feature = "gcp")]
384 providers.insert("gs".into(), Arc::new(gcp::GcsStoreProvider));
385 #[cfg(feature = "goosefs")]
386 providers.insert("goosefs".into(), Arc::new(goosefs::GooseFsStoreProvider));
387 #[cfg(feature = "oss")]
388 providers.insert("oss".into(), Arc::new(oss::OssStoreProvider));
389 #[cfg(feature = "tencent")]
390 providers.insert("cos".into(), Arc::new(tencent::TencentStoreProvider));
391 #[cfg(feature = "huggingface")]
392 providers.insert("hf".into(), Arc::new(huggingface::HuggingfaceStoreProvider));
393 #[cfg(feature = "tos")]
394 providers.insert("tos".into(), Arc::new(tos::TosStoreProvider));
395 Self {
396 providers: RwLock::new(providers),
397 active_stores: RwLock::new(HashMap::new()),
398 hits: AtomicU64::new(0),
399 misses: AtomicU64::new(0),
400 }
401 }
402}
403
404impl ObjectStoreRegistry {
405 pub fn insert(&self, scheme: &str, provider: Arc<dyn ObjectStoreProvider>) {
408 self.providers
409 .write()
410 .expect("ObjectStoreRegistry lock poisoned")
411 .insert(scheme.into(), provider);
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use std::collections::HashMap;
418 use std::sync::Mutex;
419
420 use super::*;
421 use object_store::ObjectStore as OSObjectStore;
422
423 use crate::object_store::providers::memory::MemoryStoreProvider;
424 use object_store::list::{PaginatedListOptions, PaginatedListResult, PaginatedListStore};
425 use rstest::rstest;
426
427 #[derive(Debug)]
428 struct DummyProvider;
429
430 #[async_trait::async_trait]
431 impl ObjectStoreProvider for DummyProvider {
432 async fn new_store(
433 &self,
434 _base_path: Url,
435 _params: &ObjectStoreParams,
436 ) -> Result<ObjectStore> {
437 unreachable!("This test doesn't create stores")
438 }
439 }
440
441 struct StubLister;
443
444 #[async_trait::async_trait]
445 impl PaginatedListStore for StubLister {
446 async fn list_paginated(
447 &self,
448 _prefix: Option<&str>,
449 _opts: PaginatedListOptions,
450 ) -> object_store::Result<PaginatedListResult> {
451 unimplemented!("this lister exists to be wrapped, not to list")
452 }
453 }
454
455 #[derive(Debug)]
457 struct PaginatedProvider;
458
459 #[async_trait::async_trait]
460 impl ObjectStoreProvider for PaginatedProvider {
461 async fn new_store(
462 &self,
463 base_path: Url,
464 params: &ObjectStoreParams,
465 ) -> Result<ObjectStore> {
466 let mut store = MemoryStoreProvider.new_store(base_path, params).await?;
467 store.paginated_lister = Some(Arc::new(StubLister));
468 Ok(store)
469 }
470
471 fn calculate_object_store_prefix(
472 &self,
473 _url: &Url,
474 _storage_options: Option<&HashMap<String, String>>,
475 ) -> Result<String> {
476 Ok("memory".to_string())
477 }
478 }
479
480 #[derive(Debug)]
484 struct RecordingWrapper {
485 keep_pushdown: bool,
486 prefixes: Mutex<Vec<String>>,
487 }
488
489 impl WrappingObjectStore for RecordingWrapper {
490 fn wrap(
491 &self,
492 store_prefix: &str,
493 _original: Arc<dyn OSObjectStore>,
494 ) -> Arc<dyn OSObjectStore> {
495 self.prefixes
496 .lock()
497 .unwrap()
498 .push(format!("wrap@{store_prefix}"));
499 Arc::new(object_store::memory::InMemory::new())
500 }
501
502 fn wrap_paginated(
503 &self,
504 store_prefix: &str,
505 original: Arc<dyn PaginatedListStore>,
506 ) -> Option<Arc<dyn PaginatedListStore>> {
507 self.prefixes
508 .lock()
509 .unwrap()
510 .push(format!("wrap_paginated@{store_prefix}"));
511 self.keep_pushdown.then_some(original)
512 }
513 }
514
515 #[rstest]
520 #[case::keeps_the_pushdown(true)]
521 #[case::gives_up_the_pushdown(false)]
522 #[tokio::test]
523 async fn test_the_registry_hands_the_lister_to_the_wrapper(#[case] keep_pushdown: bool) {
524 let wrapper = Arc::new(RecordingWrapper {
525 keep_pushdown,
526 prefixes: Mutex::new(Vec::new()),
527 });
528 let registry = ObjectStoreRegistry::default();
529 registry.insert("pagmem", Arc::new(PaginatedProvider));
530
531 let store = registry
532 .get_store(
533 Url::parse("pagmem:///").unwrap(),
534 &ObjectStoreParams {
535 object_store_wrapper: Some(wrapper.clone()),
536 ..Default::default()
537 },
538 )
539 .await
540 .unwrap();
541
542 assert_eq!(store.paginated_lister.is_some(), keep_pushdown);
543 assert_eq!(
545 *wrapper.prefixes.lock().unwrap(),
546 vec!["wrap@memory", "wrap_paginated@memory"]
547 );
548 if !keep_pushdown {
549 let page = store
552 .read_dir_page(Path::from(""), Default::default())
553 .await
554 .unwrap();
555 assert!(page.result.common_prefixes.is_empty());
556 assert!(page.result.objects.is_empty());
557 }
558 }
559
560 #[test]
561 fn test_calculate_object_store_prefix() {
562 let provider = DummyProvider;
563 let url = Url::parse("dummy://blah/path").unwrap();
564 assert_eq!(
565 "dummy$blah",
566 provider.calculate_object_store_prefix(&url, None).unwrap()
567 );
568 }
569
570 #[tokio::test]
571 async fn test_get_store_resolves_base_scoped_options() {
572 use crate::object_store::StorageOptionsAccessor;
573
574 let registry = ObjectStoreRegistry::default();
575 let url = Url::parse("memory://test").unwrap();
576
577 let with_scoped = ObjectStoreParams {
578 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
579 HashMap::from([
580 ("shared".to_string(), "value".to_string()),
581 ("base_1.account_key".to_string(), "base1-key".to_string()),
582 ]),
583 ))),
584 ..Default::default()
585 };
586 let without_scoped = ObjectStoreParams {
587 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
588 HashMap::from([("shared".to_string(), "value".to_string())]),
589 ))),
590 ..Default::default()
591 };
592
593 let store_scoped = registry.get_store(url.clone(), &with_scoped).await.unwrap();
596 let store_plain = registry.get_store(url, &without_scoped).await.unwrap();
597 assert!(Arc::ptr_eq(&store_scoped, &store_plain));
598 }
599
600 #[test]
601 fn test_calculate_object_store_scheme_not_found() {
602 let registry = ObjectStoreRegistry::empty();
603 registry.insert("dummy", Arc::new(DummyProvider));
604 let s = "Invalid user input: No object store provider found for scheme: 'dummy2'\nValid schemes: dummy";
605 let result = registry
606 .calculate_object_store_prefix("dummy2://mybucket/my/long/path", None)
607 .expect_err("expected error")
608 .to_string();
609 assert_eq!(s, &result[..s.len()]);
610 }
611
612 #[test]
614 fn test_calculate_object_store_prefix_for_local() {
615 let registry = ObjectStoreRegistry::empty();
616 assert_eq!(
617 "file",
618 registry
619 .calculate_object_store_prefix("/tmp/foobar", None)
620 .unwrap()
621 );
622 }
623
624 #[test]
626 fn test_calculate_object_store_prefix_for_local_windows_path() {
627 let registry = ObjectStoreRegistry::empty();
628 assert_eq!(
629 "file",
630 registry
631 .calculate_object_store_prefix("c://dos/path", None)
632 .unwrap()
633 );
634 }
635
636 #[test]
638 fn test_calculate_object_store_prefix_for_dummy_path() {
639 let registry = ObjectStoreRegistry::empty();
640 registry.insert("dummy", Arc::new(DummyProvider));
641 assert_eq!(
642 "dummy$mybucket",
643 registry
644 .calculate_object_store_prefix("dummy://mybucket/my/long/path", None)
645 .unwrap()
646 );
647 }
648
649 #[tokio::test]
650 async fn test_stats_hit_miss_tracking() {
651 use crate::object_store::StorageOptionsAccessor;
652 let registry = ObjectStoreRegistry::default();
653 let url = Url::parse("memory://test").unwrap();
654
655 let params1 = ObjectStoreParams::default();
656 let params2 = ObjectStoreParams {
657 storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
658 HashMap::from([("k".into(), "v".into())]),
659 ))),
660 ..Default::default()
661 };
662
663 let cases: &[(&ObjectStoreParams, (u64, u64, usize))] = &[
665 (¶ms1, (0, 1, 1)), (¶ms1, (1, 1, 1)), (¶ms2, (1, 2, 2)), ];
669
670 let mut stores = vec![]; for (params, (hits, misses, active)) in cases {
672 stores.push(registry.get_store(url.clone(), params).await.unwrap());
673 let s = registry.stats();
674 assert_eq!(
675 (s.hits, s.misses, s.active_stores),
676 (*hits, *misses, *active)
677 );
678 }
679
680 assert!(Arc::ptr_eq(&stores[0], &stores[1]));
682 }
683
684 #[tokio::test]
685 async fn test_new_store_bypasses_cache() {
686 let registry = ObjectStoreRegistry::default();
687 let url = Url::parse("memory://test").unwrap();
688 let params = ObjectStoreParams::default();
689
690 let first = registry.new_store(url.clone(), ¶ms).await.unwrap();
691 let second = registry.new_store(url, ¶ms).await.unwrap();
692
693 assert!(!Arc::ptr_eq(&first, &second));
694 let stats = registry.stats();
695 assert_eq!((stats.hits, stats.misses, stats.active_stores), (0, 0, 0));
696 }
697}