jerrycan-core 0.2.0

Core of the jerrycan framework: routing, extractors, dependency injection, middleware. https://jerrycan.cc
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
//! Dependency injection (spec §4.3) — async, nested, per-request memoized,
//! override-able in tests. Resolution order: cache → overrides → singletons → factories.
//! Singletons and factories are disjoint by construction (`insert_value`/`insert_factory`
//! each remove the opposite key), so there is no singleton-vs-factory tiebreak to define.

use crate::error::{Error, Result};
use crate::extract::{FromRequest, RequestCtx};
use std::any::{Any, TypeId, type_name};
use std::collections::HashMap;
use std::future::Future;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::Arc;

pub(crate) type AnyArc = Arc<dyn Any + Send + Sync>;
pub(crate) type ProviderFut<'a> = Pin<Box<dyn Future<Output = Result<AnyArc>> + Send + 'a>>;
pub(crate) type ProviderFn =
    Arc<dyn for<'a> Fn(&'a mut RequestCtx) -> ProviderFut<'a> + Send + Sync>;

/// The provider set effective for a route: app providers merged with the
/// route's module chain — inner module wins (spec §4.2 scoping).
#[derive(Default, Clone)]
pub struct DepEnv {
    pub(crate) singletons: HashMap<TypeId, AnyArc>,
    pub(crate) factories: HashMap<TypeId, ProviderFn>,
}

impl DepEnv {
    /// Register an already-built value; shared by every request (singleton scope).
    pub(crate) fn insert_value<T: Send + Sync + 'static>(&mut self, value: T) {
        let id = TypeId::of::<T>();
        self.singletons.insert(id, Arc::new(value));
        self.factories.remove(&id);
    }

    /// Register an async factory; runs at most once per request (request scope).
    pub(crate) fn insert_factory<F, Args, T>(&mut self, factory: F)
    where
        F: DepFactory<Args, T>,
        T: Send + Sync + 'static,
    {
        let id = TypeId::of::<T>();
        self.factories.insert(id, factory.into_provider());
        self.singletons.remove(&id);
    }

    /// Later entries shadow earlier ones — used to layer module envs over the app env.
    pub(crate) fn merge_from(&mut self, inner: &DepEnv) {
        for (k, v) in &inner.singletons {
            self.singletons.insert(*k, v.clone());
            self.factories.remove(k);
        }
        for (k, f) in &inner.factories {
            self.factories.insert(*k, f.clone());
            self.singletons.remove(k);
        }
    }
}

/// Per-request resolution state. Cheap to create; memoizes by `TypeId`.
pub struct DepResolver {
    pub(crate) env: Arc<DepEnv>,
    pub(crate) overrides: Arc<HashMap<TypeId, AnyArc>>,
    pub(crate) cache: HashMap<TypeId, AnyArc>,
    pub(crate) depth: u8,
}

impl DepResolver {
    pub(crate) fn new(env: Arc<DepEnv>, overrides: Arc<HashMap<TypeId, AnyArc>>) -> Self {
        Self {
            env,
            overrides,
            cache: HashMap::new(),
            depth: 0,
        }
    }
}

const MAX_RESOLVE_DEPTH: u8 = 32;

impl RequestCtx {
    /// Resolve a dependency by type, memoized for this request (spec §4.3).
    pub async fn resolve<T: Send + Sync + 'static>(&mut self) -> Result<Arc<T>> {
        let id = TypeId::of::<T>();
        if let Some(v) = self.deps.cache.get(&id) {
            return downcast::<T>(v.clone());
        }
        if let Some(v) = self.deps.overrides.get(&id).cloned() {
            self.deps.cache.insert(id, v.clone());
            return downcast::<T>(v);
        }
        if let Some(v) = self.deps.env.singletons.get(&id).cloned() {
            self.deps.cache.insert(id, v.clone());
            return downcast::<T>(v);
        }
        let factory = match self.deps.env.factories.get(&id) {
            Some(f) => f.clone(),
            None => return Err(Error::missing_dependency(type_name::<T>())),
        };
        self.deps.depth += 1;
        if self.deps.depth > MAX_RESOLVE_DEPTH {
            self.deps.depth -= 1;
            return Err(Error::dependency_cycle());
        }
        let produced = (*factory)(self).await;
        self.deps.depth -= 1;
        let v = produced?;
        self.deps.cache.insert(id, v.clone());
        downcast::<T>(v)
    }
}

fn downcast<T: Send + Sync + 'static>(v: AnyArc) -> Result<Arc<T>> {
    v.downcast::<T>()
        .map_err(|_| Error::internal("dependency type mismatch (provider/consumer disagree)"))
}

/// Resolve dependencies OUTSIDE an HTTP request — background jobs, startup
/// wiring, CLI commands. Built from [`BuiltApp::task_context`](crate::BuiltApp::task_context).
///
/// Resolution semantics mirror a request (memoized per context, honors
/// overrides and singletons), but only **app-level** providers are in scope,
/// and any factory reaching for an HTTP extractor (`Json`/`Path`/`Query`/
/// `Headers`) fails with `JC1003`.
pub struct TaskContext(RequestCtx);

impl TaskContext {
    /// Wrap a resolver in a synthetic request marked as a task context. The
    /// parts/body/params are placeholders: HTTP-coupled extractors reject a
    /// task context before reading them, and `Dep<T>` never touches them.
    pub(crate) fn new(deps: DepResolver) -> Self {
        let req = http::Request::builder()
            .uri("/")
            .body(())
            .expect("static request head always builds");
        let (parts, ()) = req.into_parts();
        let mut ctx = RequestCtx::new(parts, bytes::Bytes::new(), deps);
        ctx.is_task = true;
        TaskContext(ctx)
    }

    /// Resolve a dependency by type, memoized for this task context. Mirrors
    /// [`RequestCtx::resolve`]; returns the same `Arc<T>` `Dep<T>` would carry.
    pub async fn resolve<T: Send + Sync + 'static>(&mut self) -> Result<Arc<T>> {
        self.0.resolve::<T>().await
    }

    /// A sibling task context sharing the app-level providers but with a fresh
    /// dependency-resolution cache — the job worker forks one per job so cached
    /// deps never leak between jobs.
    ///
    /// The new context reuses the same `Arc<DepEnv>` (singletons + factories)
    /// and the same `Arc` of overrides, so it resolves identical singletons; it
    /// gets an empty cache, so request-scope factories run afresh and per-job
    /// state is isolated.
    pub fn fork(&self) -> TaskContext {
        TaskContext::new(DepResolver::new(
            self.0.deps.env.clone(),
            self.0.deps.overrides.clone(),
        ))
    }
}

/// A resolved dependency. Derefs to `T`; cloning is `Arc`-cheap.
pub struct Dep<T: ?Sized>(pub(crate) Arc<T>);

impl<T: ?Sized> Deref for Dep<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T: ?Sized> Clone for Dep<T> {
    fn clone(&self) -> Self {
        Dep(self.0.clone())
    }
}

impl<T: Send + Sync + 'static> FromRequest for Dep<T> {
    async fn from_request(ctx: &mut RequestCtx) -> Result<Self> {
        ctx.resolve::<T>().await.map(Dep)
    }
}

/// Async functions registrable as providers. `Args` is the tuple of extractor
/// parameters; `T` the produced dependency. Implemented for arities 0..=8.
pub trait DepFactory<Args, T>: Send + Sync + 'static {
    fn into_provider(self) -> ProviderFn;
}

macro_rules! impl_dep_factory {
    ($($A:ident),*) => {
        impl<F, Fut, T, $($A,)*> DepFactory<($($A,)*), T> for F
        where
            F: Fn($($A),*) -> Fut + Clone + Send + Sync + 'static,
            Fut: Future<Output = Result<T>> + Send,
            T: Send + Sync + 'static,
            $($A: FromRequest + 'static,)*
        {
            fn into_provider(self) -> ProviderFn {
                #[allow(unused_variables)]
                Arc::new(move |ctx: &mut RequestCtx| {
                    let f = self.clone();
                    Box::pin(async move {
                        #[allow(non_snake_case, unused_variables)]
                        {
                            $(let $A = <$A as FromRequest>::from_request(ctx).await?;)*
                            let value = f($($A),*).await?;
                            Ok(Arc::new(value) as AnyArc)
                        }
                    })
                })
            }
        }
    };
}

impl_dep_factory!();
impl_dep_factory!(A1);
impl_dep_factory!(A1, A2);
impl_dep_factory!(A1, A2, A3);
impl_dep_factory!(A1, A2, A3, A4);
impl_dep_factory!(A1, A2, A3, A4, A5);
impl_dep_factory!(A1, A2, A3, A4, A5, A6);
impl_dep_factory!(A1, A2, A3, A4, A5, A6, A7);
impl_dep_factory!(A1, A2, A3, A4, A5, A6, A7, A8);

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

    pub(crate) fn test_ctx(env: DepEnv) -> RequestCtx {
        let req = http::Request::builder().uri("/").body(()).unwrap();
        let (parts, ()) = req.into_parts();
        RequestCtx::new(
            parts,
            Bytes::new(),
            DepResolver::new(Arc::new(env), Arc::new(HashMap::new())),
        )
    }

    struct Config {
        name: &'static str,
    }

    #[tokio::test]
    async fn value_provider_resolves_and_derefs() {
        let mut env = DepEnv::default();
        env.insert_value(Config { name: "prod" });
        let mut ctx = test_ctx(env);
        let cfg: Dep<Config> = Dep::from_request(&mut ctx).await.unwrap();
        assert_eq!(cfg.name, "prod"); // Deref<Target = Config>
    }

    #[tokio::test]
    async fn missing_provider_is_jc1001() {
        let mut ctx = test_ctx(DepEnv::default());
        let err = Dep::<Config>::from_request(&mut ctx).await.err().unwrap();
        assert_eq!(err.code(), "JC1001");
        assert!(err.message().contains("Config"));
    }

    #[tokio::test]
    async fn same_request_yields_same_arc() {
        let mut env = DepEnv::default();
        env.insert_value(Config { name: "x" });
        let mut ctx = test_ctx(env);
        let a = ctx.resolve::<Config>().await.unwrap();
        let b = ctx.resolve::<Config>().await.unwrap();
        assert!(Arc::ptr_eq(&a, &b));
    }

    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Clone)]
    struct Db {
        url: &'static str,
    }
    struct Session {
        token: String,
    }
    struct User {
        name: String,
    }

    async fn make_session() -> crate::Result<Session> {
        Ok(Session {
            token: "t-1".into(),
        })
    }

    async fn current_user(session: Dep<Session>, db: Dep<Db>) -> crate::Result<User> {
        Ok(User {
            name: format!("{}@{}", session.token, db.url),
        })
    }

    fn nested_env() -> DepEnv {
        let mut env = DepEnv::default();
        env.insert_value(Db { url: "pg://prod" });
        env.insert_factory(make_session);
        env.insert_factory(current_user);
        env
    }

    #[tokio::test]
    async fn factories_nest_and_resolve_async() {
        let mut ctx = test_ctx(nested_env());
        let user = ctx.resolve::<User>().await.unwrap();
        assert_eq!(user.name, "t-1@pg://prod");
    }

    #[tokio::test]
    async fn nested_deps_are_memoized_once_per_request() {
        // A test-local counter (`LOCAL_RESOLVES`) + session factory so parallel tests
        // can't pollute these exact-count assertions.
        static LOCAL_RESOLVES: AtomicUsize = AtomicUsize::new(0);
        async fn local_session() -> crate::Result<Session> {
            LOCAL_RESOLVES.fetch_add(1, Ordering::SeqCst);
            Ok(Session {
                token: "t-1".into(),
            })
        }
        fn local_env() -> DepEnv {
            let mut env = DepEnv::default();
            env.insert_value(Db { url: "pg://prod" });
            env.insert_factory(local_session);
            env.insert_factory(current_user);
            env
        }

        LOCAL_RESOLVES.store(0, Ordering::SeqCst);
        let mut ctx = test_ctx(local_env());
        // Both of these need Session (one directly, one through current_user).
        let _s = ctx.resolve::<Session>().await.unwrap();
        let _u = ctx.resolve::<User>().await.unwrap();
        assert_eq!(
            LOCAL_RESOLVES.load(Ordering::SeqCst),
            1,
            "memoized within request"
        );

        // A new request resolves afresh — request scope, not singleton.
        let mut ctx2 = test_ctx(local_env());
        let _u2 = ctx2.resolve::<User>().await.unwrap();
        assert_eq!(LOCAL_RESOLVES.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn self_referential_factory_hits_cycle_guard() {
        struct Loopy;
        async fn loopy(_again: Dep<Loopy>) -> crate::Result<Loopy> {
            Ok(Loopy)
        }
        let mut env = DepEnv::default();
        env.insert_factory(loopy);
        let mut ctx = test_ctx(env);
        let err = ctx.resolve::<Loopy>().await.err().unwrap();
        assert_eq!(err.code(), "JC1002");
    }

    #[tokio::test]
    async fn overrides_shadow_both_values_and_factories() {
        // Real env: Db value + Session factory.
        let mut env = nested_env();
        env.insert_value(Db { url: "pg://prod" });

        // Overrides replace them without touching the env.
        let mut overrides: HashMap<TypeId, AnyArc> = HashMap::new();
        overrides.insert(
            TypeId::of::<Db>(),
            Arc::new(Db {
                url: "sqlite::memory:",
            }),
        );
        overrides.insert(
            TypeId::of::<Session>(),
            Arc::new(Session {
                token: "fake".into(),
            }),
        );

        let req = http::Request::builder().uri("/").body(()).unwrap();
        let (parts, ()) = req.into_parts();
        let mut ctx = RequestCtx::new(
            parts,
            bytes::Bytes::new(),
            DepResolver::new(Arc::new(env), Arc::new(overrides)),
        );

        let user = ctx.resolve::<User>().await.unwrap();
        assert_eq!(user.name, "fake@sqlite::memory:");
    }

    // ---- Task-scoped DI (Task 5): resolve deps outside an HTTP request ----

    #[tokio::test]
    async fn deps_resolve_without_a_request() {
        #[derive(Clone)]
        struct Cfg(u32);
        async fn make_cfg() -> crate::Result<Cfg> {
            Ok(Cfg(7))
        }
        let built = crate::App::new().provide_dep(make_cfg).build().unwrap();
        let mut ctx = built.task_context();
        let cfg = ctx.resolve::<Cfg>().await.unwrap();
        assert_eq!(cfg.0, 7);
    }

    #[tokio::test]
    async fn task_resolution_memoizes_and_honors_singletons() {
        // A factory with a side-effect counter must resolve at most once per
        // task context (request-scope memoization), and a `provide()` singleton
        // must also be reachable from the same context.
        static BUILDS: AtomicUsize = AtomicUsize::new(0);
        #[derive(Clone)]
        struct Singleton(&'static str);
        struct Counted;
        async fn build_counted() -> crate::Result<Counted> {
            BUILDS.fetch_add(1, Ordering::SeqCst);
            Ok(Counted)
        }

        BUILDS.store(0, Ordering::SeqCst);
        let built = crate::App::new()
            .provide(Singleton("app"))
            .provide_dep(build_counted)
            .build()
            .unwrap();

        let mut ctx = built.task_context();
        // Singleton resolves in a task context.
        let s = ctx.resolve::<Singleton>().await.unwrap();
        assert_eq!(s.0, "app");
        // Factory runs once and is memoized across repeat resolves.
        let a = ctx.resolve::<Counted>().await.unwrap();
        let b = ctx.resolve::<Counted>().await.unwrap();
        assert!(Arc::ptr_eq(&a, &b));
        assert_eq!(BUILDS.load(Ordering::SeqCst), 1, "memoized within the task");

        // A fresh task context resolves the factory afresh (task scope, like a request).
        let mut ctx2 = built.task_context();
        let _ = ctx2.resolve::<Counted>().await.unwrap();
        assert_eq!(BUILDS.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn http_extractors_reject_task_context_with_jc1003() {
        #[derive(Clone)]
        struct Whoami(#[allow(dead_code)] String);
        async fn needs_headers(h: crate::Headers) -> crate::Result<Whoami> {
            let _ = h;
            Ok(Whoami("x".into()))
        }
        let built = crate::App::new()
            .provide_dep(needs_headers)
            .build()
            .unwrap();
        let mut ctx = built.task_context();
        let err = ctx.resolve::<Whoami>().await.err().unwrap();
        assert_eq!(err.code(), "JC1003");
        assert_eq!(err.status().as_u16(), 500);
    }

    #[test]
    fn task_context_is_send() {
        // The job worker holds an owned `TaskContext` across `.await`s and forks
        // a fresh one per job; an `on_serve` future must be `Send`. An owned
        // `TaskContext` is `Send` (its body lane is `Send` but `!Sync`) — this
        // invariant is load-bearing for the jobs engine, so lock it in.
        fn assert_send<T: Send>() {}
        assert_send::<TaskContext>();
    }

    #[tokio::test]
    async fn fork_shares_singletons_but_resets_the_resolution_cache() {
        // A side-effect counter on a factory: each forked context must resolve
        // the factory afresh (independent caches), while a `provide()` singleton
        // is the same `Arc` across forks (shared app-level providers).
        static BUILDS: AtomicUsize = AtomicUsize::new(0);
        #[derive(Clone)]
        struct Singleton(&'static str);
        struct Counted;
        async fn build_counted() -> crate::Result<Counted> {
            BUILDS.fetch_add(1, Ordering::SeqCst);
            Ok(Counted)
        }

        BUILDS.store(0, Ordering::SeqCst);
        let built = crate::App::new()
            .provide(Singleton("app"))
            .provide_dep(build_counted)
            .build()
            .unwrap();
        let base = built.task_context();

        // Two forks resolve the SAME singleton Arc (shared providers)...
        let mut a = base.fork();
        let mut b = base.fork();
        let sa = a.resolve::<Singleton>().await.unwrap();
        let sb = b.resolve::<Singleton>().await.unwrap();
        assert!(Arc::ptr_eq(&sa, &sb), "forks share the singleton provider");
        assert_eq!(
            sa.0, "app",
            "the shared singleton carries the provided value"
        );

        // ...but each fork has an independent cache: the factory runs once per
        // fork, not once total, so two forks => two builds.
        let _ = a.resolve::<Counted>().await.unwrap();
        let _ = b.resolve::<Counted>().await.unwrap();
        assert_eq!(
            BUILDS.load(Ordering::SeqCst),
            2,
            "each fork resolves the factory in its own fresh cache"
        );
    }

    #[tokio::test]
    async fn test_app_task_context_honors_overrides() {
        #[derive(Clone)]
        struct Cfg(u32);
        async fn make_cfg() -> crate::Result<Cfg> {
            Ok(Cfg(1)) // real provider value
        }
        let app = crate::App::new()
            .provide_dep(make_cfg)
            .into_test()
            .override_dep(Cfg(99)); // test fake
        let mut ctx = app.task_context();
        let cfg = ctx.resolve::<Cfg>().await.unwrap();
        assert_eq!(cfg.0, 99, "override wins in a task context too");
    }
}