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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
mod convert;
mod daemon;

pub use daemon::DaemonConfig;

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

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IpfsRemote {
    #[wasm_bindgen(getter_with_clone)]
    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
    }
}

#[wasm_bindgen]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct S3StateStore {
    #[wasm_bindgen(getter_with_clone)]
    pub bucket: String,
    #[wasm_bindgen(getter_with_clone)]
    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"))
    }
}

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

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

#[wasm_bindgen]
#[derive(Clone, 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
    }
}

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

impl Default for Network {
    fn default() -> Self {
        Self::dev()
    }
}

impl Network {
    pub fn in_memory() -> Self {
        Self {
            id: NetworkIdentifier::InMemory,
            pubsub_topic: None,
        }
    }
    pub fn local(name: &str) -> Self {
        Self {
            id: NetworkIdentifier::Local,
            pubsub_topic: Some(format!("/ceramic/local-topic-{}", name)),
        }
    }

    pub fn dev() -> Self {
        Self {
            id: NetworkIdentifier::Dev,
            pubsub_topic: None, //"/ceramic/dev-unstable".to_string(),
        }
    }

    pub fn clay() -> Self {
        Self {
            id: NetworkIdentifier::Clay,
            pubsub_topic: None, //"/ceramic/testnet-clay".to_string(),
        }
    }

    pub fn mainnet() -> Self {
        Self {
            id: NetworkIdentifier::Mainnet,
            pubsub_topic: None, //"/ceramic/mainnet".to_string(),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Anchor {
    #[wasm_bindgen(getter_with_clone)]
    pub anchor_service_url: String,
    #[wasm_bindgen(getter_with_clone)]
    pub ethereum_rpc_url: String,
}

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

impl Anchor {
    pub fn in_memory() -> Self {
        Self {
            anchor_service_url: "https://localhost:8081/".to_string(),
            ethereum_rpc_url: "http://localhost:7545".to_string(),
        }
    }

    pub fn local() -> Self {
        Self {
            anchor_service_url: "https://cas-qa.3boxlabs.com/".to_string(),
            ethereum_rpc_url: "http://localhost:7545".to_string(),
        }
    }

    pub fn dev() -> Self {
        Self {
            anchor_service_url: "https://cas-qa.3boxlabs.com/".to_string(),
            ethereum_rpc_url: "http://localhost:7545".to_string(),
        }
    }

    pub fn clay() -> Self {
        Self {
            anchor_service_url: "https://cas-clay.3boxlabs.com/".to_string(),
            ethereum_rpc_url: "http://localhost:7545".to_string(),
        }
    }

    pub fn mainnet() -> Self {
        Self {
            anchor_service_url: "https://cas.3boxlabs.com/".to_string(),
            ethereum_rpc_url: "http://localhost:7545".to_string(),
        }
    }
}

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

impl Default for Indexing {
    fn default() -> Self {
        Self {
            db: "postgres://ceramic:password@localhost:5432/ceramic".to_string(),
            allow_queries_before_historical_sync: true,
            enable_historical_sync: false,
        }
    }
}

#[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())
    }
}

#[wasm_bindgen]
#[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"),
        }
    }
}

#[wasm_bindgen]
#[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(),
        }
    }
}

#[wasm_bindgen]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Metrics {
    pub enabled: bool,
    #[wasm_bindgen(getter_with_clone)]
    pub host: String,
}

impl Default for Metrics {
    fn default() -> Self {
        Self {
            enabled: false,
            host: "???".to_string(),
        }
    }
}

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

impl Config {
    pub fn in_memory(&mut self) -> &mut Self {
        self.anchor = Anchor::in_memory();
        self.network = Network::in_memory();
        self
    }

    pub fn local(&mut self, name: &str) -> &mut Self {
        self.anchor = Anchor::local();
        self.network = Network::local(name);
        self
    }

    pub fn dev(&mut self) -> &mut Self {
        self.anchor = Anchor::dev();
        self.network = Network::dev();
        self
    }

    pub fn test(&mut self) -> &mut Self {
        self.anchor = Anchor::clay();
        self.network = Network::clay();
        self
    }

    pub fn production(&mut self) -> &mut Self {
        self.anchor = Anchor::mainnet();
        self.network = Network::mainnet();
        self.indexing.enable_historical_sync = true;
        self.node.gateway = true;
        self
    }
}

#[wasm_bindgen]
#[derive(Clone)]
pub struct WasmFileLogger {
    pub enabled: bool,
    #[wasm_bindgen(getter_with_clone)]
    pub directory: String,
}

#[wasm_bindgen]
pub struct WasmLogger {
    #[wasm_bindgen(getter_with_clone)]
    pub file: Option<WasmFileLogger>,
    pub level: LogLevel,
}

#[wasm_bindgen]
pub struct WasmIpfs {
    #[wasm_bindgen(getter_with_clone)]
    pub remote: Option<IpfsRemote>,
}

#[wasm_bindgen]
pub struct WasmStateStore {
    #[wasm_bindgen(getter_with_clone)]
    pub local_directory: Option<String>,
    #[wasm_bindgen(getter_with_clone)]
    pub s3: Option<S3StateStore>,
}

#[wasm_bindgen]
impl Config {
    pub fn ipfs(&self) -> WasmIpfs {
        if let Ipfs::Remote(remote) = &self.ipfs {
            WasmIpfs {
                remote: Some(remote.clone()),
            }
        } else {
            WasmIpfs { remote: None }
        }
    }

    pub fn cors_allowed_origins(&self) -> Vec<JsValue> {
        self.http_api
            .cors_allowed_origins
            .iter()
            .map(JsValue::from)
            .collect()
    }

    pub fn admin_dids(&self) -> Vec<JsValue> {
        self.http_api.admin_dids.iter().map(JsValue::from).collect()
    }

    pub fn state_store(&self) -> WasmStateStore {
        match &self.state_store {
            StateStore::LocalDirectory(dir) => WasmStateStore {
                local_directory: Some(dir.to_string_lossy().to_string()),
                s3: None,
            },
            StateStore::S3(s3) => WasmStateStore {
                local_directory: None,
                s3: Some(s3.clone()),
            },
        }
    }

    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 logger(&self) -> WasmLogger {
        WasmLogger {
            level: self.logger.level,
            file: self.logger.file.as_ref().map(|f| WasmFileLogger {
                enabled: f.enabled,
                directory: f.directory.to_string_lossy().to_string(),
            }),
        }
    }

    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)?)
}

#[wasm_bindgen]
pub fn from_file(file: String) -> Result<Config, JsValue> {
    from_file_err(file).map_err(|e| JsValue::from(e.to_string()))
}

#[wasm_bindgen]
pub fn from_string(json: String) -> Result<Config, JsValue> {
    from_string_err(&json).map_err(|e| JsValue::from(e.to_string()))
}

#[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();
    }
}