gel-dsn 0.2.11

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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Parses DSNs for Gel database connections.

mod branding;
mod config;
mod credentials;
mod duration;
mod env;
pub mod error;
mod instance_name;
mod param;
mod params;
mod project;
mod stored;

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

use crate::{
    env::SystemEnvVars, file::SystemFileAccess, user::SystemUserProfile, EnvVar, FileAccess,
    UserProfile,
};
pub use config::*;
pub use credentials::*;
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};

#[cfg(feature = "unstable")]
pub use stored::{InstancePaths, StoredCredentials, StoredInformation, SystemPaths};

/// 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()
}

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

#[derive(Default)]
pub(crate) 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))
    }
}

pub(crate) struct BuildContextImpl<E: EnvVar = SystemEnvVars, F: FileAccess = SystemFileAccess> {
    env: E,
    files: F,
    paths: ResolvedPaths,
    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,
            paths: ResolvedPaths::new(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 {
        Self {
            env,
            files,
            paths: ResolvedPaths::new(user),
            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,
            paths: ResolvedPaths::default(),
            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;

mod sealed {
    #![allow(private_interfaces, private_bounds)]

    use super::{FileAccess, FromParamStr, UserProfile, Warning};
    use std::path::{Path, PathBuf};

    #[derive(Debug, Clone, Default)]
    pub struct ResolvedPaths {
        pub username: Option<String>,
        pub homedir: Option<PathBuf>,
        pub cache_dir: Option<PathBuf>,
        pub config_dir: Option<PathBuf>,
        pub data_dir: Option<PathBuf>,
        pub data_local_dir: Option<PathBuf>,
        pub config_dirs: Vec<PathBuf>,
    }

    impl ResolvedPaths {
        pub fn new<U: UserProfile>(user: U) -> Self {
            Self {
                username: user.username().map(|s| s.to_string()),
                homedir: user.homedir().map(|p| p.to_path_buf()),
                cache_dir: user.cache_dir().map(|p| p.to_path_buf()),
                config_dir: user.config_dirs().first().map(|p| p.to_path_buf()),
                data_dir: user.data_dir().map(|p| p.to_path_buf()),
                data_local_dir: user.data_local_dir().map(|p| p.to_path_buf()),
                config_dirs: user
                    .config_dirs()
                    .into_iter()
                    .map(|p| p.to_path_buf())
                    .collect(),
            }
        }
    }

    pub trait BuildContext {
        fn cwd(&self) -> Option<PathBuf>;
        fn files(&self) -> &impl FileAccess;
        fn paths(&self) -> &ResolvedPaths;
        fn warn(&self, warning: Warning);
        fn read_config_file<T: FromParamStr>(
            &self,
            path: impl AsRef<Path>,
        ) -> Result<Option<T>, T::Err>;
        fn write_config_file(
            &self,
            path: impl AsRef<Path>,
            content: &str,
        ) -> Result<(), std::io::Error>;
        fn delete_config_file(&self, path: impl AsRef<Path>) -> Result<(), std::io::Error>;
        fn find_config_path(&self, path: impl AsRef<Path>) -> std::io::Result<PathBuf>;
        fn list_config_files(&self, path: impl AsRef<Path>)
            -> Result<Vec<PathBuf>, std::io::Error>;
        fn read_env(&self, name: &str) -> Result<std::borrow::Cow<str>, std::env::VarError>;
        fn trace(&self, message: impl Fn(&dyn Fn(&str)));
    }
}

use sealed::{BuildContext, ResolvedPaths};

impl<E: EnvVar, F: FileAccess> BuildContext for BuildContextImpl<E, F> {
    fn cwd(&self) -> Option<PathBuf> {
        self.files.cwd()
    }

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

    fn paths(&self) -> &ResolvedPaths {
        &self.paths
    }

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

    fn read_config_file<T: FromParamStr>(
        &self,
        path: impl AsRef<Path>,
    ) -> Result<Option<T>, T::Err> {
        for config_dir in &self.paths.config_dirs {
            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 write_config_file(
        &self,
        path: impl AsRef<Path>,
        content: &str,
    ) -> Result<(), std::io::Error> {
        let path = path.as_ref();

        // Attempt to write to the first existing config directory.
        for config_dir in &self.paths.config_dirs {
            if !self.files.exists_dir(config_dir)? {
                continue;
            }
            let path = config_dir.join(path);
            context_trace!(self, "Writing config file: {}", path.display());
            self.files.write(&path, content)?;
            return Ok(());
        }

        // If we couldn't find an existing one, use the first config dir
        if let Some(config_dir) = self.paths.config_dirs.first() {
            context_trace!(self, "Writing config file: {}", path.display());
            let path = config_dir.join(path);
            self.files.write(&path, content)?;
            Ok(())
        } else {
            Err(std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "Config path not found",
            ))
        }
    }

    /// Delete a configuration file. If the file does not exist, this is a no-op.
    fn delete_config_file(&self, path: impl AsRef<Path>) -> Result<(), std::io::Error> {
        let path = path.as_ref();
        let mut res = Ok(());

        // Attempt to delete from all configuration directories, ignoring
        // non-existent files.
        for config_dir in &self.paths.config_dirs {
            let path = config_dir.join(path);
            context_trace!(self, "Deleting config file: {}", path.display());
            if let Err(e) = self.files.delete(&path) {
                if e.kind() == std::io::ErrorKind::NotFound {
                    continue;
                }
                context_trace!(self, "Failed to delete config file: {}", e);
                res = Err(e);
            }
        }

        res
    }

    fn list_config_files(&self, path: impl AsRef<Path>) -> Result<Vec<PathBuf>, std::io::Error> {
        let mut files = Vec::new();
        for config_dir in &self.paths.config_dirs {
            let path = config_dir.join(path.as_ref());
            context_trace!(self, "Checking config path: {}", path.display());
            match self.files.list_dir(&path) {
                Ok(file_list) => {
                    for file in file_list {
                        context_trace!(self, "Found config file: {}", file.display());
                        files.push(file);
                    }
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
                Err(e) => return Err(e),
            }
        }

        Ok(files)
    }

    fn find_config_path(&self, path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
        for config_dir in &self.paths.config_dirs {
            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.paths.config_dirs.first() {
            return Ok(config_dir.join(path));
        }

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

    fn read_env(&self, name: &str) -> Result<std::borrow::Cow<str>, std::env::VarError> {
        self.env.read(name)
    }

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