anvilforge-core 0.3.6

Anvilforge core: routing, middleware, container, request/response, error type, runtime cross-cutting concerns.
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
//! Configuration loading. `.env` via dotenvy + typed config structs in `config/*.rs`.

use std::env;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

/// Cached result of the first `load_dotenv()` call. We do the work exactly
/// once per process — subsequent calls (from `*Config::from_env()`,
/// `TestClient::new()`, or main.rs) hand back the cached path without
/// re-reading the filesystem.
static DOTENV_LOADED: OnceLock<Option<PathBuf>> = OnceLock::new();

/// Load environment variables from the project's `.env` file.
///
/// Walks up from the current working directory looking for a project root
/// marker (`config/anvil.toml`, then `Cargo.toml`) and loads `.env` from that
/// directory only — it does NOT walk further up. This avoids accidentally
/// picking up a parent project's `.env` when the Anvil project is nested
/// inside another codebase.
///
/// **Idempotent.** The first call does the work; subsequent calls return the
/// same cached `Option<PathBuf>`. That's what makes it safe to invoke
/// implicitly from `*Config::from_env()` — tests get a `.env`-loaded process
/// even though they never run `main.rs`.
///
/// Returns the path of the `.env` that was loaded, or `None` if no project
/// root or no `.env` was found. Callers can log this after `tracing_init`.
pub fn load_dotenv() -> Option<PathBuf> {
    DOTENV_LOADED.get_or_init(load_dotenv_impl).clone()
}

fn load_dotenv_impl() -> Option<PathBuf> {
    let cwd = env::current_dir().ok()?;
    let root = find_project_root(&cwd)?;
    let env_path = root.join(".env");
    if !env_path.exists() {
        return None;
    }
    dotenvy::from_path(&env_path).ok()?;
    Some(env_path)
}

/// Walk up from `start` looking for the first directory that contains
/// either `config/anvil.toml` (preferred — Anvil project marker) or
/// `Cargo.toml` (workspace root). Stops at the filesystem root if neither
/// is found.
fn find_project_root(start: &Path) -> Option<PathBuf> {
    let mut dir = start;
    loop {
        if dir.join("config/anvil.toml").exists() {
            return Some(dir.to_path_buf());
        }
        if dir.join("Cargo.toml").exists() {
            return Some(dir.to_path_buf());
        }
        dir = dir.parent()?;
    }
}

#[derive(Debug, Clone)]
pub struct AppConfig {
    pub name: String,
    pub env: String,
    pub key: String,
    pub debug: bool,
    pub url: String,
}

impl AppConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        Self {
            name: env::var("APP_NAME").unwrap_or_else(|_| "Anvil".to_string()),
            env: env::var("APP_ENV").unwrap_or_else(|_| "production".to_string()),
            key: env::var("APP_KEY").unwrap_or_default(),
            debug: env::var("APP_DEBUG")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(false),
            url: env::var("APP_URL").unwrap_or_else(|_| "http://localhost:8080".to_string()),
        }
    }

    pub fn is_local(&self) -> bool {
        self.env == "local" || self.env == "development"
    }
}

/// Database configuration. Mirrors Laravel's `config/database.php`:
///
/// - A `default` connection name (referenced by models, query builder, migrator).
/// - A map of named connections — each with its own URL, pool size, optional
///   read replicas.
///
/// The default `from_env()` impl auto-builds a single `default` connection
/// from `DATABASE_URL` + `DB_POOL`. Apps wanting multiple connections set:
///
/// ```text
/// DB_CONNECTIONS=default,replica,analytics
/// DATABASE_URL=postgres://...                 # the "default" connection
/// DB_REPLICA_URL=postgres://replica/...
/// DB_ANALYTICS_URL=postgres://analytics/...
/// DB_DEFAULT=default
/// ```
#[derive(Debug, Clone)]
pub struct DatabaseConfig {
    pub default: String,
    pub connections: indexmap::IndexMap<String, ConnectionConfig>,
}

/// A single named connection's config.
#[derive(Debug, Clone)]
pub struct ConnectionConfig {
    pub driver: ConnectionDriver,
    /// Write URL (or the only URL if read/write splitting is disabled).
    pub url: String,
    /// Optional comma-separated read replica URLs. If empty, reads use `url`.
    pub read_urls: Vec<String>,
    pub pool_size: u32,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionDriver {
    Postgres,
    /// Reserved for v0.2 (MySQL/SQLite drivers).
    Other(String),
}

impl DatabaseConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        // Allow a comma-separated list of connection names via `DB_CONNECTIONS`.
        // Each connection `foo` reads `DB_FOO_URL`, `DB_FOO_POOL`, `DB_FOO_DRIVER`,
        // and `DB_FOO_READ_URLS` (optional). The "default" connection falls back
        // to the legacy `DATABASE_URL` / `DB_POOL` envs for backward compat.
        let names = env::var("DB_CONNECTIONS")
            .map(|s| {
                s.split(',')
                    .map(|t| t.trim().to_string())
                    .filter(|t| !t.is_empty())
                    .collect::<Vec<_>>()
            })
            .unwrap_or_else(|_| vec!["default".to_string()]);

        let default = env::var("DB_DEFAULT").unwrap_or_else(|_| {
            names
                .first()
                .cloned()
                .unwrap_or_else(|| "default".to_string())
        });

        let mut connections = indexmap::IndexMap::new();
        for name in &names {
            let cfg = ConnectionConfig::from_env(name);
            connections.insert(name.clone(), cfg);
        }

        Self {
            default,
            connections,
        }
    }

    /// Convenience: the URL of the default connection.
    pub fn default_url(&self) -> &str {
        self.connections
            .get(&self.default)
            .map(|c| c.url.as_str())
            .unwrap_or("")
    }

    /// Convenience: the pool size of the default connection.
    pub fn default_pool_size(&self) -> u32 {
        self.connections
            .get(&self.default)
            .map(|c| c.pool_size)
            .unwrap_or(10)
    }

    /// Build a simple single-connection config — useful in tests.
    pub fn single(url: impl Into<String>, pool_size: u32) -> Self {
        let mut connections = indexmap::IndexMap::new();
        connections.insert(
            "default".to_string(),
            ConnectionConfig {
                driver: ConnectionDriver::Postgres,
                url: url.into(),
                read_urls: Vec::new(),
                pool_size,
            },
        );
        Self {
            default: "default".to_string(),
            connections,
        }
    }
}

impl ConnectionConfig {
    pub fn from_env(name: &str) -> Self {
        let _ = load_dotenv();
        let prefix = if name == "default" {
            String::new()
        } else {
            format!("DB_{}_", name.to_ascii_uppercase())
        };
        let url = if name == "default" {
            env::var("DATABASE_URL")
                .or_else(|_| env::var(format!("{prefix}URL")))
                .unwrap_or_else(|_| "postgres://postgres:postgres@localhost:5432/anvil".to_string())
        } else {
            env::var(format!("{prefix}URL")).unwrap_or_default()
        };

        let pool_size = if name == "default" {
            env::var("DB_POOL")
                .or_else(|_| env::var(format!("{prefix}POOL")))
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10)
        } else {
            env::var(format!("{prefix}POOL"))
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(10)
        };

        let read_urls = env::var(format!("{prefix}READ_URLS"))
            .map(|s| {
                s.split(',')
                    .map(|t| t.trim().to_string())
                    .filter(|t| !t.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        let driver_str = env::var(format!("{prefix}DRIVER")).unwrap_or_else(|_| {
            // Infer from URL scheme. Currently every supported variant
            // maps to "postgres"; sqlite/mysql detection lives in cast-core.
            let _ = url.starts_with("postgres://") || url.starts_with("postgresql://");
            "postgres".into()
        });
        let driver = match driver_str.as_str() {
            "postgres" | "pgsql" | "pg" => ConnectionDriver::Postgres,
            other => ConnectionDriver::Other(other.to_string()),
        };

        Self {
            driver,
            url,
            read_urls,
            pool_size,
        }
    }
}

#[derive(Debug, Clone)]
pub struct SessionConfig {
    pub driver: String,
    pub lifetime_minutes: i64,
    pub cookie_name: String,
    pub same_site: String,
    pub secure: bool,
}

impl SessionConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        Self {
            driver: env::var("SESSION_DRIVER").unwrap_or_else(|_| "file".to_string()),
            lifetime_minutes: env::var("SESSION_LIFETIME")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(120),
            cookie_name: env::var("SESSION_COOKIE").unwrap_or_else(|_| "anvil_session".to_string()),
            same_site: env::var("SESSION_SAME_SITE").unwrap_or_else(|_| "lax".to_string()),
            secure: env::var("SESSION_SECURE")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(false),
        }
    }
}

#[derive(Debug, Clone)]
pub struct CacheConfig {
    pub driver: String,
    pub ttl_seconds: u64,
}

impl CacheConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        Self {
            driver: env::var("CACHE_DRIVER").unwrap_or_else(|_| "moka".to_string()),
            ttl_seconds: env::var("CACHE_TTL")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(3600),
        }
    }
}

#[derive(Debug, Clone)]
pub struct QueueConfig {
    pub driver: String,
    pub default_queue: String,
}

impl QueueConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        Self {
            driver: env::var("QUEUE_DRIVER").unwrap_or_else(|_| "database".to_string()),
            default_queue: env::var("QUEUE_DEFAULT").unwrap_or_else(|_| "default".to_string()),
        }
    }
}

#[derive(Debug, Clone)]
pub struct MailConfig {
    pub mailer: String,
    pub host: String,
    pub port: u16,
    pub username: String,
    pub password: String,
    pub from_address: String,
    pub from_name: String,
}

impl MailConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        Self {
            mailer: env::var("MAIL_MAILER").unwrap_or_else(|_| "smtp".to_string()),
            host: env::var("MAIL_HOST").unwrap_or_else(|_| "localhost".to_string()),
            port: env::var("MAIL_PORT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(1025),
            username: env::var("MAIL_USERNAME").unwrap_or_default(),
            password: env::var("MAIL_PASSWORD").unwrap_or_default(),
            from_address: env::var("MAIL_FROM_ADDRESS")
                .unwrap_or_else(|_| "hello@example.com".to_string()),
            from_name: env::var("MAIL_FROM_NAME").unwrap_or_else(|_| "Anvil".to_string()),
        }
    }
}

#[derive(Debug, Clone)]
pub struct FilesystemConfig {
    pub default_disk: String,
    pub local_root: String,
}

impl FilesystemConfig {
    pub fn from_env() -> Self {
        let _ = load_dotenv();
        Self {
            default_disk: env::var("FILESYSTEM_DISK").unwrap_or_else(|_| "local".to_string()),
            local_root: env::var("FILESYSTEM_LOCAL_ROOT")
                .unwrap_or_else(|_| "storage/app".to_string()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::find_project_root;
    use std::fs;

    #[test]
    fn finds_root_via_anvil_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        fs::create_dir_all(root.join("config")).unwrap();
        fs::write(root.join("config/anvil.toml"), "").unwrap();
        let nested = root.join("src/foo");
        fs::create_dir_all(&nested).unwrap();
        assert_eq!(find_project_root(&nested), Some(root.to_path_buf()));
    }

    #[test]
    fn finds_root_via_cargo_toml() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        fs::write(root.join("Cargo.toml"), "[package]\nname = \"x\"\n").unwrap();
        let nested = root.join("a/b/c");
        fs::create_dir_all(&nested).unwrap();
        assert_eq!(find_project_root(&nested), Some(root.to_path_buf()));
    }

    #[test]
    fn prefers_anvil_marker_over_outer_cargo_toml() {
        // Anvil project nested inside a non-Anvil Cargo workspace — we want the
        // Anvil project root, not the workspace root.
        let tmp = tempfile::tempdir().unwrap();
        let outer = tmp.path();
        fs::write(outer.join("Cargo.toml"), "").unwrap();
        let anvil = outer.join("apps/web");
        fs::create_dir_all(anvil.join("config")).unwrap();
        fs::write(anvil.join("config/anvil.toml"), "").unwrap();
        fs::write(anvil.join("Cargo.toml"), "").unwrap();
        let cwd = anvil.join("src");
        fs::create_dir_all(&cwd).unwrap();
        // From anvil/src we should hit anvil/ first (it has both markers).
        assert_eq!(find_project_root(&cwd), Some(anvil.clone()));
    }

    #[test]
    fn load_dotenv_is_idempotent_across_calls() {
        // Hammer it; OnceLock should make every call after the first cheap +
        // identical. We can't observe "no FS work" directly, but identical
        // return values across calls is a strong signal.
        let first = super::load_dotenv();
        let second = super::load_dotenv();
        let third = super::load_dotenv();
        assert_eq!(first, second);
        assert_eq!(second, third);
    }

    #[test]
    fn returns_none_outside_any_project() {
        // tempdir() has no Cargo.toml or config/anvil.toml; nothing should match
        // unless an ancestor does. We can't easily isolate ancestors, but we can
        // at least confirm the function doesn't panic on a path with no markers
        // at the starting level by walking from a non-existent ancestor.
        let tmp = tempfile::tempdir().unwrap();
        // Note: a parent of tmp may be a Cargo project (target/, etc.), so we
        // can't assert None here. Instead just exercise the path.
        let _ = find_project_root(tmp.path());
    }
}