gel-dsn 0.2.1

Data-source name (DSN) parser for Gel and PostgreSQL databases.
Documentation
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
//! Parses DSNs for Gel database connections.

mod config;
mod duration;
mod env;
pub mod error;
mod instance_name;
mod param;
mod params;
mod project;

use std::{
    path::{Path, PathBuf},
    sync::{Arc, Mutex},
};

use crate::{
    env::SystemEnvVars, file::SystemFileAccess, user::SystemUserProfile, EnvVar, FileAccess,
    UserProfile,
};
pub use config::*;
use error::Warning;
pub use instance_name::*;
pub use param::*;
pub use params::*;

#[cfg(feature = "unstable")]
pub use env::define_env;

#[cfg(feature = "unstable")]
pub use project::{Project, ProjectDir, ProjectSearchResult};

/// Internal helper to parse a duration string into a `std::time::Duration`.
#[doc(hidden)]
pub fn parse_duration(s: &str) -> Result<std::time::Duration, Box<dyn std::error::Error>> {
    use std::str::FromStr;
    Ok(std::time::Duration::from_micros(
        duration::Duration::from_str(s)?.micros as u64,
    ))
}

/// Internal helper to format a `std::time::Duration` into a duration string.
#[doc(hidden)]
pub fn format_duration(d: &std::time::Duration) -> String {
    duration::Duration::from_micros(d.as_micros() as i64).to_string()
}

fn config_dirs<U: UserProfile>(user: &U) -> Vec<PathBuf> {
    let mut dirs = Vec::new();
    if cfg!(unix) {
        if let Some(dir) = user.config_dir() {
            dirs.push(dir.join("edgedb"));
            dirs.push(dir.join("gel"));
        }
    }
    if cfg!(windows) {
        if let Some(dir) = user.data_local_dir() {
            dirs.push(dir.join("EdgeDB").join("config"));
            dirs.push(dir.join("Gel").join("config"));
        }
    }
    dirs
}

type LoggingFn = Box<dyn Fn(&str) + 'static>;
type WarningFn = Box<dyn Fn(Warning) + 'static>;

#[derive(Default)]
struct Logging {
    tracing: Option<LoggingFn>,
    warning: Option<WarningFn>,
    #[cfg(feature = "log")]
    log_trace: bool,
    #[cfg(feature = "log")]
    log_warning: bool,
}

impl Logging {
    fn trace(&self, message: impl Fn(&dyn Fn(&str))) {
        let mut needs_trace = false;
        #[cfg(feature = "log")]
        let auto_trace = cfg!(feature = "auto-log-trace");

        #[cfg(feature = "log")]
        {
            if self.log_trace || auto_trace {
                needs_trace = log::log_enabled!(log::Level::Trace);
            }
        }

        if self.tracing.is_some() {
            needs_trace = true;
        }

        if needs_trace {
            message(&|message| {
                #[cfg(feature = "log")]
                {
                    if self.log_trace || auto_trace {
                        log::trace!("{}", message);
                    }
                }
                {
                    if let Some(tracing) = &self.tracing {
                        tracing(message);
                    }
                }
            });
        }
    }

    fn warn(&self, warning: Warning) {
        #[cfg(feature = "log")]
        {
            let auto_warning = cfg!(feature = "auto-log-warning");
            if self.log_warning || auto_warning {
                log::warn!("{}", warning);
            }
        }
        if let Some(warning_fn) = &self.warning {
            warning_fn(warning);
        }
    }
}

/// A collection of warnings.
///
/// To collect warnings from a [`Builder`], pass a [`Warnings`] instance to the
/// [`Builder::with_warnings`] method:
///
/// ```
/// # use gel_dsn::gel::*;
/// let warnings = Warnings::default();
/// let builder = Builder::new().without_system().with_warning(warnings.clone().warn_fn());
/// ```
#[derive(Default, Clone)]
pub struct Warnings {
    warnings: Arc<Mutex<Vec<Warning>>>,
}

impl Warnings {
    pub fn into_vec(self) -> Vec<Warning> {
        match Arc::try_unwrap(self.warnings) {
            Ok(mutex) => mutex.into_inner().unwrap(),
            Err(arc) => arc.lock().unwrap().clone(),
        }
    }

    pub fn warn(&self, warning: Warning) {
        let mut warnings = self.warnings.lock().unwrap();
        warnings.push(warning);
    }

    pub fn warn_fn(self) -> WarningFn {
        Box::new(move |warning| self.warn(warning))
    }
}

/// A collection of trace messages.
///
/// To collect traces from a [`Builder`], pass a [`Traces`] instance to the
/// `Builder`'s [`with_tracing`] method:
///
/// ```
/// # use gel_dsn::gel::*;
/// let traces = Traces::default();
/// let builder = Builder::new().without_system().with_tracing(traces.clone().trace_fn());
/// ```
#[derive(Default, Clone)]
pub struct Traces {
    traces: Arc<Mutex<Vec<String>>>,
}

impl Traces {
    pub fn into_vec(self) -> Vec<String> {
        match Arc::try_unwrap(self.traces) {
            Ok(mutex) => mutex.into_inner().unwrap(),
            Err(arc) => arc.lock().unwrap().clone(),
        }
    }

    pub fn trace(&self, message: &str) {
        let mut traces = self.traces.lock().unwrap();
        traces.push(message.to_string());
    }

    pub fn trace_fn(self) -> LoggingFn {
        Box::new(move |message| self.trace(message))
    }
}

struct BuildContextImpl<E: EnvVar = SystemEnvVars, F: FileAccess = SystemFileAccess> {
    env: E,
    files: F,
    pub config_dir: Option<Vec<PathBuf>>,
    pub(crate) logging: Logging,
}

impl Default for BuildContextImpl<SystemEnvVars, SystemFileAccess> {
    fn default() -> Self {
        Self::new()
    }
}

impl BuildContextImpl<SystemEnvVars, SystemFileAccess> {
    /// Create a new build context with default values.
    pub fn new() -> Self {
        Self {
            env: SystemEnvVars,
            files: SystemFileAccess,
            config_dir: Some(config_dirs(&SystemUserProfile)),
            logging: Logging::default(),
        }
    }
}

impl<E: EnvVar, F: FileAccess> BuildContextImpl<E, F> {
    /// Create a new build context with default values.
    pub fn new_with_user_profile<U: UserProfile>(env: E, files: F, user: U) -> Self {
        let config_dir = config_dirs(&user);
        Self {
            env,
            files,
            config_dir: Some(config_dir),
            logging: Logging::default(),
        }
    }

    #[cfg(test)]
    /// Create a new build context with default values.
    pub fn new_with(env: E, files: F) -> Self {
        Self {
            env,
            files,
            config_dir: None,
            logging: Logging::default(),
        }
    }
}

macro_rules! context_trace {
    ($context:expr, $message:expr $(, $arg:expr)*) => {
        $context.trace(|f: &dyn Fn(&str)| f(&format!($message, $($arg),*)));
    };
}

pub(crate) use context_trace;

pub(crate) trait BuildContext {
    type EnvVar: EnvVar;
    fn env(&self) -> &impl EnvVar;
    fn cwd(&self) -> Option<PathBuf>;
    fn files(&self) -> &impl FileAccess;
    fn warn(&mut self, warning: error::Warning);
    fn read_config_file<T: FromParamStr>(
        &mut self,
        path: impl AsRef<Path>,
    ) -> Result<Option<T>, T::Err>;
    fn find_config_path(&self, path: impl AsRef<Path>) -> std::io::Result<PathBuf>;
    fn read_env<'a, 'b, 'c, T: FromParamStr>(
        &'c mut self,
        env: impl Fn(&'b mut Self) -> Result<Option<T>, error::ParseError>,
    ) -> Result<Option<T>, error::ParseError>
    where
        Self::EnvVar: 'a,
        'c: 'a,
        'c: 'b;
    fn trace(&self, message: impl Fn(&dyn Fn(&str)));
}

impl<E: EnvVar, F: FileAccess> BuildContext for BuildContextImpl<E, F> {
    type EnvVar = E;
    fn env(&self) -> &impl EnvVar {
        &self.env
    }

    fn cwd(&self) -> Option<PathBuf> {
        self.files.cwd()
    }

    fn files(&self) -> &impl FileAccess {
        &self.files
    }

    fn warn(&mut self, warning: error::Warning) {
        self.logging.warn(warning);
    }

    fn read_config_file<T: FromParamStr>(
        &mut self,
        path: impl AsRef<Path>,
    ) -> Result<Option<T>, T::Err> {
        for config_dir in self.config_dir.iter().flatten() {
            let path = config_dir.join(path.as_ref());
            context_trace!(self, "Reading config file: {}", path.display());
            if let Ok(file) = self.files.read(&path) {
                // TODO?
                let res = T::from_param_str(&file, self);
                context_trace!(
                    self,
                    "File content: {:?}",
                    res.as_ref().map(|_| ()).map_err(|_| ())
                );
                return match res {
                    Ok(value) => Ok(Some(value)),
                    Err(e) => Err(e),
                };
            }
        }

        Ok(None)
    }

    fn find_config_path(&self, path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
        for config_dir in self.config_dir.iter().flatten() {
            context_trace!(self, "Checking config path: {}", config_dir.display());
            if matches!(self.files.exists_dir(&config_dir), Ok(true)) {
                return Ok(config_dir.join(path));
            }
        }

        // If we couldn't find an existing one, use the first config dir
        if let Some(config_dir) = self.config_dir.iter().flatten().next() {
            return Ok(config_dir.join(path));
        }

        Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "Config file not found",
        ))
    }

    fn read_env<'a, 'b, 'c, T: FromParamStr>(
        &'c mut self,
        env: impl Fn(&'b mut Self) -> Result<Option<T>, error::ParseError>,
    ) -> Result<Option<T>, error::ParseError>
    where
        Self::EnvVar: 'a,
        'c: 'a,
        'c: 'b,
    {
        let res = env(self);
        match res {
            Ok(Some(value)) => Ok(Some(value)),
            Ok(None) => Ok(None),
            Err(e) => Err(e),
        }
    }

    fn trace(&self, message: impl Fn(&dyn Fn(&str))) {
        self.logging.trace(message);
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;
    use crate::host::{Host, HostType};
    use std::{collections::HashMap, time::Duration};

    #[test]
    fn test_parse() {
        let cfg = Builder::default()
            .dsn("edgedb://hostname:1234")
            .without_system()
            .build();

        assert_eq!(
            cfg.unwrap(),
            Config {
                host: Host::new(HostType::try_from_str("hostname").unwrap(), 1234,),
                ..Default::default()
            }
        );
    }

    #[test]
    fn test_credentials_file() {
        let credentials = json!({
            "port": 10702,
            "user": "test3n",
            "password": "lZTBy1RVCfOpBAOwSCwIyBIR",
            "database": "test3n"
        });

        let credentials_file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(credentials_file.path(), credentials.to_string()).unwrap();

        let credentials = Builder::new()
            .credentials_file(credentials_file.path())
            .with_fs()
            .build()
            .expect("Failed to build credentials");

        assert_eq!(credentials.host, Host::new(DEFAULT_HOST.clone(), 10702));
        assert_eq!(&credentials.user, "test3n");
        assert_eq!(
            credentials.db,
            DatabaseBranch::Database("test3n".to_string())
        );
        assert_eq!(
            credentials.authentication,
            Authentication::Password("lZTBy1RVCfOpBAOwSCwIyBIR".into())
        );
    }

    #[test]
    fn test_schemes() {
        let dsn_schemes = ["edgedb", "gel"];
        for dsn_scheme in dsn_schemes {
            let cfg = Builder::new()
                .dsn(format!("{dsn_scheme}://localhost:1756"))
                .build()
                .unwrap();

            let host = cfg.host.target_name().unwrap();
            assert_eq!(host.host(), Some("localhost".into()));
            assert_eq!(host.port(), Some(1756));
        }
    }

    #[test]
    fn test_unix_path() {
        // Test unix path without a port
        let cfg = Builder::new()
            .unix_path("/test/.s.EDGEDB.8888")
            .build()
            .unwrap();

        let host = cfg.host.target_name().unwrap();
        assert_eq!(host.path(), Some(Path::new("/test/.s.EDGEDB.8888")));

        // Test unix path with a port
        let cfg = Builder::new()
            .port(8888)
            .unix_path("/test")
            .build()
            .unwrap();
        let host = cfg.host.target_name().unwrap();
        assert_eq!(host.path(), Some(Path::new("/test")));

        // Test unix path with a port
        let cfg = Builder::new()
            .port(8888)
            .unix_path(UnixPath::with_port_suffix(PathBuf::from("/prefix.")))
            .build()
            .unwrap();
        let host = cfg.host.target_name().unwrap();
        assert_eq!(host.path(), Some(Path::new("/prefix.8888")));
    }

    /// Test that the hidden CloudCerts env var is parsed correctly.
    #[test]
    fn test_cloud_certs() {
        let cloud_cert =
            HashMap::from_iter([("_GEL_CLOUD_CERTS".to_string(), "local".to_string())]);
        let cfg = Builder::new()
            .port(5656)
            .without_system()
            .with_env_impl(cloud_cert)
            .build()
            .unwrap();
        assert_eq!(cfg.cloud_certs, Some(CloudCerts::Local));
    }

    #[test]
    fn test_tcp_keepalive() {
        let cfg = Builder::new()
            .port(5656)
            .tcp_keepalive(TcpKeepalive::Explicit(Duration::from_secs(10)))
            .without_system()
            .build()
            .unwrap();
        assert_eq!(
            cfg.tcp_keepalive,
            TcpKeepalive::Explicit(Duration::from_secs(10))
        );
    }
}