opendal/services/lakefs/
config.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::fmt::Debug;
19
20use serde::Deserialize;
21use serde::Serialize;
22
23use super::LAKEFS_SCHEME;
24use super::backend::LakefsBuilder;
25
26/// Configuration for Lakefs service support.
27#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
28#[serde(default)]
29#[non_exhaustive]
30pub struct LakefsConfig {
31    /// Base url.
32    ///
33    /// This is required.
34    pub endpoint: Option<String>,
35    /// Username for Lakefs basic authentication.
36    ///
37    /// This is required.
38    pub username: Option<String>,
39    /// Password for Lakefs basic authentication.
40    ///
41    /// This is required.
42    pub password: Option<String>,
43    /// Root of this backend. Can be "/path/to/dir".
44    ///
45    /// Default is "/".
46    pub root: Option<String>,
47
48    /// The repository name
49    ///
50    /// This is required.
51    pub repository: Option<String>,
52    /// Name of the branch or a commit ID. Default is main.
53    ///
54    /// This is optional.
55    pub branch: Option<String>,
56}
57
58impl Debug for LakefsConfig {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("LakefsConfig")
61            .field("endpoint", &self.endpoint)
62            .field("root", &self.root)
63            .field("repository", &self.repository)
64            .field("branch", &self.branch)
65            .finish_non_exhaustive()
66    }
67}
68
69impl crate::Configurator for LakefsConfig {
70    type Builder = LakefsBuilder;
71
72    fn from_uri(uri: &crate::types::OperatorUri) -> crate::Result<Self> {
73        let authority = uri.authority().ok_or_else(|| {
74            crate::Error::new(crate::ErrorKind::ConfigInvalid, "uri authority is required")
75                .with_context("service", LAKEFS_SCHEME)
76        })?;
77
78        let raw_path = uri.root().ok_or_else(|| {
79            crate::Error::new(
80                crate::ErrorKind::ConfigInvalid,
81                "uri path must contain repository",
82            )
83            .with_context("service", LAKEFS_SCHEME)
84        })?;
85
86        let (repository, remainder) = match raw_path.split_once('/') {
87            Some((repo, rest)) => (repo, Some(rest)),
88            None => (raw_path, None),
89        };
90
91        let repository = if repository.is_empty() {
92            None
93        } else {
94            Some(repository)
95        }
96        .ok_or_else(|| {
97            crate::Error::new(
98                crate::ErrorKind::ConfigInvalid,
99                "repository is required in uri path",
100            )
101            .with_context("service", LAKEFS_SCHEME)
102        })?;
103
104        let mut map = uri.options().clone();
105        map.insert("endpoint".to_string(), format!("https://{authority}"));
106        map.insert("repository".to_string(), repository.to_string());
107
108        if let Some(rest) = remainder {
109            if map.contains_key("branch") {
110                if !rest.is_empty() {
111                    map.insert("root".to_string(), rest.to_string());
112                }
113            } else {
114                let (branch, maybe_root) = match rest.split_once('/') {
115                    Some((branch_part, root_part)) => (branch_part, Some(root_part)),
116                    None => (rest, None),
117                };
118
119                if !branch.is_empty() {
120                    map.insert("branch".to_string(), branch.to_string());
121                }
122
123                if let Some(root_part) = maybe_root {
124                    if !root_part.is_empty() {
125                        map.insert("root".to_string(), root_part.to_string());
126                    }
127                }
128            }
129        }
130
131        Self::from_iter(map)
132    }
133
134    fn into_builder(self) -> Self::Builder {
135        LakefsBuilder { config: self }
136    }
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use crate::Configurator;
143    use crate::types::OperatorUri;
144
145    #[test]
146    fn from_uri_sets_endpoint_repository_branch_and_root() {
147        let uri = OperatorUri::new(
148            "lakefs://api.example.com/sample/main/data/dir",
149            Vec::<(String, String)>::new(),
150        )
151        .unwrap();
152
153        let cfg = LakefsConfig::from_uri(&uri).unwrap();
154        assert_eq!(cfg.endpoint.as_deref(), Some("https://api.example.com"));
155        assert_eq!(cfg.repository.as_deref(), Some("sample"));
156        assert_eq!(cfg.branch.as_deref(), Some("main"));
157        assert_eq!(cfg.root.as_deref(), Some("data/dir"));
158    }
159
160    #[test]
161    fn from_uri_requires_repository() {
162        let uri =
163            OperatorUri::new("lakefs://api.example.com", Vec::<(String, String)>::new()).unwrap();
164
165        assert!(LakefsConfig::from_uri(&uri).is_err());
166    }
167
168    #[test]
169    fn from_uri_respects_branch_override_and_sets_root() {
170        let uri = OperatorUri::new(
171            "lakefs://api.example.com/sample/content",
172            vec![("branch".to_string(), "develop".to_string())],
173        )
174        .unwrap();
175
176        let cfg = LakefsConfig::from_uri(&uri).unwrap();
177        assert_eq!(cfg.branch.as_deref(), Some("develop"));
178        assert_eq!(cfg.root.as_deref(), Some("content"));
179    }
180}