Skip to main content

larastvel_core/foundation/
mod.rs

1pub mod event_service_provider;
2pub mod maintenance;
3pub mod route_service_provider;
4
5use std::any::{Any, TypeId};
6use std::collections::HashMap;
7use std::path::PathBuf;
8use std::sync::{Arc, Mutex};
9
10use axum::Router as AxumRouter;
11use tracing::info;
12
13use crate::config::Config;
14use crate::console::ConsoleKernel;
15use crate::database::DatabaseManager;
16use crate::encryption::Encrypter;
17use crate::routing::{Registrar, RouteDefinition};
18use crate::session::csrf::CsrfLayer;
19use crate::session::middleware::{SessionConfig, SessionLayer};
20
21pub use event_service_provider::EventServiceProvider;
22pub use route_service_provider::RouteServiceProvider;
23
24pub trait ServiceProvider: Send + Sync {
25    fn register(&self, app: &Application);
26    fn boot(&self, _app: &Application) {}
27    fn provides(&self) -> Vec<&'static str> {
28        vec![]
29    }
30}
31
32/// Marker trait for providers that should be lazily registered and booted.
33///
34/// Implement this trait on your provider to defer `register()` and `boot()`
35/// until one of the services listed in `provides()` is first resolved via
36/// [`Application::make`] or [`Application::make_by_alias`].
37///
38/// This matches Laravel's deferred provider pattern.
39pub trait DeferrableProvider: ServiceProvider {}
40
41#[derive(Clone)]
42pub struct Application {
43    inner: Arc<Mutex<AppInner>>,
44}
45
46/// A conditional container binding, mirroring Laravel's `#[BindWhen]`.
47///
48/// The binding is only active when its `condition` returns `true` against the
49/// application's [`Config`]. Rules are evaluated in declaration order and the
50/// first one whose condition holds is the one used when the binding name is
51/// resolved via [`Application::make_by_alias`].
52pub struct ConditionalBinding {
53    /// The condition that gates this binding.
54    pub condition: Box<dyn Fn(&Config) -> bool + Send + Sync>,
55    /// The instance returned when the condition holds.
56    pub instance: Box<dyn Any + Send + Sync>,
57}
58
59impl ConditionalBinding {
60    pub fn new(
61        condition: impl Fn(&Config) -> bool + Send + Sync + 'static,
62        instance: impl Any + Send + Sync + 'static,
63    ) -> Self {
64        Self {
65            condition: Box::new(condition),
66            instance: Box::new(instance),
67        }
68    }
69}
70
71/// Whether a config value parses as a truthy token.
72///
73/// Tolerates the quoted string form (`"1"`) produced by `Config::get` for
74/// values stored in the `extra` section.
75pub fn config_truthy(config: &Config, key: &str) -> bool {
76    config
77        .get(key)
78        .map(|v| {
79            let v = v.trim().trim_matches('"');
80            matches!(v, "1" | "true" | "yes" | "on")
81        })
82        .unwrap_or(false)
83}
84
85struct AppInner {
86    instances: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
87    aliases: HashMap<String, TypeId>,
88    conditional_bindings: HashMap<String, Vec<ConditionalBinding>>,
89    config: Config,
90    console: Option<ConsoleKernel>,
91    db: Option<DatabaseManager>,
92    base_path: PathBuf,
93    booted: bool,
94    providers: Vec<Arc<dyn ServiceProvider>>,
95    deferred_providers: Vec<Arc<dyn ServiceProvider>>,
96    deferred_providers_by_name: HashMap<String, Arc<dyn ServiceProvider>>,
97    router: Arc<Mutex<AxumRouter>>,
98    routes: Arc<Mutex<Vec<RouteDefinition>>>,
99    layers: Vec<Box<dyn FnOnce(AxumRouter) -> AxumRouter + Send>>,
100}
101
102impl Application {
103    pub fn new(base_path: Option<PathBuf>) -> Self {
104        let path = base_path.unwrap_or_else(|| PathBuf::from("."));
105        let config = Config::load(&path);
106
107        let inner = Arc::new(Mutex::new(AppInner {
108            instances: HashMap::new(),
109            aliases: HashMap::new(),
110            conditional_bindings: HashMap::new(),
111            config,
112            console: None,
113            db: None,
114            base_path: path,
115            booted: false,
116            providers: Vec::new(),
117            deferred_providers: Vec::new(),
118            deferred_providers_by_name: HashMap::new(),
119            router: Arc::new(Mutex::new(AxumRouter::new())),
120            routes: Arc::new(Mutex::new(vec![])),
121            layers: Vec::new(),
122        }));
123
124        Self { inner }
125    }
126
127    pub fn base_path(&self) -> PathBuf {
128        self.inner.lock().unwrap().base_path.clone()
129    }
130
131    pub fn config(&self) -> Config {
132        self.inner.lock().unwrap().config.clone()
133    }
134
135    /// Whether the config value at `key` parses as a truthy token.
136    ///
137    /// Convenience wrapper around [`config_truthy`]; used by `#[bind_when]`'s
138    /// generated `conditional_enabled`.
139    pub fn config_bool(&self, key: &str) -> bool {
140        let config = self.config();
141        config_truthy(&config, key)
142    }
143
144    /// Replace the application configuration at runtime.
145    pub fn set_config(&self, config: Config) {
146        self.inner.lock().unwrap().config = config;
147    }
148
149    /// Register a provider that will be eagerly registered and booted.
150    pub fn register_provider(&self, provider: Arc<dyn ServiceProvider>) {
151        provider.register(self);
152        let mut inner = self.inner.lock().unwrap();
153        if inner.booted {
154            provider.boot(self);
155        }
156        inner.providers.push(provider);
157    }
158
159    /// Register a provider whose `register()` and `boot()` are deferred
160    /// until one of its provided services is first resolved via
161    /// [`make`](Self::make) or [`make_by_alias`](Self::make_by_alias).
162    ///
163    /// The provider **must** return a non-empty list from `provides()`.
164    /// If `provides()` is empty the provider will never be activated.
165    pub fn register_deferred_provider(&self, provider: Arc<dyn ServiceProvider>) {
166        let mut inner = self.inner.lock().unwrap();
167        for name in provider.provides() {
168            inner
169                .deferred_providers_by_name
170                .insert(name.to_string(), provider.clone());
171        }
172        inner.deferred_providers.push(provider);
173    }
174
175    /// Boot all eager providers (idempotent).
176    pub fn boot(&self) {
177        let providers_to_boot = {
178            let mut inner = self.inner.lock().unwrap();
179            if inner.booted {
180                return;
181            }
182            inner.booted = true;
183            inner.providers.clone()
184        };
185
186        info!("Application booted");
187
188        for provider in &providers_to_boot {
189            provider.boot(self);
190        }
191    }
192
193    /// Bind an instance into the container by its type.
194    pub fn bind<T: Any + Send + Sync>(&self, instance: T) {
195        let id = TypeId::of::<T>();
196        self.inner
197            .lock()
198            .unwrap()
199            .instances
200            .insert(id, Box::new(instance));
201    }
202
203    /// Bind a shared (singleton) instance into the container.
204    pub fn singleton<T: Any + Send + Sync + Clone>(&self, instance: T) {
205        self.bind(instance);
206    }
207
208    /// Resolve a previously bound instance by type.
209    ///
210    /// If the type matches a service provided by a deferred provider, that
211    /// provider will be registered and booted before the instance is returned.
212    pub fn make<T: Any + Send + Sync + Clone>(&self) -> Option<T> {
213        self.boot_deferred_for::<T>();
214        let inner = self.inner.lock().unwrap();
215        let id = TypeId::of::<T>();
216        inner
217            .instances
218            .get(&id)
219            .and_then(|b| b.downcast_ref::<T>())
220            .cloned()
221    }
222
223    /// Resolve a previously bound instance by string alias.
224    ///
225    /// Conditional bindings registered with [`bind_if`](Self::bind_if) take
226    /// precedence: each condition is evaluated in declaration order and the
227    /// first match is returned. Otherwise the plain alias – if any – is used.
228    ///
229    /// If the alias matches a service provided by a deferred provider, that
230    /// provider will be registered and booted before the instance is returned.
231    pub fn make_by_alias<T: Any + Send + Sync + Clone>(&self, alias: &str) -> Option<T> {
232        self.boot_deferred_for_name(alias);
233
234        if let Some(instance) = self.resolve_conditional::<T>(alias) {
235            return Some(instance);
236        }
237
238        let inner = self.inner.lock().unwrap();
239        let id = inner.aliases.get(alias)?;
240        inner
241            .instances
242            .get(id)
243            .and_then(|b| b.downcast_ref::<T>())
244            .cloned()
245    }
246
247    /// Register a conditional binding under `name`.
248    ///
249    /// This mirrors Laravel's `#[BindWhen]` attribute: when `name` is resolved
250    /// via [`make_by_alias`](Self::make_by_alias), each `condition` is
251    /// evaluated in declaration order against the application config and the
252    /// instance of the first matching rule is returned. Later rules act as
253    /// fallbacks.
254    pub fn bind_if<T: Any + Send + Sync + 'static>(
255        &self,
256        name: impl Into<String>,
257        condition: impl Fn(&Config) -> bool + Send + Sync + 'static,
258        instance: T,
259    ) {
260        self.inner
261            .lock()
262            .unwrap()
263            .conditional_bindings
264            .entry(name.into())
265            .or_default()
266            .push(ConditionalBinding::new(condition, instance));
267    }
268
269    /// Register a convenience conditional binding gated on a config key.
270    ///
271    /// The condition holds when the config value at `config_key` parses as a
272    /// truthy token (`"1"`, `"true"`, `"yes"`).
273    pub fn bind_if_config<T: Any + Send + Sync + 'static>(
274        &self,
275        name: impl Into<String>,
276        config_key: impl Into<String>,
277        instance: T,
278    ) {
279        let key = config_key.into();
280        let condition = move |config: &Config| config_truthy(config, &key);
281        self.bind_if(name, condition, instance);
282    }
283
284    /// Register an unconditional fallback binding for a conditional name.
285    ///
286    /// A conditional name whose `bind_if` rules all return false stays
287    /// resolvable when a default binding is also registered.
288    pub fn bind_default<T: Any + Send + Sync + 'static>(
289        &self,
290        name: impl Into<String>,
291        instance: T,
292    ) {
293        self.bind_if(name, |_| true, instance);
294    }
295
296    /// Evaluate the conditional bindings registered for `name` in declaration
297    /// order and return the first matching instance, cloned as `T`.
298    fn resolve_conditional<T: Any + Send + Sync + Clone>(&self, name: &str) -> Option<T> {
299        let inner = self.inner.lock().unwrap();
300        let rules = inner.conditional_bindings.get(name)?;
301        let config = inner.config.clone();
302        rules
303            .iter()
304            .find(|r| (r.condition)(&config))
305            .and_then(|r| r.instance.downcast_ref::<T>())
306            .cloned()
307    }
308
309    /// Activate deferred providers whose provided services match `T`'s alias.
310    fn boot_deferred_for<T: 'static>(&self) {
311        let tid = TypeId::of::<T>();
312        let names: Vec<String> = {
313            let inner = self.inner.lock().unwrap();
314            inner
315                .aliases
316                .iter()
317                .filter(|(_, id)| **id == tid)
318                .map(|(name, _)| name.clone())
319                .collect()
320        };
321
322        for name in &names {
323            self.activate_deferred_provider(name);
324        }
325    }
326
327    /// Activate any deferred provider that provides a service matching `name`.
328    fn boot_deferred_for_name(&self, name: &str) {
329        self.activate_deferred_provider(name);
330    }
331
332    /// Internal: register & boot the deferred provider that provides `name`,
333    /// then remove it from the deferred lists.
334    fn activate_deferred_provider(&self, name: &str) {
335        let provider = {
336            let mut inner = self.inner.lock().unwrap();
337            inner.deferred_providers_by_name.remove(name)
338        };
339
340        if let Some(p) = provider {
341            p.register(self);
342            p.boot(self);
343            // Remove from deferred_providers vec too
344            let mut inner = self.inner.lock().unwrap();
345            inner.deferred_providers.retain(|d| !Arc::ptr_eq(d, &p));
346        }
347    }
348
349    pub fn alias(&self, alias: &str, id: TypeId) {
350        self.inner
351            .lock()
352            .unwrap()
353            .aliases
354            .insert(alias.to_string(), id);
355    }
356
357    pub fn database(&self) -> Option<DatabaseManager> {
358        self.inner.lock().unwrap().db.clone()
359    }
360
361    pub fn with_database(self, db: DatabaseManager) -> Self {
362        self.inner.lock().unwrap().db = Some(db);
363        self
364    }
365
366    pub fn console_kernel(&self) -> ConsoleKernel {
367        let mut inner = self.inner.lock().unwrap();
368        inner
369            .console
370            .get_or_insert_with(|| ConsoleKernel::new(self.clone()))
371            .clone()
372    }
373
374    pub fn router(&self) -> Registrar {
375        let inner = self.inner.lock().unwrap();
376        Registrar::new(inner.router.clone(), inner.routes.clone())
377    }
378
379    /// Check if the application has been booted.
380    pub fn is_booted(&self) -> bool {
381        self.inner.lock().unwrap().booted
382    }
383
384    /// Return the number of registered providers (eager + deferred).
385    pub fn provider_count(&self) -> usize {
386        let inner = self.inner.lock().unwrap();
387        inner.providers.len() + inner.deferred_providers.len()
388    }
389
390    /// Return the number of deferred providers awaiting activation.
391    pub fn deferred_provider_count(&self) -> usize {
392        self.inner.lock().unwrap().deferred_providers.len()
393    }
394
395    /// Add a Tower layer or Axum extension to the final router.
396    ///
397    /// The closure receives the fully-built `Router` (after all routes and
398    /// the `/health` endpoint are registered) and must return a router.
399    ///
400    /// This is used to add middleware, CORS, compression, or Axum
401    /// `Extension<T>` state to the application:
402    ///
403    /// ```rust,ignore
404    /// app.with_layer(|router| router.layer(Extension(my_state)));
405    /// ```
406    pub fn with_layer(&self, f: impl FnOnce(AxumRouter) -> AxumRouter + Send + 'static) {
407        self.inner.lock().unwrap().layers.push(Box::new(f));
408    }
409
410    pub async fn run(self) {
411        self.boot();
412
413        let router = {
414            let inner = self.inner.lock().unwrap();
415            let registrar = Registrar::new(inner.router.clone(), inner.routes.clone());
416            registrar.build()
417        };
418
419        // Auto-wire SessionLayer and CsrfLayer when an app key is configured.
420        {
421            let config = self.config();
422            if let Some(key) = &config.app.key {
423                if let Ok(encrypter) = Encrypter::new(key.as_bytes()) {
424                    let session_layer =
425                        SessionLayer::new(SessionConfig::default(), Some(Arc::new(encrypter)));
426                    let csrf_layer =
427                        CsrfLayer::new().except(vec!["/api/*".to_string(), "/health".to_string()]);
428
429                    let mut inner = self.inner.lock().unwrap();
430                    inner
431                        .layers
432                        .push(Box::new(move |router: AxumRouter| -> AxumRouter {
433                            router.layer(csrf_layer).layer(session_layer)
434                        }));
435                }
436            }
437        }
438
439        // Apply user-registered layers/extensions to the final router.
440        let router = {
441            let mut inner = self.inner.lock().unwrap();
442            let layers = std::mem::take(&mut inner.layers);
443            layers.into_iter().fold(router, |r, layer| layer(r))
444        };
445
446        let addr = self
447            .config()
448            .get("app.url")
449            .unwrap_or_else(|| "0.0.0.0:8080".to_string())
450            .replace("http://", "")
451            .trim_end_matches('/')
452            .to_string();
453        let addr = if addr.contains(':') {
454            addr
455        } else {
456            format!("{}:8080", addr)
457        };
458
459        info!("Larastvel server starting on {}", addr);
460        let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
461        axum::serve(listener, router).await.unwrap();
462    }
463}
464
465pub trait Kernel: Send + Sync {
466    fn register_providers(&self, app: &Application);
467    fn register_routes(&self, app: &Application);
468    fn boot(&self, app: &Application);
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474
475    #[test]
476    fn test_application_new_uses_default_config() {
477        let app = Application::new(None);
478        assert_eq!(app.config().app.name, "larastvel");
479    }
480
481    #[test]
482    fn test_application_base_path_defaults_to_dot() {
483        let app = Application::new(None);
484        assert_eq!(app.base_path(), std::path::PathBuf::from("."));
485    }
486
487    #[test]
488    fn test_application_base_path_custom() {
489        let app = Application::new(Some(std::path::PathBuf::from("/tmp")));
490        assert_eq!(app.base_path(), std::path::PathBuf::from("/tmp"));
491    }
492
493    #[test]
494    fn test_application_bind_and_make() {
495        let app = Application::new(None);
496        app.bind(42i32);
497        let val: Option<i32> = app.make();
498        assert_eq!(val, Some(42));
499    }
500
501    #[test]
502    fn test_application_make_nonexistent() {
503        let app = Application::new(None);
504        let val: Option<String> = app.make();
505        assert!(val.is_none());
506    }
507
508    #[test]
509    fn test_application_singleton() {
510        let app = Application::new(None);
511        app.singleton("shared".to_string());
512        let val: Option<String> = app.make();
513        assert_eq!(val, Some("shared".to_string()));
514    }
515
516    #[test]
517    fn test_application_boot_twice_is_idempotent() {
518        let app = Application::new(None);
519        app.boot();
520        app.boot();
521    }
522
523    #[test]
524    fn test_application_database_is_none_by_default() {
525        let app = Application::new(None);
526        assert!(app.database().is_none());
527    }
528
529    #[test]
530    fn test_application_router_returns_registrar() {
531        let app = Application::new(None);
532        let registrar = app.router();
533        registrar.get("/ping", || async { "pong" });
534        let routes = registrar.list_routes();
535        assert_eq!(routes.len(), 1);
536        assert_eq!(routes[0].uri, "/ping");
537    }
538
539    #[test]
540    fn test_service_provider_trait() {
541        struct TestProvider;
542        impl ServiceProvider for TestProvider {
543            fn register(&self, _app: &Application) {}
544        }
545        let provider = TestProvider;
546        assert!(provider.provides().is_empty());
547    }
548
549    // -----------------------------------------------------------------------
550    // Deferred provider tests
551    // -----------------------------------------------------------------------
552
553    #[test]
554    fn test_register_deferred_provider_not_booted_immediately() {
555        struct DeferredTest;
556        impl ServiceProvider for DeferredTest {
557            fn register(&self, _app: &Application) {}
558            fn provides(&self) -> Vec<&'static str> {
559                vec!["deferred-service"]
560            }
561        }
562
563        let app = Application::new(None);
564        app.register_deferred_provider(Arc::new(DeferredTest));
565
566        // Deferred provider should not be in the eager providers list
567        assert_eq!(app.provider_count(), 1);
568        // Provider count is 1 (deferred) + 0 (eager)
569        assert_eq!(app.deferred_provider_count(), 1);
570    }
571
572    #[test]
573    fn test_deferred_provider_activated_on_make_by_alias() {
574        static REGISTERED: std::sync::atomic::AtomicBool =
575            std::sync::atomic::AtomicBool::new(false);
576        static BOOTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
577
578        struct DeferredTest;
579        impl ServiceProvider for DeferredTest {
580            fn register(&self, app: &Application) {
581                REGISTERED.store(true, std::sync::atomic::Ordering::SeqCst);
582                app.bind(42i32);
583            }
584            fn boot(&self, _app: &Application) {
585                BOOTED.store(true, std::sync::atomic::Ordering::SeqCst);
586            }
587            fn provides(&self) -> Vec<&'static str> {
588                vec!["the-answer"]
589            }
590        }
591
592        let app = Application::new(None);
593        app.alias("the-answer", TypeId::of::<i32>());
594        app.register_deferred_provider(Arc::new(DeferredTest));
595
596        assert!(!REGISTERED.load(std::sync::atomic::Ordering::SeqCst));
597        assert!(!BOOTED.load(std::sync::atomic::Ordering::SeqCst));
598
599        let val: Option<i32> = app.make();
600        assert_eq!(val, Some(42));
601        assert!(REGISTERED.load(std::sync::atomic::Ordering::SeqCst));
602        assert!(BOOTED.load(std::sync::atomic::Ordering::SeqCst));
603        assert_eq!(app.deferred_provider_count(), 0);
604    }
605
606    #[test]
607    fn test_deferred_provider_not_activated_for_unrelated_types() {
608        static CALLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
609
610        struct DeferredTest;
611        impl ServiceProvider for DeferredTest {
612            fn register(&self, _app: &Application) {
613                CALLED.store(true, std::sync::atomic::Ordering::SeqCst);
614            }
615            fn provides(&self) -> Vec<&'static str> {
616                vec!["only-service"]
617            }
618        }
619
620        let app = Application::new(None);
621        app.alias("only-service", TypeId::of::<String>());
622        app.register_deferred_provider(Arc::new(DeferredTest));
623
624        // Make a different type — should NOT activate the deferred provider
625        app.bind(99i32);
626        let _: Option<i32> = app.make();
627
628        assert!(!CALLED.load(std::sync::atomic::Ordering::SeqCst));
629        assert_eq!(app.deferred_provider_count(), 1);
630    }
631
632    #[test]
633    fn test_register_deferred_provider_with_empty_provides_not_activated() {
634        // Providers with empty provides() list cannot be activated because
635        // there's no service name to trigger deferral. This is expected
636        // (programmer error) — our deferred provider requires provides().
637        struct EmptyProvides;
638        impl ServiceProvider for EmptyProvides {
639            fn register(&self, _app: &Application) {}
640            fn provides(&self) -> Vec<&'static str> {
641                vec![]
642            }
643        }
644
645        let app = Application::new(None);
646        app.register_deferred_provider(Arc::new(EmptyProvides));
647        assert_eq!(app.deferred_provider_count(), 1);
648        // Never activated since nothing can trigger it
649    }
650
651    #[test]
652    fn test_eager_provider_registered_and_booted_normally() {
653        static REGISTERED: std::sync::atomic::AtomicBool =
654            std::sync::atomic::AtomicBool::new(false);
655
656        struct EagerTest;
657        impl ServiceProvider for EagerTest {
658            fn register(&self, _app: &Application) {
659                REGISTERED.store(true, std::sync::atomic::Ordering::SeqCst);
660            }
661            fn provides(&self) -> Vec<&'static str> {
662                vec!["eager"]
663            }
664        }
665
666        let app = Application::new(None);
667        app.register_provider(Arc::new(EagerTest));
668
669        assert!(REGISTERED.load(std::sync::atomic::Ordering::SeqCst));
670        assert_eq!(app.provider_count(), 1);
671        assert_eq!(app.deferred_provider_count(), 0);
672    }
673
674    #[test]
675    fn test_mixed_eager_and_deferred_providers() {
676        static EAGER_REGISTERED: std::sync::atomic::AtomicBool =
677            std::sync::atomic::AtomicBool::new(false);
678        static DEFERRED_REGISTERED: std::sync::atomic::AtomicBool =
679            std::sync::atomic::AtomicBool::new(false);
680
681        struct EagerTest;
682        impl ServiceProvider for EagerTest {
683            fn register(&self, _app: &Application) {
684                EAGER_REGISTERED.store(true, std::sync::atomic::Ordering::SeqCst);
685            }
686            fn provides(&self) -> Vec<&'static str> {
687                vec!["eager-svc"]
688            }
689        }
690
691        struct DeferredTest;
692        impl ServiceProvider for DeferredTest {
693            fn register(&self, _app: &Application) {
694                DEFERRED_REGISTERED.store(true, std::sync::atomic::Ordering::SeqCst);
695            }
696            fn provides(&self) -> Vec<&'static str> {
697                vec!["deferred-svc"]
698            }
699        }
700
701        let app = Application::new(None);
702        app.alias("deferred-svc", TypeId::of::<String>());
703        app.register_provider(Arc::new(EagerTest));
704        app.register_deferred_provider(Arc::new(DeferredTest));
705
706        assert!(EAGER_REGISTERED.load(std::sync::atomic::Ordering::SeqCst));
707        assert!(!DEFERRED_REGISTERED.load(std::sync::atomic::Ordering::SeqCst));
708
709        assert_eq!(app.provider_count(), 2);
710        assert_eq!(app.deferred_provider_count(), 1);
711    }
712
713    #[test]
714    fn test_deferred_provider_boot_not_called_if_not_resolved() {
715        static BOOTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
716
717        struct DeferredTest;
718        impl ServiceProvider for DeferredTest {
719            fn register(&self, _app: &Application) {}
720            fn boot(&self, _app: &Application) {
721                BOOTED.store(true, std::sync::atomic::Ordering::SeqCst);
722            }
723            fn provides(&self) -> Vec<&'static str> {
724                vec!["never-resolved"]
725            }
726        }
727
728        let app = Application::new(None);
729        app.alias("never-resolved", TypeId::of::<String>());
730        app.register_deferred_provider(Arc::new(DeferredTest));
731
732        // Boot the app — deferred providers should NOT be booted
733        app.boot();
734        assert!(!BOOTED.load(std::sync::atomic::Ordering::SeqCst));
735    }
736
737    // -----------------------------------------------------------------------
738    // #[provider] macro tests
739    // -----------------------------------------------------------------------
740
741    use larastvel_macros::provider;
742
743    #[provider]
744    struct TestAppProvider;
745
746    impl TestAppProvider {
747        fn register_services(&self, _app: &Application) {
748            // no-op for testing
749        }
750    }
751
752    #[test]
753    fn test_bind_if_config_conditional_binding() {
754        let app = Application::new(None);
755        app.bind_if_config(
756            "gateway",
757            "features.payments.beta",
758            "beta-gateway".to_string(),
759        );
760        assert!(app.make_by_alias::<String>("gateway").is_none());
761    }
762
763    #[test]
764    fn test_conditional_binding_first_match_by_declaration_order() {
765        let app = Application::new(None);
766        app.bind_if_config("gateway", "features.payments.beta", "beta".to_string());
767        app.bind_default("gateway", "fallback".to_string());
768
769        let mut config = app.config();
770        config.set("features.payments.beta", "1");
771        app.set_config(config);
772
773        let resolved: Option<String> = app.make_by_alias("gateway");
774        assert_eq!(resolved, Some("beta".to_string()));
775    }
776
777    #[test]
778    fn test_conditional_binding_falls_back_to_default() {
779        let app = Application::new(None);
780        app.bind_if_config("gateway", "features.payments.beta", "beta".to_string());
781        app.bind_default("gateway", "fallback".to_string());
782
783        let resolved: Option<String> = app.make_by_alias("gateway");
784        assert_eq!(resolved, Some("fallback".to_string()));
785    }
786
787    #[test]
788    fn test_conditional_binding_closure_condition_on_config() {
789        let app = Application::new(None);
790        app.bind_if(
791            "gateway",
792            |config| config.get("app.env") == Some("production".to_string()),
793            "prod".to_string(),
794        );
795        app.bind_default("gateway", "dev".to_string());
796
797        assert_eq!(
798            app.make_by_alias::<String>("gateway"),
799            Some("dev".to_string())
800        );
801
802        let mut config = app.config();
803        config.set("app.env", "production");
804        app.set_config(config);
805        assert_eq!(
806            app.make_by_alias::<String>("gateway"),
807            Some("prod".to_string())
808        );
809    }
810
811    #[test]
812    fn test_conditional_binding_does_not_affect_plain_aliases() {
813        let app = Application::new(None);
814        app.alias("answer", std::any::TypeId::of::<i32>());
815        app.bind(42i32);
816        assert_eq!(app.make_by_alias::<i32>("answer"), Some(42));
817    }
818
819    // -----------------------------------------------------------------------
820    // #[bind_when] macro tests
821    // -----------------------------------------------------------------------
822
823    use larastvel_macros::bind_when;
824
825    #[bind_when(alias = "payment-gateway", condition_key = "features.payments.beta")]
826    trait PaymentGatewayTestCase: Send + Sync + 'static {
827        fn name(&self) -> &'static str;
828    }
829
830    struct BetaGatewayTestCase;
831    impl PaymentGatewayTestCase for BetaGatewayTestCase {
832        fn name(&self) -> &'static str {
833            "beta"
834        }
835    }
836
837    #[test]
838    fn test_bind_when_macro_constants() {
839        assert_eq!(
840            PaymentGatewayTestCaseConditionalBindings::ALIAS,
841            "payment-gateway"
842        );
843        assert_eq!(
844            PaymentGatewayTestCaseConditionalBindings::CONDITION_KEY,
845            "features.payments.beta"
846        );
847    }
848
849    #[test]
850    fn test_bind_when_macro_registers_and_resolves() {
851        let app = Application::new(None);
852        PaymentGatewayTestCaseConditionalBindings::register_conditional_binding(&app, || {
853            std::sync::Arc::new(BetaGatewayTestCase) as std::sync::Arc<dyn PaymentGatewayTestCase>
854        });
855
856        let mut config = app.config();
857        config.set(
858            PaymentGatewayTestCaseConditionalBindings::CONDITION_KEY,
859            "1",
860        );
861        app.set_config(config);
862
863        assert!(PaymentGatewayTestCaseConditionalBindings::conditional_enabled(&app));
864        let gateway = PaymentGatewayTestCaseConditionalBindings::resolve(&app);
865        assert!(gateway.is_some());
866        assert_eq!(gateway.unwrap().name(), "beta");
867    }
868
869    #[test]
870    fn test_bind_when_macro_not_enabled_when_config_false() {
871        let app = Application::new(None);
872        PaymentGatewayTestCaseConditionalBindings::register_conditional_binding(&app, || {
873            std::sync::Arc::new(BetaGatewayTestCase) as std::sync::Arc<dyn PaymentGatewayTestCase>
874        });
875
876        assert!(!PaymentGatewayTestCaseConditionalBindings::conditional_enabled(&app));
877        assert!(PaymentGatewayTestCaseConditionalBindings::resolve(&app).is_none());
878    }
879
880    #[test]
881    fn test_provider_macro_implements_trait() {
882        fn assert_provider<P: ServiceProvider>() {}
883        assert_provider::<TestAppProvider>();
884    }
885
886    #[test]
887    fn test_provider_macro_register_delegates() {
888        let provider = TestAppProvider;
889        let app = Application::new(None);
890        // Should not panic — verifies register_services is called
891        provider.register(&app);
892    }
893
894    #[test]
895    fn test_provider_macro_boot_default() {
896        let provider = TestAppProvider;
897        let app = Application::new(None);
898        // Should use trait default (no-op)
899        provider.boot(&app);
900    }
901
902    #[test]
903    fn test_provider_macro_provides_default() {
904        let provider = TestAppProvider;
905        assert!(provider.provides().is_empty());
906    }
907
908    /// Provider that actually registers a service
909    #[provider]
910    struct RegistrationProvider;
911
912    impl RegistrationProvider {
913        fn register_services(&self, app: &Application) {
914            app.bind(42u32);
915        }
916    }
917
918    #[test]
919    fn test_provider_macro_actual_registration() {
920        let app = Application::new(None);
921        let provider = RegistrationProvider;
922        provider.register(&app);
923        let val: u32 = app.make::<u32>().unwrap();
924        assert_eq!(val, 42);
925    }
926}