caelix-core 0.0.30

Core primitives for the Caelix framework.
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
use crate::{
    BoxFuture, Container, Controller, EventHandler, EventHandlerDef, Injectable, MessageHandlerDef,
    MessageHandlerKind, Microservice, MicroserviceDef, RegisterableEventHandler, Result,
    WebSocketGateway,
};
use std::{
    any::{Any, TypeId},
    collections::{HashMap, HashSet},
    fmt::Debug,
    future::Future,
    sync::Arc,
    time::Instant,
};

type ProviderValue = Arc<dyn Any + Send + Sync>;
type BuildProviderFn =
    Box<dyn for<'a> Fn(&'a Container) -> BoxFuture<'a, crate::Result<ProviderValue>> + Send + Sync>;
type LifecycleFn =
    Box<dyn for<'a> Fn(&'a ProviderValue) -> BoxFuture<'a, crate::Result<()>> + Send + Sync>;

/// Metadata for one resolved provider dependency.
#[derive(Clone, Copy)]
/// Public Caelix type `ProviderDependency`.
pub struct ProviderDependency {
    type_id: TypeId,
    type_name: &'static str,
}

impl ProviderDependency {
    /// Runs the `of` public API operation.
    pub fn of<T: Send + Sync + 'static>() -> Self {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
        }
    }

    pub(crate) fn type_id(&self) -> TypeId {
        self.type_id
    }
}

/// Declares provider dependencies for manual `Injectable` implementations and factories.
/// Builds the explicit dependency list required by a handwritten
/// [`Injectable`](crate::Injectable) implementation.
///
/// Pass zero or more provider types, for example
/// `provider_dependencies![UserRepository, Logger]`. The returned metadata is
/// used during module visibility validation before the provider is constructed.
#[macro_export]
macro_rules! provider_dependencies {
    ($($dependency:ty),* $(,)?) => {
        vec![$($crate::ProviderDependency::of::<$dependency>()),*]
    };
}

/// Public Caelix type `ProviderDef`.
pub struct ProviderDef {
    type_id: TypeId,
    type_name: &'static str,
    dependencies: Vec<ProviderDependency>,
    build: BuildProviderFn,
    init_fn: LifecycleFn,
    bootstrap_fn: LifecycleFn,
    shutdown_fn: LifecycleFn,
}

impl ProviderDef {
    /// Runs the `of` public API operation.
    pub fn of<T: Injectable>() -> Self {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
            dependencies: T::dependencies(),
            build: Box::new(|container| {
                Box::pin(async move { Ok(Arc::new(T::create(container).await?) as ProviderValue) })
            }),
            init_fn: Box::new(|value| {
                let value = downcast_provider::<T>(value);
                Box::pin(async move { value?.on_module_init().await })
            }),
            bootstrap_fn: Box::new(|value| {
                let value = downcast_provider::<T>(value);
                Box::pin(async move { value?.on_bootstrap().await })
            }),
            shutdown_fn: Box::new(|value| {
                let value = downcast_provider::<T>(value);
                Box::pin(async move { value?.on_shutdown().await })
            }),
        }
    }

    /// Pre-built provider value for tests and other manual registration paths.
    /// Lifecycle hooks are no-ops (`useValue` semantics).
    pub fn instance<T: Send + Sync + 'static>(value: T) -> Self {
        let value = Arc::new(value) as ProviderValue;
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
            dependencies: vec![],
            build: Box::new(move |_| {
                let value = value.clone();
                Box::pin(async move { Ok(value) })
            }),
            init_fn: noop_lifecycle(),
            bootstrap_fn: noop_lifecycle(),
            shutdown_fn: noop_lifecycle(),
        }
    }

    /// Runs the `async_factory` public API operation.
    pub fn async_factory<T, Fut, E>(
        dependencies: Vec<ProviderDependency>,
        factory: impl Fn(Arc<Container>) -> Fut + Send + Sync + 'static,
    ) -> Self
    where
        T: Send + Sync + 'static,
        Fut: Future<Output = std::result::Result<T, E>> + Send + 'static,
        E: Debug + Send + 'static,
    {
        Self {
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>(),
            dependencies,
            build: Box::new(move |container| {
                let future = factory(Arc::new(container.clone()));
                Box::pin(async move {
                    let value = future.await.map_err(|err| {
                        crate::exception::startup_error(format!(
                            "async factory failed for {}: {:?}",
                            std::any::type_name::<T>(),
                            err
                        ))
                    })?;
                    Ok(Arc::new(value) as ProviderValue)
                })
            }),
            init_fn: noop_lifecycle(),
            bootstrap_fn: noop_lifecycle(),
            shutdown_fn: noop_lifecycle(),
        }
    }

    /// Runs the `type_id` public API operation.
    pub fn type_id(&self) -> TypeId {
        self.type_id
    }
    /// Runs the `type_name` public API operation.
    pub fn type_name(&self) -> &'static str {
        self.type_name
    }

    fn assert_registered(&self, container: &Container) -> crate::Result<()> {
        if container.contains_type_id(self.type_id) {
            return Ok(());
        }
        Err(crate::exception::startup_error(format!(
            "missing provider at startup: {} was declared by module metadata but was not registered",
            self.type_name
        )))
    }

    async fn run_lifecycle(
        &self,
        value: &ProviderValue,
        hook: &'static str,
        callback: &LifecycleFn,
    ) -> crate::Result<()> {
        callback(value).await.map_err(|err| {
            crate::exception::startup_error(format!(
                "{hook} failed for {}: {}: {}",
                self.type_name, err.error, err.message
            ))
        })
    }

    async fn run_lifecycle_from_container(
        &self,
        container: &Container,
        hook: &'static str,
        callback: &LifecycleFn,
    ) -> crate::Result<()> {
        let value = container.resolve_erased(self.type_id).ok_or_else(|| crate::exception::startup_error(format!(
            "missing provider during {hook}: {} was declared by module metadata but was not registered", self.type_name
        )))?;
        self.run_lifecycle(&value, hook, callback).await
    }
}

/// Public Caelix type `ProviderOverrides`.
pub struct ProviderOverrides {
    defs: HashMap<TypeId, ProviderDef>,
}
impl ProviderOverrides {
    /// Runs the `new` public API operation.
    pub fn new() -> Self {
        Self {
            defs: HashMap::new(),
        }
    }
    /// Runs the `insert_instance` public API operation.
    pub fn insert_instance<T: Send + Sync + 'static>(mut self, value: T) -> Self {
        self.defs
            .insert(TypeId::of::<T>(), ProviderDef::instance(value));
        self
    }
    /// Runs the `insert_factory` public API operation.
    pub fn insert_factory<T, Fut, E>(
        mut self,
        dependencies: Vec<ProviderDependency>,
        factory: impl Fn(Arc<Container>) -> Fut + Send + Sync + 'static,
    ) -> Self
    where
        T: Send + Sync + 'static,
        Fut: Future<Output = std::result::Result<T, E>> + Send + 'static,
        E: Debug + Send + 'static,
    {
        self.defs.insert(
            TypeId::of::<T>(),
            ProviderDef::async_factory::<T, Fut, E>(dependencies, factory),
        );
        self
    }
    /// Runs the `insert` public API operation.
    pub fn insert(mut self, def: ProviderDef) -> Self {
        self.defs.insert(def.type_id, def);
        self
    }
    pub(crate) fn into_inner(self) -> HashMap<TypeId, ProviderDef> {
        self.defs
    }
}
impl Default for ProviderOverrides {
    fn default() -> Self {
        Self::new()
    }
}

fn downcast_provider<T: Send + Sync + 'static>(value: &ProviderValue) -> crate::Result<Arc<T>> {
    value.clone().downcast::<T>().map_err(|_| {
        crate::exception::startup_error(format!(
            "type mismatch running lifecycle hook for {}",
            std::any::type_name::<T>()
        ))
    })
}
fn noop_lifecycle() -> LifecycleFn {
    Box::new(|_| Box::pin(async { Ok(()) }))
}

/// Public Caelix type `ControllerDef`.
pub struct ControllerDef {
    /// The `register_fn` value.
    pub register_fn: fn(&mut dyn Any),
    /// The `route_log_fn` value.
    pub route_log_fn: fn(),
    pub(crate) route_count_fn: fn() -> usize,
    #[cfg(feature = "openapi")]
    pub(crate) openapi_routes_fn: fn() -> &'static [crate::openapi::OpenApiRouteDef],
    provider: ProviderDef,
}
impl ControllerDef {
    /// Runs the `of` public API operation.
    pub fn of<C: Controller + Injectable + 'static>() -> Self {
        let mut provider = ProviderDef::of::<C>();
        for dependency in C::route_dependencies() {
            if !provider
                .dependencies
                .iter()
                .any(|existing| existing.type_id == dependency.type_id)
            {
                provider.dependencies.push(dependency);
            }
        }
        Self {
            register_fn: |any| C::register_routes(any),
            route_log_fn: || crate::log_controller_routes::<C>(),
            route_count_fn: || C::routes().len(),
            #[cfg(feature = "openapi")]
            openapi_routes_fn: || C::openapi_routes(),
            provider,
        }
    }
}

/// Public Caelix type `GatewayDef`.
pub struct GatewayDef {
    /// The `path` value.
    pub path: &'static str,
    /// The `type_id` value.
    pub type_id: TypeId,
    provider: ProviderDef,
    kind: GatewayKind,
}
enum GatewayKind {
    WebSocket {
        resolve_fn: fn(&Container) -> crate::Result<Arc<dyn WebSocketGateway>>,
    },
    SocketIo {
        register_fn: fn(&Container, &dyn Any) -> Result<()>,
    },
}
impl GatewayDef {
    /// Runs the `websocket` public API operation.
    pub fn websocket<G: WebSocketGateway>(path: &'static str) -> Self {
        Self {
            path,
            type_id: TypeId::of::<G>(),
            provider: ProviderDef::of::<G>(),
            kind: GatewayKind::WebSocket {
                resolve_fn: |c| Ok(c.resolve::<G>()? as Arc<dyn WebSocketGateway>),
            },
        }
    }
    #[doc(hidden)]
    pub fn socket_io<G: Injectable>(
        path: &'static str,
        register_fn: fn(&Container, &dyn Any) -> crate::Result<()>,
    ) -> Self {
        Self {
            path,
            type_id: TypeId::of::<G>(),
            provider: ProviderDef::of::<G>(),
            kind: GatewayKind::SocketIo { register_fn },
        }
    }
    /// Runs the `resolve` public API operation.
    pub fn resolve(&self, container: &Container) -> Result<Arc<dyn WebSocketGateway>> {
        match self.kind {
            GatewayKind::WebSocket { resolve_fn } => resolve_fn(container),
            GatewayKind::SocketIo { .. } => Err(crate::exception::startup_error(format!(
                "Socket.IO gateway {} cannot be mounted by an RFC 6455 application",
                self.path
            ))),
        }
    }
    #[doc(hidden)]
    pub fn is_websocket(&self) -> bool {
        matches!(self.kind, GatewayKind::WebSocket { .. })
    }
    #[doc(hidden)]
    pub fn register_socket_io(&self, container: &Container, handle: &dyn Any) -> Result<()> {
        match self.kind {
            GatewayKind::WebSocket { .. } => Ok(()),
            GatewayKind::SocketIo { register_fn } => register_fn(container, handle),
        }
    }
}
/// Public Caelix extension trait `Gateway`.
pub trait Gateway: Injectable {
    #[doc(hidden)]
    fn definition() -> GatewayDef;
}

/// Public Caelix type `ModuleDef`.
pub struct ModuleDef {
    pub(crate) type_id: TypeId,
    type_name: &'static str,
    pub(crate) metadata_fn: fn() -> ModuleMetadata,
}
impl ModuleDef {
    /// Runs the `of` public API operation.
    pub fn of<M: Module + 'static>() -> Self {
        Self {
            type_id: TypeId::of::<M>(),
            type_name: std::any::type_name::<M>(),
            metadata_fn: M::register,
        }
    }
}
/// Public Caelix extension trait `Module`.
pub trait Module {
    /// Public Caelix API.
    fn register() -> ModuleMetadata;
}

/// Public Caelix type `ModuleMetadata`.
pub struct ModuleMetadata {
    /// The `imports` value.
    pub imports: Vec<ModuleDef>,
    /// The `providers` value.
    pub providers: Vec<ProviderDef>,
    /// The `controllers` value.
    pub controllers: Vec<ControllerDef>,
    /// The `event_handlers` value.
    pub event_handlers: Vec<EventHandlerDef>,
    /// The `gateways` value.
    pub gateways: Vec<GatewayDef>,
    /// The dependency-injected microservice classes declared by this module.
    pub microservices: Vec<MicroserviceDef>,
    exports: Vec<ProviderDependency>,
    global: bool,
}
impl ModuleMetadata {
    /// Runs the `new` public API operation.
    pub fn new() -> Self {
        Self {
            imports: vec![],
            providers: vec![],
            controllers: vec![],
            event_handlers: vec![],
            gateways: vec![],
            microservices: vec![],
            exports: vec![],
            global: false,
        }
    }
    /// Creates metadata for a global module. Only explicitly exported providers become global.
    pub fn global() -> Self {
        let mut metadata = Self::new();
        metadata.global = true;
        metadata
    }
    /// Runs the `import` public API operation.
    pub fn import<M: Module + 'static>(mut self) -> Self {
        self.imports.push(ModuleDef::of::<M>());
        self
    }
    /// Runs the `provider` public API operation.
    pub fn provider<T: Injectable>(mut self) -> Self {
        self.providers.push(ProviderDef::of::<T>());
        self
    }
    /// Runs the `provider_async_factory` public API operation.
    pub fn provider_async_factory<T, Fut, E>(
        mut self,
        dependencies: Vec<ProviderDependency>,
        factory: impl Fn(Arc<Container>) -> Fut + Send + Sync + 'static,
    ) -> Self
    where
        T: Send + Sync + 'static,
        Fut: Future<Output = std::result::Result<T, E>> + Send + 'static,
        E: Debug + Send + 'static,
    {
        self.providers.push(ProviderDef::async_factory::<T, Fut, E>(
            dependencies,
            factory,
        ));
        self
    }
    /// Runs the `controller` public API operation.
    pub fn controller<C: Controller + Injectable + 'static>(mut self) -> Self {
        self.controllers.push(ControllerDef::of::<C>());
        self
    }
    /// Runs the `gateway` public API operation.
    pub fn gateway<G: Gateway>(mut self) -> Self {
        self.gateways.push(G::definition());
        self
    }
    /// Registers a dependency-injected microservice and all of its message handlers.
    ///
    /// A microservice is already a provider; do not additionally register it
    /// with [`Self::provider`].
    pub fn microservice<T: Microservice>(mut self) -> Self {
        self.microservices.push(T::definition());
        self
    }
    /// Runs the `event_handler` public API operation.
    pub fn event_handler<H>(mut self) -> Self
    where
        H: RegisterableEventHandler + EventHandler<H::Event>,
    {
        self.event_handlers.push(EventHandlerDef::of::<H>());
        self
    }
    /// Runs the `event_handler_for` public API operation.
    pub fn event_handler_for<E, H>(mut self) -> Self
    where
        E: Clone + Send + Sync + 'static,
        H: Injectable + EventHandler<E>,
    {
        self.event_handlers
            .push(EventHandlerDef::for_event::<E, H>());
        self
    }
    /// Makes a locally declared provider, or a direct import's export, available to importing modules.
    pub fn export<T: Send + Sync + 'static>(mut self) -> Self {
        self.exports.push(ProviderDependency::of::<T>());
        self
    }
}
impl Default for ModuleMetadata {
    fn default() -> Self {
        Self::new()
    }
}

struct ModuleNode {
    type_id: TypeId,
    type_name: &'static str,
    metadata: ModuleMetadata,
    imports: Vec<usize>,
}
struct ModuleGraph {
    nodes: Vec<ModuleNode>,
}
#[derive(Clone, Copy)]
enum ProviderSlot {
    Provider(usize),
    Controller(usize),
    Gateway(usize),
    Microservice(usize),
}
#[derive(Clone, Copy)]
struct ProviderRegistration {
    module: usize,
    slot: ProviderSlot,
}

impl ModuleGraph {
    fn discover<M: Module + 'static>() -> crate::Result<Self> {
        Self::discover_from(ModuleDef::of::<M>())
    }
    fn discover_from(root: ModuleDef) -> crate::Result<Self> {
        fn visit(
            def: ModuleDef,
            graph: &mut Vec<ModuleNode>,
            states: &mut HashMap<TypeId, u8>,
            path: &mut Vec<&'static str>,
        ) -> crate::Result<usize> {
            match states.get(&def.type_id).copied() {
                Some(2) => {
                    return Ok(graph
                        .iter()
                        .position(|node| node.type_id == def.type_id)
                        .expect("discovered module missing"));
                }
                Some(1) => {
                    let mut cycle = path.clone();
                    cycle.push(def.type_name);
                    return Err(crate::exception::startup_error(format!(
                        "circular module import: {}",
                        cycle.join(" -> ")
                    )));
                }
                _ => {}
            }
            states.insert(def.type_id, 1);
            path.push(def.type_name);
            let metadata = (def.metadata_fn)();
            let index = graph.len();
            graph.push(ModuleNode {
                type_id: def.type_id,
                type_name: def.type_name,
                metadata,
                imports: vec![],
            });
            let imports = std::mem::take(&mut graph[index].metadata.imports);
            for import in imports {
                let child = visit(import, graph, states, path)?;
                graph[index].imports.push(child);
            }
            path.pop();
            states.insert(def.type_id, 2);
            Ok(index)
        }
        let mut nodes = vec![];
        let mut states = HashMap::new();
        let root_index = visit(root, &mut nodes, &mut states, &mut vec![])?;
        // DFS creates parents before children; reverse for imported-first deterministic traversal.
        let mut ordered = Vec::new();
        let mut seen = HashSet::new();
        fn order(
            index: usize,
            nodes: &Vec<ModuleNode>,
            seen: &mut HashSet<usize>,
            ordered: &mut Vec<usize>,
        ) {
            if !seen.insert(index) {
                return;
            }
            for &child in &nodes[index].imports {
                order(child, nodes, seen, ordered);
            }
            ordered.push(index);
        }
        order(root_index, &nodes, &mut seen, &mut ordered);
        let mut remap = HashMap::new();
        for (new, old) in ordered.iter().enumerate() {
            remap.insert(*old, new);
        }
        let mut slots: Vec<Option<ModuleNode>> = nodes.into_iter().map(Some).collect();
        let mut result = Vec::with_capacity(slots.len());
        for old in ordered {
            let mut node = slots[old]
                .take()
                .expect("module graph ordering repeated a node");
            node.imports = node.imports.into_iter().map(|i| remap[&i]).collect();
            result.push(node);
        }
        let _ = remap[&root_index];
        Ok(Self { nodes: result })
    }

    fn definitions(&self) -> Vec<ProviderRegistration> {
        let mut values = vec![];
        for (module, node) in self.nodes.iter().enumerate() {
            values.extend(
                (0..node.metadata.providers.len()).map(|slot| ProviderRegistration {
                    module,
                    slot: ProviderSlot::Provider(slot),
                }),
            );
            values.extend(
                (0..node.metadata.controllers.len()).map(|slot| ProviderRegistration {
                    module,
                    slot: ProviderSlot::Controller(slot),
                }),
            );
            for slot in 0..node.metadata.gateways.len() {
                values.push(ProviderRegistration {
                    module,
                    slot: ProviderSlot::Gateway(slot),
                });
            }
            values.extend((0..node.metadata.microservices.len()).map(|slot| {
                ProviderRegistration {
                    module,
                    slot: ProviderSlot::Microservice(slot),
                }
            }));
        }
        values
    }
    fn def(&self, registration: ProviderRegistration) -> &ProviderDef {
        match registration.slot {
            ProviderSlot::Provider(index) => {
                &self.nodes[registration.module].metadata.providers[index]
            }
            ProviderSlot::Controller(index) => {
                &self.nodes[registration.module].metadata.controllers[index].provider
            }
            ProviderSlot::Gateway(index) => {
                &self.nodes[registration.module].metadata.gateways[index].provider
            }
            ProviderSlot::Microservice(index) => {
                &self.nodes[registration.module].metadata.microservices[index].provider
            }
        }
    }
    fn local_types(&self, module: usize) -> HashSet<TypeId> {
        self.definitions()
            .into_iter()
            .filter(|r| r.module == module)
            .map(|r| self.def(r).type_id)
            .collect()
    }
    /// Validates the module graph and returns providers in construction order.
    ///
    /// Passing `None` performs metadata-only validation. A container is only
    /// needed during application startup, when provider overrides and values
    /// registered by application setup may satisfy declarations.
    fn preflight(&self, container: Option<&Container>) -> crate::Result<Vec<ProviderRegistration>> {
        let definitions = self.definitions();
        let mut by_type = HashMap::new();
        for registration in &definitions {
            let def = self.def(*registration);
            if let Some(existing) = by_type.insert(def.type_id, *registration) {
                if !container.is_some_and(|container| {
                    container.has_pending_override(def.type_id)
                        || container.was_overridden(def.type_id)
                }) {
                    return Err(crate::exception::startup_error(format!(
                        "duplicate provider registration for {} in {} and {}",
                        def.type_name,
                        self.nodes[existing.module].type_name,
                        self.nodes[registration.module].type_name
                    )));
                }
            }
        }
        let locals: Vec<HashSet<TypeId>> =
            (0..self.nodes.len()).map(|i| self.local_types(i)).collect();
        let mut exports = vec![HashSet::new(); self.nodes.len()];
        for index in 0..self.nodes.len() {
            let node = &self.nodes[index];
            for export in &node.metadata.exports {
                let imported = node
                    .imports
                    .iter()
                    .any(|&child| exports[child].contains(&export.type_id));
                if !locals[index].contains(&export.type_id) && !imported {
                    return Err(crate::exception::startup_error(format!(
                        "module {} cannot export {}: it is neither declared locally nor exported by a direct import",
                        node.type_name, export.type_name
                    )));
                }
                exports[index].insert(export.type_id);
            }
        }
        let global_exports: HashSet<TypeId> = self
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, node)| node.metadata.global)
            .flat_map(|(index, _)| exports[index].iter().copied())
            .collect();
        let visible = |module: usize, type_id: TypeId| {
            locals[module].contains(&type_id)
                || global_exports.contains(&type_id)
                || self.nodes[module]
                    .imports
                    .iter()
                    .any(|&child| exports[child].contains(&type_id))
        };
        for registration in &definitions {
            let production = self.def(*registration);
            let effective = container
                .and_then(|container| container.pending_override(production.type_id))
                .unwrap_or(production);
            for dependency in &effective.dependencies {
                if dependency.type_id == TypeId::of::<crate::Logger>() {
                    continue;
                }
                if by_type.contains_key(&dependency.type_id) {
                    if !visible(registration.module, dependency.type_id) {
                        return Err(crate::exception::startup_error(format!(
                            "{} depends on {} but it is not visible in module {}; import and export its module",
                            effective.type_name,
                            dependency.type_name,
                            self.nodes[registration.module].type_name
                        )));
                    }
                } else if !container
                    .is_some_and(|container| container.contains_type_id(dependency.type_id))
                {
                    return Err(crate::exception::startup_error(format!(
                        "missing provider at startup: {} depends on {} but no provider is registered",
                        effective.type_name, dependency.type_name
                    )));
                }
            }
        }
        for (module, node) in self.nodes.iter().enumerate() {
            for handler in &node.metadata.event_handlers {
                handler.assert_registered_or_declared(&locals[module])?;
                if !visible(module, TypeId::of::<crate::EventBus>()) {
                    return Err(crate::exception::startup_error(format!(
                        "no provider registered for EventBus in module {}; import EventModule",
                        node.type_name
                    )));
                }
            }
        }
        let mut command_patterns: HashMap<&'static str, usize> = HashMap::new();
        let mut event_patterns: HashMap<&'static str, usize> = HashMap::new();
        for (module, node) in self.nodes.iter().enumerate() {
            for microservice in &node.metadata.microservices {
                for handler in microservice.handlers() {
                    if !valid_microservice_pattern(
                        handler.pattern,
                        handler.kind == MessageHandlerKind::Command,
                    ) {
                        return Err(crate::exception::startup_error(format!(
                            "invalid microservice subject `{}` in module {}",
                            handler.pattern, node.type_name
                        )));
                    }
                    let (other, existing) = if handler.kind == MessageHandlerKind::Command {
                        (&event_patterns, command_patterns.get(handler.pattern))
                    } else {
                        (&command_patterns, event_patterns.get(handler.pattern))
                    };
                    if let Some(other_module) = other.get(handler.pattern) {
                        return Err(crate::exception::startup_error(format!(
                            "command and event handlers cannot share subject `{}` in {} and {}",
                            handler.pattern, self.nodes[*other_module].type_name, node.type_name
                        )));
                    }
                    if let Some(existing) = existing {
                        return Err(crate::exception::startup_error(format!(
                            "duplicate {:?} handler subject `{}` in {} and {}",
                            handler.kind,
                            handler.pattern,
                            self.nodes[*existing].type_name,
                            node.type_name
                        )));
                    }
                    if handler.kind == MessageHandlerKind::Command {
                        command_patterns.insert(handler.pattern, module);
                    } else {
                        event_patterns.insert(handler.pattern, module);
                    }
                }
            }
        }
        for command in command_patterns.keys() {
            for event in event_patterns.keys() {
                if microservice_patterns_intersect(command, event) {
                    return Err(crate::exception::startup_error(format!(
                        "command subject `{command}` overlaps event subject `{event}`; command and event transports must be disjoint"
                    )));
                }
            }
        }
        let event_subjects: Vec<_> = event_patterns.keys().copied().collect();
        for (index, first) in event_subjects.iter().enumerate() {
            for second in event_subjects.iter().skip(index + 1) {
                if microservice_patterns_intersect(first, second) {
                    return Err(crate::exception::startup_error(format!(
                        "event subjects `{first}` and `{second}` overlap; each event delivery must have one owner"
                    )));
                }
            }
        }
        let mut sorted = vec![];
        let mut states = HashMap::new();
        let mut stack = vec![];
        fn schedule(
            reg: ProviderRegistration,
            graph: &ModuleGraph,
            by_type: &HashMap<TypeId, ProviderRegistration>,
            container: Option<&Container>,
            states: &mut HashMap<TypeId, u8>,
            stack: &mut Vec<&'static str>,
            sorted: &mut Vec<ProviderRegistration>,
        ) -> crate::Result<()> {
            let def = graph.def(reg);
            match states.get(&def.type_id).copied() {
                Some(2) => return Ok(()),
                Some(1) => {
                    let mut cycle = stack.clone();
                    cycle.push(def.type_name);
                    return Err(crate::exception::startup_error(format!(
                        "provider dependency cycle: {}",
                        cycle.join(" -> ")
                    )));
                }
                _ => {}
            }
            states.insert(def.type_id, 1);
            stack.push(def.type_name);
            let effective = container
                .and_then(|container| container.pending_override(def.type_id))
                .unwrap_or(def);
            for dep in &effective.dependencies {
                if let Some(next) = by_type.get(&dep.type_id) {
                    schedule(*next, graph, by_type, container, states, stack, sorted)?;
                }
            }
            stack.pop();
            states.insert(def.type_id, 2);
            sorted.push(reg);
            Ok(())
        }
        for registration in definitions {
            schedule(
                registration,
                self,
                &by_type,
                container,
                &mut states,
                &mut stack,
                &mut sorted,
            )?;
        }
        Ok(sorted)
    }
    fn def_by_type(&self, type_id: TypeId) -> Option<&ProviderDef> {
        self.definitions().into_iter().find_map(|r| {
            let def = self.def(r);
            (def.type_id == type_id).then_some(def)
        })
    }
}

async fn initialize_graph(graph: &ModuleGraph, container: &mut Container) -> crate::Result<()> {
    let order = graph.preflight(Some(container))?;
    for registration in order {
        let declared = graph.def(registration);
        container.mark_provider_declared(declared.type_id);
        if container.contains_type_id(declared.type_id)
            || container.was_overridden(declared.type_id)
        {
            continue;
        }
        let start = Instant::now();
        let override_def = container.take_pending_override(declared.type_id);
        if override_def.is_some() {
            container.mark_override_applied(declared.type_id);
        }
        let effective = override_def.as_ref().unwrap_or(declared);
        let scoped_container =
            container.scoped_for_provider(effective.type_name, &effective.dependencies);
        let value = match (effective.build)(&scoped_container).await {
            Ok(value) => value,
            Err(error) => {
                rollback_graph(graph, container).await;
                return Err(error);
            }
        };
        container.register_erased(effective.type_id, value.clone());
        if let Err(error) = effective
            .run_lifecycle(&value, "on_module_init", &effective.init_fn)
            .await
        {
            rollback_graph(graph, container).await;
            return Err(error);
        }
        if override_def.is_none() {
            container.record_initialized_provider(declared.type_id);
        }
        crate::log_provider_initialized(effective.type_name, start.elapsed());
    }
    for node in &graph.nodes {
        for handler in &node.metadata.event_handlers {
            if let Err(error) = handler.register(container) {
                rollback_graph(graph, container).await;
                return Err(error);
            }
        }
        crate::log_module_initialized(node.type_name);
    }
    Ok(())
}

async fn bootstrap_graph(graph: &ModuleGraph, container: &Container) -> crate::Result<()> {
    let order = graph.preflight(Some(container))?;
    let initialized: HashSet<TypeId> = container.initialized_provider_types().into_iter().collect();
    for registration in order {
        let def = graph.def(registration);
        if initialized.contains(&def.type_id)
            && !container.was_overridden(def.type_id)
            && container.begin_provider_bootstrap(def.type_id)
        {
            if let Err(error) = def
                .run_lifecycle_from_container(container, "on_bootstrap", &def.bootstrap_fn)
                .await
            {
                rollback_graph(graph, container).await;
                return Err(error);
            }
        }
    }
    Ok(())
}

async fn rollback_graph(graph: &ModuleGraph, container: &Container) {
    for type_id in container.take_initialized_providers().into_iter().rev() {
        if let Some(def) = graph.def_by_type(type_id) {
            let _ = def
                .run_lifecycle_from_container(container, "on_shutdown", &def.shutdown_fn)
                .await;
        }
    }
}

/// Runs the `register_module` public API operation.
pub async fn register_module<M: Module + 'static>(container: &mut Container) -> Result<()> {
    let graph = ModuleGraph::discover::<M>()?;
    initialize_graph(&graph, container).await
}
/// Runs the `bootstrap_module` public API operation.
pub async fn bootstrap_module<M: Module + 'static>(container: &Container) -> Result<()> {
    let graph = ModuleGraph::discover::<M>()?;
    bootstrap_graph(&graph, container).await
}
/// Runs the `shutdown_module` public API operation.
pub async fn shutdown_module<M: Module + 'static>(container: &Container) -> Result<()> {
    let graph = ModuleGraph::discover::<M>()?;
    let mut first = None;
    for type_id in container.take_initialized_providers().into_iter().rev() {
        if let Some(def) = graph.def_by_type(type_id) {
            if let Err(error) = def
                .run_lifecycle_from_container(container, "on_shutdown", &def.shutdown_fn)
                .await
            {
                if first.is_none() {
                    first = Some(error);
                }
            }
        }
    }
    first.map_or(Ok(()), Err)
}

/// Runs the `build_container` public API operation.
pub async fn build_container<M: Module + 'static>() -> Result<Container> {
    build_container_with_overrides::<M>(ProviderOverrides::new()).await
}
#[doc(hidden)]
pub async fn build_container_with_setup<M: Module + 'static>(
    setup: impl FnOnce(&mut Container),
) -> Result<Container> {
    let mut container = Container::new();
    setup(&mut container);
    if let Err(error) = register_module::<M>(&mut container).await {
        return Err(error);
    }
    if let Err(error) =
        validate_module_providers::<M>(&container).and_then(|_| validate_gateway_paths::<M>())
    {
        let graph = ModuleGraph::discover::<M>()?;
        rollback_graph(&graph, &container).await;
        return Err(error);
    }
    if let Err(error) = bootstrap_module::<M>(&container).await {
        return Err(error);
    }
    Ok(container)
}
/// Runs the `build_container_with_overrides` public API operation.
pub async fn build_container_with_overrides<M: Module + 'static>(
    overrides: ProviderOverrides,
) -> crate::Result<Container> {
    let mut container = Container::new();
    container.seed_overrides(overrides);
    if let Err(error) = register_module::<M>(&mut container).await {
        return Err(error);
    }
    if let Err(error) = container
        .assert_no_unused_overrides()
        .and_then(|_| validate_module_providers::<M>(&container))
        .and_then(|_| validate_gateway_paths::<M>())
    {
        let graph = ModuleGraph::discover::<M>()?;
        rollback_graph(&graph, &container).await;
        return Err(error);
    }
    if let Err(error) = bootstrap_module::<M>(&container).await {
        return Err(error);
    }
    Ok(container)
}

/// Collects the transport-neutral handlers declared by a module graph.
///
/// Transport adapters call this after constructing the shared container. The
/// same graph validation used during startup rejects duplicate ownership before
/// any subscriptions are started.
pub fn collect_module_message_handlers<M: Module + 'static>() -> Result<Vec<MessageHandlerDef>> {
    collect_module_message_handlers_with_container::<M>(None)
}

/// Collects message handlers while validating dependencies against an existing
/// application container. Transport adapters use this when they register
/// transport-owned values before module construction.
pub fn collect_module_message_handlers_with_container<M: Module + 'static>(
    container: Option<&Container>,
) -> Result<Vec<MessageHandlerDef>> {
    let graph = ModuleGraph::discover::<M>()?;
    graph.preflight(container)?;
    let mut handlers = Vec::new();
    for node in &graph.nodes {
        for microservice in &node.metadata.microservices {
            handlers.extend(microservice.handlers());
        }
    }
    Ok(handlers)
}

fn validate_gateway_paths_in_graph(graph: &ModuleGraph) -> crate::Result<()> {
    let mut paths = HashSet::new();
    for node in &graph.nodes {
        for gateway in &node.metadata.gateways {
            if !gateway.path.starts_with('/') {
                return Err(crate::exception::startup_error(format!(
                    "websocket gateway path must start with '/': {}",
                    gateway.path
                )));
            }
            if !paths.insert((gateway.path, gateway.is_websocket())) {
                return Err(crate::exception::startup_error(format!(
                    "duplicate gateway path: {}",
                    gateway.path
                )));
            }
        }
    }
    Ok(())
}

fn valid_microservice_pattern(pattern: &str, command: bool) -> bool {
    if pattern.is_empty() || pattern.chars().any(char::is_whitespace) {
        return false;
    }
    let tokens: Vec<_> = pattern.split('.').collect();
    tokens.iter().enumerate().all(|(index, token)| {
        !token.is_empty()
            && (!token.contains('*') || (!command && *token == "*"))
            && (!token.contains('>') || (!command && *token == ">" && index + 1 == tokens.len()))
    })
}

fn microservice_patterns_intersect(first: &str, second: &str) -> bool {
    let first: Vec<_> = first.split('.').collect();
    let second: Vec<_> = second.split('.').collect();
    let mut index = 0;
    loop {
        let left = first.get(index).copied();
        let right = second.get(index).copied();
        match (left, right) {
            (None, None) => return true,
            (Some(">"), Some(_)) | (Some(_), Some(">")) => return true,
            (Some(left), Some(right)) if left == "*" || right == "*" || left == right => {
                index += 1;
            }
            _ => return false,
        }
    }
}

#[cfg(test)]
mod microservice_pattern_tests {
    use super::microservice_patterns_intersect;

    #[test]
    fn terminal_wildcards_do_not_overlap_their_empty_prefix() {
        assert!(!microservice_patterns_intersect("orders", "orders.>"));
        assert!(microservice_patterns_intersect(
            "orders.created",
            "orders.>"
        ));
    }
}

fn validate_gateway_paths<M: Module + 'static>() -> crate::Result<()> {
    validate_gateway_paths_in_graph(&ModuleGraph::discover::<M>()?)
}

/// Validates a module's metadata without constructing providers or starting an application.
///
/// This checks module imports, provider declarations and dependencies, exports,
/// event-handler declarations, and WebSocket gateway paths. It intentionally
/// does not invoke provider constructors or factories, lifecycle hooks, external
/// services, or network listeners.
pub fn validate_module<M: Module + 'static>() -> Result<()> {
    let graph = ModuleGraph::discover::<M>()?;
    graph.preflight(None)?;
    validate_gateway_paths_in_graph(&graph)
}

/// Runs the `validate_module_providers` public API operation.
pub fn validate_module_providers<M: Module + 'static>(container: &Container) -> Result<()> {
    let graph = ModuleGraph::discover::<M>()?;
    graph.preflight(Some(container))?;
    for registration in graph.definitions() {
        graph.def(registration).assert_registered(container)?;
    }
    Ok(())
}

/// Runs the `register_module_controllers` public API operation.
pub fn register_module_controllers<M: Module + 'static>(any: &mut dyn Any) {
    if let Ok(graph) = ModuleGraph::discover::<M>() {
        for node in graph.nodes {
            for controller in &node.metadata.controllers {
                (controller.register_fn)(any);
            }
        }
    }
}
#[cfg(feature = "openapi")]
#[doc(hidden)]
pub fn visit_module_openapi_routes<M: Module + 'static>(
    visitor: &mut impl FnMut(&crate::openapi::OpenApiRouteDef),
) {
    if let Ok(graph) = ModuleGraph::discover::<M>() {
        for node in graph.nodes {
            for controller in &node.metadata.controllers {
                for route in (controller.openapi_routes_fn)() {
                    visitor(route);
                }
            }
        }
    }
}
/// Runs the `visit_module_gateways` public API operation.
pub fn visit_module_gateways<M: Module + 'static>(visitor: &mut impl FnMut(&GatewayDef)) {
    if let Ok(graph) = ModuleGraph::discover::<M>() {
        let mut seen = HashSet::new();
        for node in graph.nodes {
            for gateway in &node.metadata.gateways {
                if seen.insert(gateway.type_id) {
                    visitor(gateway);
                }
            }
        }
    }
}