Skip to main content

opendal_service_cloudflare_kv/
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 opendal_core::raw::*;
21use serde::Deserialize;
22use serde::Serialize;
23
24use super::CLOUDFLARE_KV_SCHEME;
25use super::backend::CloudflareKvBuilder;
26
27/// Cloudflare KV Service Support.
28#[derive(Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
29pub struct CloudflareKvConfig {
30    /// The token used to authenticate with CloudFlare.
31    pub api_token: Option<String>,
32    /// The account ID used to authenticate with CloudFlare. Used as URI path parameter.
33    pub account_id: Option<String>,
34    /// The namespace ID. Used as URI path parameter.
35    pub namespace_id: Option<String>,
36    /// The default ttl for write operations.
37    pub default_ttl: Option<SignedDuration>,
38
39    /// Root within this backend.
40    pub root: Option<String>,
41}
42
43impl Debug for CloudflareKvConfig {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("CloudflareKvConfig")
46            .field("account_id", &self.account_id)
47            .field("namespace_id", &self.namespace_id)
48            .field("default_ttl", &self.default_ttl)
49            .field("root", &self.root)
50            .finish_non_exhaustive()
51    }
52}
53
54impl opendal_core::Configurator for CloudflareKvConfig {
55    type Builder = CloudflareKvBuilder;
56
57    fn from_uri(uri: &opendal_core::OperatorUri) -> opendal_core::Result<Self> {
58        let account_id = uri.name().ok_or_else(|| {
59            opendal_core::Error::new(
60                opendal_core::ErrorKind::ConfigInvalid,
61                "uri host must contain account id",
62            )
63            .with_context("service", CLOUDFLARE_KV_SCHEME)
64        })?;
65
66        let raw_root = uri.root().ok_or_else(|| {
67            opendal_core::Error::new(
68                opendal_core::ErrorKind::ConfigInvalid,
69                "uri path must contain namespace id",
70            )
71            .with_context("service", CLOUDFLARE_KV_SCHEME)
72        })?;
73
74        let mut segments = raw_root.splitn(2, '/');
75        let namespace_id = segments.next().filter(|s| !s.is_empty()).ok_or_else(|| {
76            opendal_core::Error::new(
77                opendal_core::ErrorKind::ConfigInvalid,
78                "namespace id is required in uri path",
79            )
80            .with_context("service", CLOUDFLARE_KV_SCHEME)
81        })?;
82
83        let mut map = uri.options().clone();
84        map.insert("account_id".to_string(), account_id.to_string());
85        map.insert("namespace_id".to_string(), namespace_id.to_string());
86
87        if let Some(rest) = segments.next()
88            && !rest.is_empty()
89        {
90            map.insert("root".to_string(), rest.to_string());
91        }
92
93        Self::from_iter(map)
94    }
95
96    fn into_builder(self) -> Self::Builder {
97        CloudflareKvBuilder {
98            config: self,
99            default_ttl: None,
100        }
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107    use opendal_core::Configurator;
108    use opendal_core::OperatorUri;
109
110    #[test]
111    fn from_uri_extracts_ids_and_root() {
112        let uri = OperatorUri::new(
113            "cloudflare-kv://acc123/ns456/prefix/dir",
114            Vec::<(String, String)>::new(),
115        )
116        .unwrap();
117
118        let cfg = CloudflareKvConfig::from_uri(&uri).unwrap();
119        assert_eq!(cfg.account_id.as_deref(), Some("acc123"));
120        assert_eq!(cfg.namespace_id.as_deref(), Some("ns456"));
121        assert_eq!(cfg.root.as_deref(), Some("prefix/dir"));
122    }
123
124    #[test]
125    fn from_uri_requires_namespace() {
126        let uri =
127            OperatorUri::new("cloudflare-kv://acc123", Vec::<(String, String)>::new()).unwrap();
128
129        assert!(CloudflareKvConfig::from_uri(&uri).is_err());
130    }
131
132    #[test]
133    fn from_iter_parses_default_ttl() {
134        let cfg = CloudflareKvConfig::from_iter([("default_ttl".to_string(), "PT1M".to_string())])
135            .unwrap();
136
137        assert_eq!(cfg.default_ttl, Some(SignedDuration::from_mins(1)));
138    }
139}