atrg-core 0.2.1

Core framework: AppState, config, app builder for at-rust-go
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
//! Application state shared across all Axum handlers.

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;

use atrg_db::DbPool;

use crate::config::Config;
use atrg_identity::IdentityResolver;

// ---------------------------------------------------------------------------
// Extensions — a type-erased map for app-specific state
// ---------------------------------------------------------------------------

/// A type-erased container for app-specific state.
///
/// `Extensions` lets applications attach arbitrary typed values to
/// [`AppState`] without modifying the framework. Each type can appear at most
/// once — the type itself is the key.
///
/// # Examples
///
/// ```rust
/// use atrg_core::Extensions;
///
/// struct S3Client { bucket: String }
/// struct SmtpConfig { host: String }
///
/// let mut ext = Extensions::new();
/// ext.insert(S3Client { bucket: "my-blobs".into() });
/// ext.insert(SmtpConfig { host: "smtp.example.com".into() });
///
/// assert_eq!(ext.get::<S3Client>().expect("registered").bucket, "my-blobs");
/// assert_eq!(ext.get::<SmtpConfig>().expect("registered").host, "smtp.example.com");
/// assert!(ext.get::<u64>().is_none());
/// ```
#[derive(Default)]
pub struct Extensions {
    map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl Extensions {
    /// Create a new, empty extensions map.
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }

    /// Insert a value into the map. If a value of this type already exists,
    /// it is replaced and the old value is returned.
    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
        self.map
            .insert(TypeId::of::<T>(), Box::new(value))
            .and_then(|boxed| boxed.downcast::<T>().ok().map(|b| *b))
    }

    /// Retrieve a reference to a value by type. Returns `None` if the type
    /// has not been inserted.
    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.map
            .get(&TypeId::of::<T>())
            .and_then(|boxed| boxed.downcast_ref::<T>())
    }

    /// Returns `true` if the map contains a value of the given type.
    pub fn contains<T: Send + Sync + 'static>(&self) -> bool {
        self.map.contains_key(&TypeId::of::<T>())
    }

    /// Returns the number of entries in the map.
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the map is empty.
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }
}

// Manual Debug impl because `dyn Any` is not Debug.
impl std::fmt::Debug for Extensions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Extensions")
            .field("len", &self.map.len())
            .finish_non_exhaustive()
    }
}

// ---------------------------------------------------------------------------
// AppState
// ---------------------------------------------------------------------------

/// Shared application state passed to every Axum handler.
///
/// This is the central state object that every route handler receives via
/// `axum::extract::State<AppState>`. It holds the parsed configuration,
/// database connection pool, and a shared HTTP client for outbound requests.
///
/// `AppState` is cheaply cloneable — all inner fields are either `Arc`-wrapped
/// or already use internal reference counting (e.g. sqlx pools, `reqwest::Client`).
#[derive(Clone)]
pub struct AppState {
    /// Parsed configuration from `atrg.toml`.
    pub config: Arc<Config>,
    /// Database connection pool. May be SQLite or PostgreSQL depending on
    /// the `[database] url` scheme in `atrg.toml` (and which features are
    /// compiled in to `atrg-db`).
    pub db: DbPool,
    /// Shared HTTP client for outbound requests.
    pub http: reqwest::Client,
    /// DID/handle resolver with TTL-backed in-memory cache.
    pub identity: Arc<IdentityResolver>,
    /// Type-erased container for app-specific state (S3 clients, SMTP config,
    /// domain-specific services, etc.). Access via [`AppState::extension`] or
    /// [`AppState::try_extension`].
    pub extensions: Arc<Extensions>,
}

impl AppState {
    /// Retrieve a reference to an app-specific extension by type.
    ///
    /// # Panics
    ///
    /// Panics if the extension has not been registered. Use
    /// [`try_extension`](Self::try_extension) for a non-panicking variant.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// struct MyService { url: String }
    ///
    /// // In a handler:
    /// async fn my_handler(State(state): State<AppState>) -> impl IntoResponse {
    ///     let svc = state.extension::<MyService>();
    ///     Json(json!({ "url": svc.url }))
    /// }
    /// ```
    pub fn extension<T: Send + Sync + 'static>(&self) -> &T {
        self.extensions.get::<T>().unwrap_or_else(|| {
            panic!(
                "AppState::extension::<{}>() called but no value of that type was registered. \
                 Did you forget to call `AtrgApp::with_extension(value)` during app setup?",
                std::any::type_name::<T>()
            )
        })
    }

    /// Retrieve a reference to an app-specific extension by type, returning
    /// `None` if the type was never registered.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// if let Some(metrics) = state.try_extension::<MetricsCollector>() {
    ///     metrics.record_request();
    /// }
    /// ```
    pub fn try_extension<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions.get::<T>()
    }

    /// Returns `true` if an extension of type `T` has been registered.
    pub fn has_extension<T: Send + Sync + 'static>(&self) -> bool {
        self.extensions.contains::<T>()
    }
}

// ---------------------------------------------------------------------------
// FromRef implementations — allow Axum sub-extractors to pull individual
// fields out of AppState without the handler needing to destructure manually.
// ---------------------------------------------------------------------------

impl axum::extract::FromRef<AppState> for DbPool {
    fn from_ref(state: &AppState) -> Self {
        state.db.clone()
    }
}

impl axum::extract::FromRef<AppState> for Arc<Config> {
    fn from_ref(state: &AppState) -> Self {
        state.config.clone()
    }
}

impl axum::extract::FromRef<AppState> for Arc<IdentityResolver> {
    fn from_ref(state: &AppState) -> Self {
        state.identity.clone()
    }
}

impl axum::extract::FromRef<AppState> for Arc<Extensions> {
    fn from_ref(state: &AppState) -> Self {
        state.extensions.clone()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Compile-time assertion helper.
    fn _assert_send_sync_clone<T: Send + Sync + Clone>() {}

    #[test]
    fn app_state_is_send_sync_clone() {
        _assert_send_sync_clone::<AppState>();
    }

    // -- Extensions unit tests ------------------------------------------------

    #[test]
    fn extensions_insert_and_get() {
        struct Foo(u32);
        struct Bar(String);

        let mut ext = Extensions::new();
        ext.insert(Foo(42));
        ext.insert(Bar("hello".into()));

        assert_eq!(ext.get::<Foo>().unwrap().0, 42);
        assert_eq!(ext.get::<Bar>().unwrap().0, "hello");
    }

    #[test]
    fn extensions_get_missing_returns_none() {
        let ext = Extensions::new();
        assert!(ext.get::<u32>().is_none());
    }

    #[test]
    fn extensions_insert_replaces_and_returns_old() {
        struct Config(String);

        let mut ext = Extensions::new();
        let old = ext.insert(Config("v1".into()));
        assert!(old.is_none());

        let old = ext.insert(Config("v2".into()));
        assert_eq!(old.unwrap().0, "v1");
        assert_eq!(ext.get::<Config>().unwrap().0, "v2");
    }

    #[test]
    fn extensions_contains() {
        struct Present;

        let mut ext = Extensions::new();
        assert!(!ext.contains::<Present>());
        ext.insert(Present);
        assert!(ext.contains::<Present>());
    }

    #[test]
    fn extensions_len_and_is_empty() {
        struct A;
        struct B;

        let mut ext = Extensions::new();
        assert!(ext.is_empty());
        assert_eq!(ext.len(), 0);

        ext.insert(A);
        assert!(!ext.is_empty());
        assert_eq!(ext.len(), 1);

        ext.insert(B);
        assert_eq!(ext.len(), 2);
    }

    #[test]
    fn extensions_debug_shows_len() {
        let mut ext = Extensions::new();
        ext.insert(42u32);
        let dbg = format!("{:?}", ext);
        assert!(dbg.contains("Extensions"));
        assert!(dbg.contains("len"));
    }

    #[tokio::test]
    async fn app_state_extension_returns_value() {
        struct MyService {
            name: String,
        }

        let mut ext = Extensions::new();
        ext.insert(MyService {
            name: "test".into(),
        });

        let db = atrg_db::connect("sqlite::memory:").await.unwrap();
        let state = AppState {
            config: Arc::new(crate::config::Config {
                app: crate::config::AppConfig {
                    name: "test".into(),
                    host: "127.0.0.1".into(),
                    port: 3000,
                    secret_key: "secret".into(),
                    cors_origins: vec![],
                    environment: "development".into(),
                    admin_dids: vec![],
                },
                auth: crate::config::AuthConfig {
                    client_id: "http://localhost/client-metadata.json".into(),
                    redirect_uri: "http://localhost/auth/callback".into(),
                    scope: "atproto transition:generic".into(),
                    post_login_redirect: "/".into(),
                },
                database: crate::config::DatabaseConfig {
                    url: "sqlite::memory:".into(),
                },
                jetstream: None,
                firehose: None,
                feed_generator: None,
                labeler: None,
                rate_limit: None,
            }),
            db,
            http: reqwest::Client::new(),
            identity: Arc::new(atrg_identity::IdentityResolver::with_defaults(
                reqwest::Client::new(),
            )),
            extensions: Arc::new(ext),
        };

        assert_eq!(state.extension::<MyService>().name, "test");
    }

    #[tokio::test]
    async fn app_state_try_extension_returns_none_when_missing() {
        struct NotRegistered;

        let db = atrg_db::connect("sqlite::memory:").await.unwrap();
        let state = AppState {
            config: Arc::new(crate::config::Config {
                app: crate::config::AppConfig {
                    name: "test".into(),
                    host: "127.0.0.1".into(),
                    port: 3000,
                    secret_key: "secret".into(),
                    cors_origins: vec![],
                    environment: "development".into(),
                    admin_dids: vec![],
                },
                auth: crate::config::AuthConfig {
                    client_id: "http://localhost/client-metadata.json".into(),
                    redirect_uri: "http://localhost/auth/callback".into(),
                    scope: "atproto transition:generic".into(),
                    post_login_redirect: "/".into(),
                },
                database: crate::config::DatabaseConfig {
                    url: "sqlite::memory:".into(),
                },
                jetstream: None,
                firehose: None,
                feed_generator: None,
                labeler: None,
                rate_limit: None,
            }),
            db,
            http: reqwest::Client::new(),
            identity: Arc::new(atrg_identity::IdentityResolver::with_defaults(
                reqwest::Client::new(),
            )),
            extensions: Arc::new(Extensions::new()),
        };

        assert!(state.try_extension::<NotRegistered>().is_none());
        assert!(!state.has_extension::<NotRegistered>());
    }

    #[tokio::test]
    #[should_panic(expected = "no value of that type was registered")]
    async fn app_state_extension_panics_when_missing() {
        struct NotRegistered;

        let db = atrg_db::connect("sqlite::memory:").await.unwrap();
        let state = AppState {
            config: Arc::new(crate::config::Config {
                app: crate::config::AppConfig {
                    name: "test".into(),
                    host: "127.0.0.1".into(),
                    port: 3000,
                    secret_key: "secret".into(),
                    cors_origins: vec![],
                    environment: "development".into(),
                    admin_dids: vec![],
                },
                auth: crate::config::AuthConfig {
                    client_id: "http://localhost/client-metadata.json".into(),
                    redirect_uri: "http://localhost/auth/callback".into(),
                    scope: "atproto transition:generic".into(),
                    post_login_redirect: "/".into(),
                },
                database: crate::config::DatabaseConfig {
                    url: "sqlite::memory:".into(),
                },
                jetstream: None,
                firehose: None,
                feed_generator: None,
                labeler: None,
                rate_limit: None,
            }),
            db,
            http: reqwest::Client::new(),
            identity: Arc::new(atrg_identity::IdentityResolver::with_defaults(
                reqwest::Client::new(),
            )),
            extensions: Arc::new(Extensions::new()),
        };

        let _ = state.extension::<NotRegistered>();
    }
}