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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
mod convert;
mod daemon;

pub use convert::convert_network_identifier;
pub use daemon::DaemonConfig;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IpfsRemote {
    pub host: String,
}

impl Default for IpfsRemote {
    fn default() -> Self {
        Self {
            host: "/ipfs".to_string(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Ipfs {
    Bundled,
    Remote(IpfsRemote),
}

impl std::fmt::Display for Ipfs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bundled => write!(f, "Bundled"),
            Self::Remote(_) => write!(f, "Remote"),
        }
    }
}

impl Default for Ipfs {
    fn default() -> Self {
        Self::Bundled
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct S3StateStore {
    pub bucket: String,
    pub endpoint: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum StateStore {
    S3(S3StateStore),
    LocalDirectory(PathBuf),
}

impl Default for StateStore {
    fn default() -> Self {
        Self::LocalDirectory(PathBuf::from("/etc/ceramic/data"))
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct HttpApi {
    pub hostname: String,
    pub port: u16,
    pub cors_allowed_origins: Vec<String>,
    pub admin_dids: Vec<String>,
}

impl Default for HttpApi {
    fn default() -> Self {
        Self {
            hostname: std::net::Ipv4Addr::LOCALHOST.to_string(),
            port: 7007,
            cors_allowed_origins: vec![],
            admin_dids: vec![],
        }
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum NetworkIdentifier {
    InMemory,
    Local,
    Dev,
    Clay,
    Mainnet,
}

impl std::fmt::Display for NetworkIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InMemory => write!(f, "InMemory"),
            Self::Local => write!(f, "Local"),
            Self::Dev => write!(f, "Dev"),
            Self::Clay => write!(f, "Clay"),
            Self::Mainnet => write!(f, "Mainnet"),
        }
    }
}

impl Default for NetworkIdentifier {
    fn default() -> Self {
        Self::Clay
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Network {
    pub id: NetworkIdentifier,
    pub pubsub_topic: Option<String>,
}

impl Default for Network {
    fn default() -> Self {
        Self {
            id: NetworkIdentifier::default(),
            pubsub_topic: None,
        }
    }
}

impl Network {
    pub fn new(id: &NetworkIdentifier, name: &str) -> Self {
        let topic = if NetworkIdentifier::Local == *id {
            Some(format!("/ceramic/local-topic-{}", name))
        } else {
            None
        };
        Self {
            id: *id,
            pubsub_topic: topic,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Anchor {
    None,
    Ip {
        url: String,
    },
    RemoteDid {
        url: String,
        private_seed_url: String,
    },
}

impl Default for Anchor {
    fn default() -> Self {
        Self::None
    }
}

impl Anchor {
    pub fn url_for_network(id: &NetworkIdentifier) -> Option<String> {
        match id {
            NetworkIdentifier::InMemory => None,
            NetworkIdentifier::Local | NetworkIdentifier::Dev => {
                Some("https://cas-qa.3boxlabs.com/".to_string())
            }
            NetworkIdentifier::Clay => Some("https://cas-clay.3boxlabs.com/".to_string()),
            NetworkIdentifier::Mainnet => Some("https://cas.3boxlabs.com/".to_string()),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Indexing {
    pub db: String,
    pub allow_queries_before_historical_sync: bool,
    pub enable_historical_sync: bool,
}

impl Default for Indexing {
    fn default() -> Self {
        Self {
            db: Indexing::postgres_default().to_string(),
            allow_queries_before_historical_sync: true,
            enable_historical_sync: false,
        }
    }
}

impl Indexing {
    pub fn postgres_default() -> &'static str {
        "postgres://ceramic:password@localhost:5432/ceramic"
    }

    pub fn is_sqlite(&self) -> bool {
        self.db.starts_with("sqlite")
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum DidResolvers {
    Ethr(HashMap<String, serde_json::Value>),
}

impl Default for DidResolvers {
    fn default() -> Self {
        Self::Ethr(HashMap::default())
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Node {
    pub gateway: bool,
    pub sync_override: bool,
    pub stream_cache_limit: usize,
}

impl Default for Node {
    fn default() -> Self {
        Self {
            gateway: false,
            sync_override: false,
            stream_cache_limit: 100,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FileLogger {
    pub enabled: bool,
    pub directory: PathBuf,
}

impl Default for FileLogger {
    fn default() -> Self {
        Self {
            enabled: true,
            directory: PathBuf::from("./log/ceramic"),
        }
    }
}

#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
pub enum LogLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

impl Default for LogLevel {
    fn default() -> Self {
        Self::Info
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Logger {
    pub file: Option<FileLogger>,
    pub level: LogLevel,
}

impl Default for Logger {
    fn default() -> Self {
        Self {
            file: Some(FileLogger::default()),
            level: LogLevel::default(),
        }
    }
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum Metrics {
    Disabled,
    Enabled(String),
}

impl Default for Metrics {
    fn default() -> Self {
        Self::Disabled
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Config {
    pub ipfs: Ipfs,
    pub state_store: StateStore,
    pub http_api: HttpApi,
    pub network: Network,
    pub anchor: Anchor,
    pub indexing: Indexing,
    pub did_resolvers: DidResolvers,
    pub node: Node,
    pub logger: Logger,
    pub metrics: Metrics,
}

pub struct CasAuth {
    pub url: String,
    pub pk: Option<String>,
}

impl Config {
    pub fn new(id: &NetworkIdentifier, name: &str, cas_auth: Option<CasAuth>) -> Self {
        let mut cfg = Self::default();
        cfg.initialize(id, name, cas_auth);
        cfg
    }

    pub fn initialize(
        &mut self,
        id: &NetworkIdentifier,
        name: &str,
        cas_auth: Option<CasAuth>,
    ) -> &mut Self {
        self.network = Network::new(id, name);
        self.anchor = if let Some(auth) = cas_auth {
            if let Some(p) = auth.pk {
                Anchor::RemoteDid {
                    url: auth.url,
                    private_seed_url: p,
                }
            } else {
                Anchor::Ip { url: auth.url }
            }
        } else {
            Anchor::None
        };
        if NetworkIdentifier::Mainnet == *id {
            self.indexing.enable_historical_sync = true;
        }
        self
    }
}

impl Config {
    pub fn eth_resolver_options(&self) -> Option<String> {
        let DidResolvers::Ethr(m) = &self.did_resolvers;
        Some(serde_json::to_string(m).unwrap_or_else(|_| String::default()))
    }

    pub fn allows_sqlite(&self) -> bool {
        self.network.id != NetworkIdentifier::Mainnet
    }
}

pub fn from_file_err(file: String) -> anyhow::Result<Config> {
    let data = std::fs::read(PathBuf::from(file))?;
    Ok(serde_json::from_slice(data.as_slice())?)
}

pub fn from_string_err(json: &str) -> anyhow::Result<Config> {
    Ok(serde_json::from_str(json)?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn should_roundtrip_default_config() {
        let js = serde_json::to_string(&Config::default()).unwrap();
        let _: Config = serde_json::from_str(&js).unwrap();
    }
}