Skip to main content

datafusion_execution/
object_store.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! ObjectStoreRegistry holds all the object stores at Runtime with a scheme for each store.
6//! This allows the user to extend DataFusion with different storage systems such as S3 or HDFS
7//! and query data inside these systems.
8
9use dashmap::DashMap;
10use datafusion_common::{
11    DataFusionError, Result, exec_err, internal_datafusion_err, not_impl_err,
12};
13use object_store::ObjectStore;
14#[cfg(not(target_arch = "wasm32"))]
15use object_store::local::LocalFileSystem;
16use std::sync::Arc;
17use url::Url;
18
19/// A parsed URL identifying a particular [`ObjectStore`] instance
20///
21/// For example:
22/// * `file://` for local file system
23/// * `s3://bucket` for AWS S3 bucket
24/// * `oss://bucket` for Aliyun OSS bucket
25#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
26pub struct ObjectStoreUrl {
27    url: Url,
28}
29
30impl ObjectStoreUrl {
31    /// Parse an [`ObjectStoreUrl`] from a string
32    ///
33    /// # Example
34    /// ```
35    /// # use url::Url;
36    /// # use datafusion_execution::object_store::ObjectStoreUrl;
37    /// let object_store_url = ObjectStoreUrl::parse("s3://bucket").unwrap();
38    /// assert_eq!(object_store_url.as_str(), "s3://bucket/");
39    /// // can also access the underlying `Url`
40    /// let url: &Url = object_store_url.as_ref();
41    /// assert_eq!(url.scheme(), "s3");
42    /// assert_eq!(url.host_str(), Some("bucket"));
43    /// assert_eq!(url.path(), "/");
44    /// ```
45    pub fn parse(s: impl AsRef<str>) -> Result<Self> {
46        let mut parsed =
47            Url::parse(s.as_ref()).map_err(|e| DataFusionError::External(Box::new(e)))?;
48
49        let remaining = &parsed[url::Position::BeforePath..];
50        if !remaining.is_empty() && remaining != "/" {
51            return exec_err!(
52                "ObjectStoreUrl must only contain scheme and authority, got: {remaining}"
53            );
54        }
55
56        // Always set path for consistency
57        parsed.set_path("/");
58        Ok(Self { url: parsed })
59    }
60
61    /// An [`ObjectStoreUrl`] for the local filesystem (`file://`)
62    ///
63    /// # Example
64    /// ```
65    /// # use datafusion_execution::object_store::ObjectStoreUrl;
66    /// let local_fs = ObjectStoreUrl::parse("file://").unwrap();
67    /// assert_eq!(local_fs, ObjectStoreUrl::local_filesystem())
68    /// ```
69    pub fn local_filesystem() -> Self {
70        Self::parse("file://").unwrap()
71    }
72
73    /// Returns this [`ObjectStoreUrl`] as a string
74    pub fn as_str(&self) -> &str {
75        self.as_ref()
76    }
77}
78
79impl AsRef<str> for ObjectStoreUrl {
80    fn as_ref(&self) -> &str {
81        self.url.as_ref()
82    }
83}
84
85impl AsRef<Url> for ObjectStoreUrl {
86    fn as_ref(&self) -> &Url {
87        &self.url
88    }
89}
90
91impl std::fmt::Display for ObjectStoreUrl {
92    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
93        self.as_str().fmt(f)
94    }
95}
96
97/// [`ObjectStoreRegistry`] maps a URL to an [`ObjectStore`] instance,
98/// and allows DataFusion to read from different [`ObjectStore`]
99/// instances. For example DataFusion might be configured so that
100///
101/// 1. `s3://my_bucket/lineitem/` mapped to the `/lineitem` path on an
102///    AWS S3 object store bound to `my_bucket`
103///
104/// 2. `s3://my_other_bucket/lineitem/` mapped to the (same)
105///    `/lineitem` path on a *different* AWS S3 object store bound to
106///    `my_other_bucket`
107///
108/// When given a [`ListingTableUrl`], DataFusion tries to find an
109/// appropriate [`ObjectStore`]. For example
110///
111/// ```sql
112/// create external table unicorns stored as parquet location 's3://my_bucket/lineitem/';
113/// ```
114///
115/// In this particular case, the url `s3://my_bucket/lineitem/` will be provided to
116/// [`ObjectStoreRegistry::get_store`] and one of three things will happen:
117///
118/// - If an [`ObjectStore`] has been registered with [`ObjectStoreRegistry::register_store`] with
119///   `s3://my_bucket`, that [`ObjectStore`] will be returned
120///
121/// - If an AWS S3 object store can be ad-hoc discovered by the url `s3://my_bucket/lineitem/`, this
122///   object store will be registered with key `s3://my_bucket` and returned.
123///
124/// - Otherwise an error will be returned, indicating that no suitable [`ObjectStore`] could
125///   be found
126///
127/// This allows for two different use-cases:
128///
129/// 1. Systems where object store buckets are explicitly created using DDL, can register these
130///    buckets using [`ObjectStoreRegistry::register_store`]
131///
132/// 2. Systems relying on ad-hoc discovery, without corresponding DDL, can create [`ObjectStore`]
133///    lazily by providing a custom implementation of [`ObjectStoreRegistry`]
134///
135/// <!-- is in a different crate so normal rustdoc links don't work -->
136/// [`ListingTableUrl`]: https://docs.rs/datafusion/latest/datafusion/datasource/listing/struct.ListingTableUrl.html
137/// [`ObjectStore`]: object_store::ObjectStore
138pub trait ObjectStoreRegistry: Send + Sync + std::fmt::Debug + 'static {
139    /// If a store with the same key existed before, it is replaced and returned
140    fn register_store(
141        &self,
142        url: &Url,
143        store: Arc<dyn ObjectStore>,
144    ) -> Option<Arc<dyn ObjectStore>>;
145
146    /// Deregister the store previously registered with the same key. Returns the
147    /// deregistered store if it existed.
148    #[expect(unused_variables)]
149    fn deregister_store(&self, url: &Url) -> Result<Arc<dyn ObjectStore>> {
150        not_impl_err!(
151            "ObjectStoreRegistry::deregister_store is not implemented for this ObjectStoreRegistry"
152        )
153    }
154
155    /// Get a suitable store for the provided URL. For example:
156    ///
157    /// - URL with scheme `file:///` or no scheme will return the default LocalFS store
158    /// - URL with scheme `s3://bucket/` will return the S3 store
159    /// - URL with scheme `hdfs://hostname:port/` will return the hdfs store
160    ///
161    /// If no [`ObjectStore`] found for the `url`, ad-hoc discovery may be executed depending on
162    /// the `url` and [`ObjectStoreRegistry`] implementation. An [`ObjectStore`] may be lazily
163    /// created and registered.
164    fn get_store(&self, url: &Url) -> Result<Arc<dyn ObjectStore>>;
165}
166
167/// The default [`ObjectStoreRegistry`]
168pub struct DefaultObjectStoreRegistry {
169    /// A map from scheme to object store that serve list / read operations for the store
170    object_stores: DashMap<String, Arc<dyn ObjectStore>>,
171}
172
173impl std::fmt::Debug for DefaultObjectStoreRegistry {
174    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
175        f.debug_struct("DefaultObjectStoreRegistry")
176            .field(
177                "schemes",
178                &self
179                    .object_stores
180                    .iter()
181                    .map(|o| o.key().clone())
182                    .collect::<Vec<_>>(),
183            )
184            .finish()
185    }
186}
187
188impl Default for DefaultObjectStoreRegistry {
189    fn default() -> Self {
190        Self::new()
191    }
192}
193
194impl DefaultObjectStoreRegistry {
195    /// This will register [`LocalFileSystem`] to handle `file://` paths
196    #[cfg(not(target_arch = "wasm32"))]
197    pub fn new() -> Self {
198        let object_stores: DashMap<String, Arc<dyn ObjectStore>> = DashMap::new();
199        object_stores.insert("file://".to_string(), Arc::new(LocalFileSystem::new()));
200        Self { object_stores }
201    }
202
203    /// Default without any backend registered.
204    #[cfg(target_arch = "wasm32")]
205    pub fn new() -> Self {
206        let object_stores: DashMap<String, Arc<dyn ObjectStore>> = DashMap::new();
207        Self { object_stores }
208    }
209}
210
211///
212/// Stores are registered based on the scheme, host and port of the provided URL
213/// with a [`LocalFileSystem::new`] automatically registered for `file://` (if the
214/// target arch is not `wasm32`).
215///
216/// For example:
217///
218/// - `file:///my_path` will return the default LocalFS store
219/// - `s3://bucket/path` will return a store registered with `s3://bucket` if any
220/// - `hdfs://host:port/path` will return a store registered with `hdfs://host:port` if any
221impl ObjectStoreRegistry for DefaultObjectStoreRegistry {
222    fn register_store(
223        &self,
224        url: &Url,
225        store: Arc<dyn ObjectStore>,
226    ) -> Option<Arc<dyn ObjectStore>> {
227        let s = get_url_key(url);
228        self.object_stores.insert(s, store)
229    }
230
231    fn deregister_store(&self, url: &Url) -> Result<Arc<dyn ObjectStore>> {
232        let s = get_url_key(url);
233        let (_, object_store) = self.object_stores
234            .remove(&s)
235            .ok_or_else(|| {
236                internal_datafusion_err!("Failed to deregister object store. No suitable object store found for {url}. See `RuntimeEnv::register_object_store`")
237            })?;
238
239        Ok(object_store)
240    }
241
242    fn get_store(&self, url: &Url) -> Result<Arc<dyn ObjectStore>> {
243        let s = get_url_key(url);
244        self.object_stores
245            .get(&s)
246            .map(|o| Arc::clone(o.value()))
247            .ok_or_else(|| {
248                internal_datafusion_err!("No suitable object store found for {url}. See `RuntimeEnv::register_object_store`")
249            })
250    }
251}
252
253/// Get the key of a url for object store registration.
254/// The credential info will be removed
255fn get_url_key(url: &Url) -> String {
256    format!(
257        "{}://{}",
258        url.scheme(),
259        &url[url::Position::BeforeHost..url::Position::AfterPort],
260    )
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn test_object_store_url() {
269        let file = ObjectStoreUrl::parse("file://").unwrap();
270        assert_eq!(file.as_str(), "file:///");
271
272        let url = ObjectStoreUrl::parse("s3://bucket").unwrap();
273        assert_eq!(url.as_str(), "s3://bucket/");
274
275        let url = ObjectStoreUrl::parse("s3://username:password@host:123").unwrap();
276        assert_eq!(url.as_str(), "s3://username:password@host:123/");
277
278        let err = ObjectStoreUrl::parse("s3://bucket:invalid").unwrap_err();
279        assert_eq!(err.strip_backtrace(), "External error: invalid port number");
280
281        let err = ObjectStoreUrl::parse("s3://bucket?").unwrap_err();
282        assert_eq!(
283            err.strip_backtrace(),
284            "Execution error: ObjectStoreUrl must only contain scheme and authority, got: ?"
285        );
286
287        let err = ObjectStoreUrl::parse("s3://bucket?foo=bar").unwrap_err();
288        assert_eq!(
289            err.strip_backtrace(),
290            "Execution error: ObjectStoreUrl must only contain scheme and authority, got: ?foo=bar"
291        );
292
293        let err = ObjectStoreUrl::parse("s3://host:123/foo").unwrap_err();
294        assert_eq!(
295            err.strip_backtrace(),
296            "Execution error: ObjectStoreUrl must only contain scheme and authority, got: /foo"
297        );
298
299        let err =
300            ObjectStoreUrl::parse("s3://username:password@host:123/foo").unwrap_err();
301        assert_eq!(
302            err.strip_backtrace(),
303            "Execution error: ObjectStoreUrl must only contain scheme and authority, got: /foo"
304        );
305    }
306
307    #[test]
308    fn test_get_url_key() {
309        let file = ObjectStoreUrl::parse("file://").unwrap();
310        let key = get_url_key(&file.url);
311        assert_eq!(key.as_str(), "file://");
312
313        let url = ObjectStoreUrl::parse("s3://bucket").unwrap();
314        let key = get_url_key(&url.url);
315        assert_eq!(key.as_str(), "s3://bucket");
316
317        let url = ObjectStoreUrl::parse("s3://username:password@host:123").unwrap();
318        let key = get_url_key(&url.url);
319        assert_eq!(key.as_str(), "s3://host:123");
320    }
321}