ferro-rs 0.2.1

A Laravel-inspired web framework for Rust
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
//! Application Container for Dependency Injection
//!
//! This module provides Laravel-like service container capabilities:
//! - Singletons: shared instances across the application
//! - Factories: new instance per resolution
//! - Trait bindings: bind interfaces to implementations
//! - Test faking: swap implementations in tests
//! - Service Providers: bootstrap services with register/boot lifecycle
//!
//! # Example
//!
//! ```rust,ignore
//! use ferro_rs::{App, bind, singleton, service};
//!
//! // Define a service trait with auto-registration
//! #[service(RealHttpClient)]
//! pub trait HttpClient {
//!     async fn get(&self, url: &str) -> Result<String, Error>;
//! }
//!
//! // Or register manually using macros
//! bind!(dyn HttpClient, RealHttpClient::new());
//! singleton!(CacheService::new());
//!
//! // Resolve anywhere in your app
//! let client: Arc<dyn HttpClient> = App::make::<dyn HttpClient>().unwrap();
//! ```

pub mod provider;
pub mod testing;

pub use provider::{get_registered_services, ServiceBindingType, ServiceInfo};

use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::{Arc, OnceLock, RwLock};

/// Global application container
static APP_CONTAINER: OnceLock<RwLock<Container>> = OnceLock::new();

// Thread-local test overrides for isolated testing
thread_local! {
    pub(crate) static TEST_CONTAINER: RefCell<Option<Container>> = const { RefCell::new(None) };
}

/// Binding types: either a singleton instance or a factory closure
#[derive(Clone)]
enum Binding {
    /// Shared singleton instance - same instance returned every time
    Singleton(Arc<dyn Any + Send + Sync>),

    /// Factory closure - creates new instance each time
    Factory(Arc<dyn Fn() -> Arc<dyn Any + Send + Sync> + Send + Sync>),
}

/// The main service container
///
/// Stores type-erased bindings keyed by TypeId. Supports both concrete types
/// and trait objects (via `Arc<dyn Trait>`).
pub struct Container {
    /// Type bindings: TypeId -> Binding
    bindings: HashMap<TypeId, Binding>,
}

impl Container {
    /// Create a new empty container
    pub fn new() -> Self {
        Self {
            bindings: HashMap::new(),
        }
    }

    /// Register a singleton instance (shared across all resolutions)
    ///
    /// # Example
    /// ```rust,ignore
    /// container.singleton(DatabaseConnection::new(&url));
    /// ```
    pub fn singleton<T: Any + Send + Sync + 'static>(&mut self, instance: T) {
        let arc: Arc<dyn Any + Send + Sync> = Arc::new(instance);
        self.bindings
            .insert(TypeId::of::<T>(), Binding::Singleton(arc));
    }

    /// Register a factory closure (new instance per resolution)
    ///
    /// # Example
    /// ```rust,ignore
    /// container.factory(|| RequestLogger::new());
    /// ```
    pub fn factory<T, F>(&mut self, factory: F)
    where
        T: Any + Send + Sync + 'static,
        F: Fn() -> T + Send + Sync + 'static,
    {
        let wrapped: Arc<dyn Fn() -> Arc<dyn Any + Send + Sync> + Send + Sync> =
            Arc::new(move || Arc::new(factory()) as Arc<dyn Any + Send + Sync>);
        self.bindings
            .insert(TypeId::of::<T>(), Binding::Factory(wrapped));
    }

    /// Bind a trait object to a concrete implementation (as singleton)
    ///
    /// This stores the value under `TypeId::of::<Arc<dyn Trait>>()` which allows
    /// trait objects to be resolved via `make::<dyn Trait>()`.
    ///
    /// # Example
    /// ```rust,ignore
    /// container.bind::<dyn HttpClient>(RealHttpClient::new());
    /// ```
    pub fn bind<T: ?Sized + Send + Sync + 'static>(&mut self, instance: Arc<T>) {
        // Store under TypeId of Arc<T> (works for both concrete and trait objects)
        let type_id = TypeId::of::<Arc<T>>();
        let arc: Arc<dyn Any + Send + Sync> = Arc::new(instance);
        self.bindings.insert(type_id, Binding::Singleton(arc));
    }

    /// Bind a trait object to a factory
    ///
    /// # Example
    /// ```rust,ignore
    /// container.bind_factory::<dyn HttpClient>(|| Arc::new(RealHttpClient::new()));
    /// ```
    pub fn bind_factory<T: ?Sized + Send + Sync + 'static, F>(&mut self, factory: F)
    where
        F: Fn() -> Arc<T> + Send + Sync + 'static,
    {
        let type_id = TypeId::of::<Arc<T>>();
        let wrapped: Arc<dyn Fn() -> Arc<dyn Any + Send + Sync> + Send + Sync> =
            Arc::new(move || Arc::new(factory()) as Arc<dyn Any + Send + Sync>);
        self.bindings.insert(type_id, Binding::Factory(wrapped));
    }

    /// Resolve a concrete type (requires Clone)
    ///
    /// # Example
    /// ```rust,ignore
    /// let db: DatabaseConnection = container.get().unwrap();
    /// ```
    pub fn get<T: Any + Send + Sync + Clone + 'static>(&self) -> Option<T> {
        match self.bindings.get(&TypeId::of::<T>())? {
            Binding::Singleton(arc) => arc.downcast_ref::<T>().cloned(),
            Binding::Factory(factory) => {
                let arc = factory();
                arc.downcast_ref::<T>().cloned()
            }
        }
    }

    /// Resolve a trait binding - returns `Arc<T>`
    ///
    /// # Example
    /// ```rust,ignore
    /// let client: Arc<dyn HttpClient> = container.make::<dyn HttpClient>().unwrap();
    /// ```
    pub fn make<T: ?Sized + Send + Sync + 'static>(&self) -> Option<Arc<T>> {
        let type_id = TypeId::of::<Arc<T>>();
        match self.bindings.get(&type_id)? {
            Binding::Singleton(arc) => {
                // The stored value is Arc<Arc<T>>, so we downcast and clone the inner Arc
                arc.downcast_ref::<Arc<T>>().cloned()
            }
            Binding::Factory(factory) => {
                let arc = factory();
                arc.downcast_ref::<Arc<T>>().cloned()
            }
        }
    }

    /// Check if a concrete type is registered
    pub fn has<T: Any + 'static>(&self) -> bool {
        self.bindings.contains_key(&TypeId::of::<T>())
    }

    /// Check if a trait binding is registered
    pub fn has_binding<T: ?Sized + 'static>(&self) -> bool {
        self.bindings.contains_key(&TypeId::of::<Arc<T>>())
    }
}

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

/// Application container facade
///
/// Provides static methods for service registration and resolution.
/// Uses a global container with thread-local test overrides.
///
/// # Example
///
/// ```rust,ignore
/// use ferro_rs::{App, bind, singleton};
///
/// // Register services at startup using macros
/// singleton!(DatabaseConnection::new(&url));
/// bind!(dyn HttpClient, RealHttpClient::new());
///
/// // Resolve anywhere
/// let db: DatabaseConnection = App::get().unwrap();
/// let client: Arc<dyn HttpClient> = App::make::<dyn HttpClient>().unwrap();
/// ```
pub struct App;

impl App {
    /// Initialize the application container
    ///
    /// Should be called once at application startup. This is automatically
    /// called by `Server::from_config()`.
    pub fn init() {
        APP_CONTAINER.get_or_init(|| RwLock::new(Container::new()));
    }

    /// Register a singleton instance (shared across all resolutions)
    ///
    /// # Example
    /// ```rust,ignore
    /// App::singleton(DatabaseConnection::new(&url));
    /// ```
    pub fn singleton<T: Any + Send + Sync + 'static>(instance: T) {
        let container = APP_CONTAINER.get_or_init(|| RwLock::new(Container::new()));
        if let Ok(mut c) = container.write() {
            c.singleton(instance);
        }
    }

    /// Register a factory binding (new instance per resolution)
    ///
    /// # Example
    /// ```rust,ignore
    /// App::factory(|| RequestLogger::new());
    /// ```
    pub fn factory<T, F>(factory: F)
    where
        T: Any + Send + Sync + 'static,
        F: Fn() -> T + Send + Sync + 'static,
    {
        let container = APP_CONTAINER.get_or_init(|| RwLock::new(Container::new()));
        if let Ok(mut c) = container.write() {
            c.factory(factory);
        }
    }

    /// Bind a trait object to a concrete implementation (as singleton)
    ///
    /// # Example
    /// ```rust,ignore
    /// App::bind::<dyn HttpClient>(Arc::new(RealHttpClient::new()));
    /// ```
    pub fn bind<T: ?Sized + Send + Sync + 'static>(instance: Arc<T>) {
        let container = APP_CONTAINER.get_or_init(|| RwLock::new(Container::new()));
        if let Ok(mut c) = container.write() {
            c.bind(instance);
        }
    }

    /// Bind a trait object to a factory
    ///
    /// # Example
    /// ```rust,ignore
    /// App::bind_factory::<dyn HttpClient>(|| Arc::new(RealHttpClient::new()));
    /// ```
    pub fn bind_factory<T: ?Sized + Send + Sync + 'static, F>(factory: F)
    where
        F: Fn() -> Arc<T> + Send + Sync + 'static,
    {
        let container = APP_CONTAINER.get_or_init(|| RwLock::new(Container::new()));
        if let Ok(mut c) = container.write() {
            c.bind_factory(factory);
        }
    }

    /// Resolve a concrete type
    ///
    /// Checks test overrides first, then falls back to global container.
    ///
    /// # Example
    /// ```rust,ignore
    /// let db: DatabaseConnection = App::get().unwrap();
    /// ```
    pub fn get<T: Any + Send + Sync + Clone + 'static>() -> Option<T> {
        // Check test overrides first (thread-local)
        let test_result = TEST_CONTAINER.with(|c| {
            c.borrow()
                .as_ref()
                .and_then(|container| container.get::<T>())
        });

        if test_result.is_some() {
            return test_result;
        }

        // Fall back to global container
        let container = APP_CONTAINER.get()?;
        container.read().ok()?.get::<T>()
    }

    /// Resolve a trait binding - returns `Arc<T>`
    ///
    /// Checks test overrides first, then falls back to global container.
    ///
    /// # Example
    /// ```rust,ignore
    /// let client: Arc<dyn HttpClient> = App::make::<dyn HttpClient>().unwrap();
    /// ```
    pub fn make<T: ?Sized + Send + Sync + 'static>() -> Option<Arc<T>> {
        // Check test overrides first (thread-local)
        let test_result = TEST_CONTAINER.with(|c| {
            c.borrow()
                .as_ref()
                .and_then(|container| container.make::<T>())
        });

        if test_result.is_some() {
            return test_result;
        }

        // Fall back to global container
        let container = APP_CONTAINER.get()?;
        container.read().ok()?.make::<T>()
    }

    /// Resolve a concrete type, returning an error if not found
    ///
    /// This allows using the `?` operator in controllers and services for
    /// automatic error propagation with proper HTTP responses.
    ///
    /// # Example
    /// ```rust,ignore
    /// pub async fn index(_req: Request) -> Response {
    ///     let service = App::resolve::<MyService>()?;
    ///     // ...
    /// }
    /// ```
    pub fn resolve<T: Any + Send + Sync + Clone + 'static>(
    ) -> Result<T, crate::error::FrameworkError> {
        Self::get::<T>().ok_or_else(crate::error::FrameworkError::service_not_found::<T>)
    }

    /// Resolve a trait binding, returning an error if not found
    ///
    /// This allows using the `?` operator for trait object resolution.
    ///
    /// # Example
    /// ```rust,ignore
    /// let client: Arc<dyn HttpClient> = App::resolve_make::<dyn HttpClient>()?;
    /// ```
    pub fn resolve_make<T: ?Sized + Send + Sync + 'static>(
    ) -> Result<Arc<T>, crate::error::FrameworkError> {
        Self::make::<T>().ok_or_else(crate::error::FrameworkError::service_not_found::<T>)
    }

    /// Check if a concrete type is registered
    pub fn has<T: Any + 'static>() -> bool {
        // Check test container first
        let in_test = TEST_CONTAINER.with(|c| {
            c.borrow()
                .as_ref()
                .map(|container| container.has::<T>())
                .unwrap_or(false)
        });

        if in_test {
            return true;
        }

        APP_CONTAINER
            .get()
            .and_then(|c| c.read().ok())
            .map(|c| c.has::<T>())
            .unwrap_or(false)
    }

    /// Check if a trait binding is registered
    pub fn has_binding<T: ?Sized + 'static>() -> bool {
        // Check test container first
        let in_test = TEST_CONTAINER.with(|c| {
            c.borrow()
                .as_ref()
                .map(|container| container.has_binding::<T>())
                .unwrap_or(false)
        });

        if in_test {
            return true;
        }

        APP_CONTAINER
            .get()
            .and_then(|c| c.read().ok())
            .map(|c| c.has_binding::<T>())
            .unwrap_or(false)
    }

    /// Boot all auto-registered services
    ///
    /// This registers all services marked with `#[service(ConcreteType)]`.
    /// Called automatically by `Server::from_config()`.
    pub fn boot_services() {
        provider::bootstrap();
    }
}

/// Bind a trait to a singleton implementation (auto-wraps in Arc)
///
/// # Example
/// ```rust,ignore
/// bind!(dyn Database, PostgresDB::connect(&db_url));
/// bind!(dyn HttpClient, RealHttpClient::new());
/// ```
#[macro_export]
macro_rules! bind {
    ($trait:ty, $instance:expr) => {
        $crate::App::bind::<$trait>(::std::sync::Arc::new($instance) as ::std::sync::Arc<$trait>)
    };
}

/// Bind a trait to a factory (auto-wraps in Arc, new instance each resolution)
///
/// # Example
/// ```rust,ignore
/// bind_factory!(dyn HttpClient, || RealHttpClient::new());
/// ```
#[macro_export]
macro_rules! bind_factory {
    ($trait:ty, $factory:expr) => {{
        let f = $factory;
        $crate::App::bind_factory::<$trait, _>(move || {
            ::std::sync::Arc::new(f()) as ::std::sync::Arc<$trait>
        })
    }};
}

/// Register a singleton instance (concrete type)
///
/// # Example
/// ```rust,ignore
/// singleton!(DatabaseConnection::new(&url));
/// ```
#[macro_export]
macro_rules! singleton {
    ($instance:expr) => {
        $crate::App::singleton($instance)
    };
}

/// Register a factory (concrete type, new instance each resolution)
///
/// # Example
/// ```rust,ignore
/// factory!(|| RequestLogger::new());
/// ```
#[macro_export]
macro_rules! factory {
    ($factory:expr) => {
        $crate::App::factory($factory)
    };
}