1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use std::fmt::Debug;

use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::raw::*;
use crate::*;

/// Builder is used to set up underlying services.
///
/// This trait allows the developer to define a builder struct that can:
///
/// - build a service via builder style API.
/// - configure in-memory options like `http_client` or `customized_credential_load`.
///
/// Usually, users don't need to use or import this trait directly, they can use `Operator` API instead.
///
/// For example:
///
/// ```
/// # use anyhow::Result;
/// use opendal::services::Fs;
/// use opendal::Operator;
/// async fn test() -> Result<()> {
///     // Create fs backend builder.
///     let mut builder = Fs::default().root("/tmp");
///
///     // Build an `Operator` to start operating the storage.
///     let op: Operator = Operator::new(builder)?.finish();
///
///     Ok(())
/// }
/// ```
pub trait Builder: Default + 'static {
    /// Associated scheme for this builder. It indicates what underlying service is.
    const SCHEME: Scheme;
    /// Associated configuration for this builder.
    type Config: Configurator;

    /// Consume the accessor builder to build a service.
    fn build(self) -> Result<impl Access>;
}

/// Dummy implementation of builder
impl Builder for () {
    const SCHEME: Scheme = Scheme::Custom("dummy");
    type Config = ();

    fn build(self) -> Result<impl Access> {
        Ok(())
    }
}

/// Configurator is used to configure the underlying service.
///
/// This trait allows the developer to define a configuration struct that can:
///
/// - deserialize from an iterator like hashmap or vector.
/// - convert into a service builder and finally build the underlying services.
///
/// Usually, users don't need to use or import this trait directly, they can use `Operator` API instead.
///
/// For example:
///
/// ```
/// # use anyhow::Result;
/// use std::collections::HashMap;
///
/// use opendal::services::MemoryConfig;
/// use opendal::Operator;
/// async fn test() -> Result<()> {
///     let mut cfg = MemoryConfig::default();
///     cfg.root = Some("/".to_string());
///
///     // Build an `Operator` to start operating the storage.
///     let op: Operator = Operator::from_config(cfg)?.finish();
///
///     Ok(())
/// }
/// ```
///
/// Some service builder might contain in memory options like `http_client` . Users can call
/// `into_builder` to convert the configuration into a builder instead.
///
/// ```
/// # use anyhow::Result;
/// use std::collections::HashMap;
///
/// use opendal::raw::HttpClient;
/// use opendal::services::S3Config;
/// use opendal::Configurator;
/// use opendal::Operator;
///
/// async fn test() -> Result<()> {
///     let mut cfg = S3Config::default();
///     cfg.root = Some("/".to_string());
///     cfg.bucket = "test".to_string();
///
///     let builder = cfg.into_builder();
///     let builder = builder.http_client(HttpClient::new()?);
///
///     // Build an `Operator` to start operating the storage.
///     let op: Operator = Operator::new(builder)?.finish();
///
///     Ok(())
/// }
/// ```
pub trait Configurator: Serialize + DeserializeOwned + Debug + 'static {
    /// Associated builder for this configuration.
    type Builder: Builder;

    /// Deserialize from an iterator.
    ///
    /// This API is provided by opendal, developer should not implement it.
    fn from_iter(iter: impl IntoIterator<Item = (String, String)>) -> Result<Self> {
        let cfg = ConfigDeserializer::new(iter.into_iter().collect());

        Self::deserialize(cfg).map_err(|err| {
            Error::new(ErrorKind::ConfigInvalid, "failed to deserialize config").set_source(err)
        })
    }

    /// Convert this configuration into a service builder.
    fn into_builder(self) -> Self::Builder;
}

impl Configurator for () {
    type Builder = ();

    fn into_builder(self) -> Self::Builder {}
}