quarlus-core 0.1.0

Core runtime for Quarlus web framework - AppBuilder, plugins, guards, and dependency injection
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
use std::any::{type_name, Any, TypeId};
use std::collections::HashMap;
use std::fmt;

// ── Traits ──────────────────────────────────────────────────────────────────

/// Marker trait for types that can be auto-constructed from a [`BeanContext`].
///
/// Implement this trait (or use `#[derive(Bean)]` / `#[bean]`) to declare
/// a type as a bean that the [`BeanRegistry`] can resolve automatically.
pub trait Bean: Clone + Send + Sync + 'static {
    /// Returns the [`TypeId`]s and type names of all dependencies needed
    /// to construct this bean.
    fn dependencies() -> Vec<(TypeId, &'static str)>;

    /// Construct the bean from a fully resolved context.
    fn build(ctx: &BeanContext) -> Self;
}

/// Trait for state structs that can be assembled from a [`BeanContext`].
///
/// Use `#[derive(BeanState)]` to auto-generate this implementation along
/// with `FromRef` impls for Axum state extraction.
pub trait BeanState: Clone + Send + Sync + 'static {
    /// Construct the state struct by pulling every field from the context.
    fn from_context(ctx: &BeanContext) -> Self;
}

// ── BeanContext ─────────────────────────────────────────────────────────────

/// Read-only container holding all resolved bean instances.
///
/// Produced by [`BeanRegistry::resolve`]. Each entry is keyed by [`TypeId`].
pub struct BeanContext {
    entries: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl fmt::Debug for BeanContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BeanContext")
            .field("entry_count", &self.entries.len())
            .finish()
    }
}

impl BeanContext {
    /// Retrieve a bean by type, cloning it out of the context.
    ///
    /// # Panics
    ///
    /// Panics if the requested type was not registered or provided.
    pub fn get<T: Clone + 'static>(&self) -> T {
        self.entries
            .get(&TypeId::of::<T>())
            .and_then(|v| v.downcast_ref::<T>())
            .unwrap_or_else(|| {
                panic!(
                    "Bean of type `{}` not found in context",
                    type_name::<T>()
                )
            })
            .clone()
    }

    /// Try to retrieve a bean by type, returning `None` if absent.
    pub fn try_get<T: Clone + 'static>(&self) -> Option<T> {
        self.entries
            .get(&TypeId::of::<T>())
            .and_then(|v| v.downcast_ref::<T>())
            .cloned()
    }
}

// ── BeanRegistry ────────────────────────────────────────────────────────────

type Factory = Box<dyn FnOnce(&BeanContext) -> Box<dyn Any + Send + Sync> + Send>;

/// Builder that collects bean registrations and provided instances,
/// resolves the dependency graph, and produces a [`BeanContext`].
pub struct BeanRegistry {
    beans: Vec<BeanRegistration>,
    provided: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

struct BeanRegistration {
    type_id: TypeId,
    type_name: &'static str,
    /// (TypeId, human-readable name) for each dependency.
    dependencies: Vec<(TypeId, &'static str)>,
    factory: Factory,
}

/// Errors that can occur during bean graph resolution.
#[derive(Debug)]
pub enum BeanError {
    /// A dependency cycle was detected.
    CyclicDependency { cycle: Vec<String> },
    /// A bean declares a dependency that is neither registered nor provided.
    MissingDependency { bean: String, dependency: String },
    /// The same type was registered more than once.
    DuplicateBean { type_name: String },
}

impl fmt::Display for BeanError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BeanError::CyclicDependency { cycle } => {
                write!(
                    f,
                    "Circular dependency detected: {}",
                    cycle.join(" -> ")
                )
            }
            BeanError::MissingDependency { bean, dependency } => {
                write!(
                    f,
                    "Missing dependency for bean '{}': type '{}' is not registered. \
                     Use .provide(instance) or .with_bean::<Type>()",
                    bean, dependency
                )
            }
            BeanError::DuplicateBean { type_name } => {
                write!(f, "Bean of type '{}' registered twice", type_name)
            }
        }
    }
}

impl std::error::Error for BeanError {}

impl BeanRegistry {
    /// Create a new, empty registry.
    pub fn new() -> Self {
        Self {
            beans: Vec::new(),
            provided: HashMap::new(),
        }
    }

    /// Provide a pre-built instance (e.g. external types like `SqlitePool`).
    ///
    /// The instance will be available to beans that depend on type `T`.
    pub fn provide<T: Clone + Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
        self.provided.insert(TypeId::of::<T>(), Box::new(value));
        self
    }

    /// Register a bean type for automatic construction.
    ///
    /// The bean's dependencies will be resolved from other beans or provided
    /// instances during [`resolve`](Self::resolve).
    pub fn register<T: Bean>(&mut self) -> &mut Self {
        self.beans.push(BeanRegistration {
            type_id: TypeId::of::<T>(),
            type_name: type_name::<T>(),
            dependencies: T::dependencies(),
            factory: Box::new(|ctx| Box::new(T::build(ctx))),
        });
        self
    }

    /// Resolve the dependency graph and build all beans.
    ///
    /// Uses Kahn's algorithm for topological sorting. Returns a
    /// [`BeanContext`] with all instances, or a [`BeanError`] if the graph
    /// is invalid (cycles, missing deps, or duplicates).
    pub fn resolve(self) -> Result<BeanContext, BeanError> {
        let mut entries: HashMap<TypeId, Box<dyn Any + Send + Sync>> = HashMap::new();

        // Move provided instances into the resolved set.
        for (tid, value) in self.provided {
            entries.insert(tid, value);
        }

        let bean_count = self.beans.len();
        if bean_count == 0 {
            return Ok(BeanContext { entries });
        }

        // Check for duplicates: a bean type that is also provided, or
        // registered twice.
        let mut seen: HashMap<TypeId, &str> = HashMap::new();
        for reg in &self.beans {
            if entries.contains_key(&reg.type_id) {
                return Err(BeanError::DuplicateBean {
                    type_name: reg.type_name.to_string(),
                });
            }
            if seen.insert(reg.type_id, reg.type_name).is_some() {
                return Err(BeanError::DuplicateBean {
                    type_name: reg.type_name.to_string(),
                });
            }
        }

        // Map TypeId -> index for beans.
        let id_to_idx: HashMap<TypeId, usize> = self
            .beans
            .iter()
            .enumerate()
            .map(|(i, r)| (r.type_id, i))
            .collect();

        // Check for missing dependencies.
        for reg in &self.beans {
            for (dep_id, dep_name) in &reg.dependencies {
                if !entries.contains_key(dep_id) && !id_to_idx.contains_key(dep_id) {
                    return Err(BeanError::MissingDependency {
                        bean: reg.type_name.to_string(),
                        dependency: dep_name.to_string(),
                    });
                }
            }
        }

        // Kahn's algorithm: topological sort.
        // in_degree = number of deps that are other beans (not provided).
        let mut in_degree: Vec<usize> = Vec::with_capacity(bean_count);
        for reg in &self.beans {
            let deg = reg
                .dependencies
                .iter()
                .filter(|(d, _)| id_to_idx.contains_key(d))
                .count();
            in_degree.push(deg);
        }

        // Dependents: for each bean index, which other bean indices depend on it.
        let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); bean_count];
        for (i, reg) in self.beans.iter().enumerate() {
            for (dep_id, _) in &reg.dependencies {
                if let Some(&dep_idx) = id_to_idx.get(dep_id) {
                    dependents[dep_idx].push(i);
                }
            }
        }

        // Seed queue with beans whose deps are all already provided.
        let mut queue: Vec<usize> = (0..bean_count)
            .filter(|&i| in_degree[i] == 0)
            .collect();

        let mut sorted_order: Vec<usize> = Vec::with_capacity(bean_count);

        while let Some(idx) = queue.pop() {
            sorted_order.push(idx);
            for &dep_idx in &dependents[idx] {
                in_degree[dep_idx] -= 1;
                if in_degree[dep_idx] == 0 {
                    queue.push(dep_idx);
                }
            }
        }

        // If not all beans were sorted, there's a cycle.
        if sorted_order.len() != bean_count {
            let cycle: Vec<String> = (0..bean_count)
                .filter(|i| in_degree[*i] > 0)
                .map(|i| self.beans[i].type_name.to_string())
                .collect();
            return Err(BeanError::CyclicDependency { cycle });
        }

        // Construct beans in topological order.
        // Move factories and type_ids out so we can consume them one by one.
        let mut bean_data: Vec<Option<(TypeId, Factory)>> = self
            .beans
            .into_iter()
            .map(|r| Some((r.type_id, r.factory)))
            .collect();

        for idx in sorted_order {
            let (type_id, factory) = bean_data[idx].take().unwrap();
            // Temporarily move entries into a BeanContext so the factory can
            // call ctx.get::<T>(). After the call, move entries back.
            let ctx = BeanContext { entries };
            let bean_value = factory(&ctx);
            entries = ctx.entries;
            entries.insert(type_id, bean_value);
        }

        Ok(BeanContext { entries })
    }
}

impl Default for BeanRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[derive(Clone)]
    struct Dep {
        value: i32,
    }

    #[derive(Clone)]
    struct ServiceA {
        dep: Dep,
    }

    impl Bean for ServiceA {
        fn dependencies() -> Vec<(TypeId, &'static str)> {
            vec![(TypeId::of::<Dep>(), type_name::<Dep>())]
        }
        fn build(ctx: &BeanContext) -> Self {
            Self {
                dep: ctx.get::<Dep>(),
            }
        }
    }

    #[derive(Clone)]
    struct ServiceB {
        a: ServiceA,
        dep: Dep,
    }

    impl Bean for ServiceB {
        fn dependencies() -> Vec<(TypeId, &'static str)> {
            vec![
                (TypeId::of::<ServiceA>(), type_name::<ServiceA>()),
                (TypeId::of::<Dep>(), type_name::<Dep>()),
            ]
        }
        fn build(ctx: &BeanContext) -> Self {
            Self {
                a: ctx.get::<ServiceA>(),
                dep: ctx.get::<Dep>(),
            }
        }
    }

    #[test]
    fn resolve_simple_graph() {
        let mut reg = BeanRegistry::new();
        reg.provide(Dep { value: 42 });
        reg.register::<ServiceA>();
        reg.register::<ServiceB>();
        let ctx = reg.resolve().unwrap();

        let b: ServiceB = ctx.get();
        assert_eq!(b.dep.value, 42);
        assert_eq!(b.a.dep.value, 42);
    }

    #[test]
    fn missing_dependency() {
        let mut reg = BeanRegistry::new();
        reg.register::<ServiceA>();
        let err = reg.resolve().unwrap_err();
        match &err {
            BeanError::MissingDependency { dependency, .. } => {
                assert!(dependency.contains("Dep"), "error should name the missing type: {}", err);
            }
            _ => panic!("expected MissingDependency, got {:?}", err),
        }
    }

    #[test]
    fn duplicate_bean_registered_twice() {
        let mut reg = BeanRegistry::new();
        reg.provide(Dep { value: 1 });
        reg.register::<ServiceA>();
        reg.register::<ServiceA>();
        let err = reg.resolve().unwrap_err();
        assert!(matches!(err, BeanError::DuplicateBean { .. }));
    }

    #[test]
    fn duplicate_provided_and_bean() {
        let mut reg = BeanRegistry::new();
        reg.provide(Dep { value: 1 });
        reg.provide(ServiceA {
            dep: Dep { value: 2 },
        });
        reg.register::<ServiceA>();
        let err = reg.resolve().unwrap_err();
        assert!(matches!(err, BeanError::DuplicateBean { .. }));
    }

    #[derive(Clone)]
    struct CycleA;
    #[derive(Clone)]
    struct CycleB;

    impl Bean for CycleA {
        fn dependencies() -> Vec<(TypeId, &'static str)> {
            vec![(TypeId::of::<CycleB>(), type_name::<CycleB>())]
        }
        fn build(ctx: &BeanContext) -> Self {
            let _ = ctx.get::<CycleB>();
            Self
        }
    }
    impl Bean for CycleB {
        fn dependencies() -> Vec<(TypeId, &'static str)> {
            vec![(TypeId::of::<CycleA>(), type_name::<CycleA>())]
        }
        fn build(ctx: &BeanContext) -> Self {
            let _ = ctx.get::<CycleA>();
            Self
        }
    }

    #[test]
    fn cyclic_dependency() {
        let mut reg = BeanRegistry::new();
        reg.register::<CycleA>();
        reg.register::<CycleB>();
        let err = reg.resolve().unwrap_err();
        assert!(matches!(err, BeanError::CyclicDependency { .. }));
    }

    #[test]
    fn provided_only() {
        let mut reg = BeanRegistry::new();
        reg.provide(Dep { value: 7 });
        let ctx = reg.resolve().unwrap();
        let d: Dep = ctx.get();
        assert_eq!(d.value, 7);
    }

    #[test]
    fn try_get_none() {
        let reg = BeanRegistry::new();
        let ctx = reg.resolve().unwrap();
        assert!(ctx.try_get::<Dep>().is_none());
    }

    #[test]
    fn empty_registry() {
        let reg = BeanRegistry::new();
        let ctx = reg.resolve().unwrap();
        assert!(ctx.try_get::<i32>().is_none());
    }
}