Skip to main content

server/db/
url.rs

1use super::DBError;
2use std::sync::OnceLock;
3
4/// The admin database URL: set explicitly once, otherwise read from
5/// `DATABASE_URL` on first use. The first resolution is final.
6pub(super) struct UrlSource {
7    resolved: OnceLock<Option<String>>,
8}
9
10impl UrlSource {
11    pub(super) const fn new() -> Self {
12        Self {
13            resolved: OnceLock::new(),
14        }
15    }
16
17    pub(super) fn set(&self, url: String) -> Result<(), DBError> {
18        self.resolved
19            .set(Some(url))
20            .map_err(|_| DBError::UrlAlreadyResolved)
21    }
22
23    pub(super) fn get_or_env(&self, env: impl FnOnce() -> Option<String>) -> Option<&str> {
24        self.resolved.get_or_init(env).as_deref()
25    }
26}
27
28static DB_URL: UrlSource = UrlSource::new();
29
30fn env_url() -> Option<String> {
31    std::env::var("DATABASE_URL").ok()
32}
33
34/// Makes `url` the admin database URL instead of `DATABASE_URL`.
35///
36/// # Errors
37/// [`DBError::UrlAlreadyResolved`] if a URL was already set or any code
38/// already resolved the URL from the environment.
39pub fn use_url(url: String) -> Result<(), DBError> {
40    DB_URL.set(url)
41}
42
43/// The admin database URL the server was configured with.
44///
45/// # Errors
46/// [`DBError::MissingUrl`] if no URL was set and `DATABASE_URL` is unset.
47pub fn admin_database_url() -> Result<String, DBError> {
48    current_url().map(str::to_owned).ok_or(DBError::MissingUrl)
49}
50
51pub(super) fn current_url() -> Option<&'static str> {
52    DB_URL.get_or_env(env_url)
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    fn env(url: &'static str) -> impl FnOnce() -> Option<String> {
60        move || Some(url.to_owned())
61    }
62
63    #[test]
64    fn explicit_url_wins_over_env() {
65        let source = UrlSource::new();
66        assert!(source.set("postgres://explicit/db".into()).is_ok());
67        assert_eq!(
68            source.get_or_env(env("postgres://env/db")),
69            Some("postgres://explicit/db")
70        );
71    }
72
73    #[test]
74    fn env_is_used_when_nothing_was_set() {
75        let source = UrlSource::new();
76        assert_eq!(
77            source.get_or_env(env("postgres://env/db")),
78            Some("postgres://env/db")
79        );
80    }
81
82    #[test]
83    fn missing_everywhere_resolves_to_none() {
84        let source = UrlSource::new();
85        assert_eq!(source.get_or_env(|| None), None);
86    }
87
88    #[test]
89    fn second_set_is_refused() {
90        let source = UrlSource::new();
91        assert!(source.set("postgres://a/db".into()).is_ok());
92        assert!(matches!(
93            source.set("postgres://b/db".into()),
94            Err(DBError::UrlAlreadyResolved)
95        ));
96        assert_eq!(source.get_or_env(|| None), Some("postgres://a/db"));
97    }
98
99    #[test]
100    fn set_after_first_use_is_refused() {
101        let source = UrlSource::new();
102        assert_eq!(
103            source.get_or_env(env("postgres://env/db")),
104            Some("postgres://env/db")
105        );
106        assert!(matches!(
107            source.set("postgres://late/db".into()),
108            Err(DBError::UrlAlreadyResolved)
109        ));
110    }
111}