Skip to main content

toolkit/
registry.rs

1// toolkit/src/registry/mod.rs
2use std::collections::{HashMap, VecDeque};
3use std::sync::Arc;
4
5use thiserror::Error;
6
7// Re-exported contracts are referenced but not defined here.
8use crate::contracts;
9
10/// Type alias for REST host gear configuration.
11type RestHostEntry = (&'static str, Arc<dyn contracts::ApiGatewayCapability>);
12
13// ============================================================================
14// Capability System
15// ============================================================================
16
17/// A single capability variant that a gear can provide.
18#[derive(Clone)]
19pub enum Capability {
20    #[cfg(feature = "db")]
21    Database(Arc<dyn contracts::DatabaseCapability>),
22    RestApi(Arc<dyn contracts::RestApiCapability>),
23    ApiGateway(Arc<dyn contracts::ApiGatewayCapability>),
24    Runnable(Arc<dyn contracts::RunnableCapability>),
25    System(Arc<dyn contracts::SystemCapability>),
26    GrpcHub(Arc<dyn contracts::GrpcHubCapability>),
27    GrpcService(Arc<dyn contracts::GrpcServiceCapability>),
28    GtsPublication(Arc<dyn crate::gts_publication::GtsPublicationCapability>),
29}
30
31impl std::fmt::Debug for Capability {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            #[cfg(feature = "db")]
35            Capability::Database(_) => write!(f, "Database(<impl DatabaseCapability>)"),
36            Capability::RestApi(_) => write!(f, "RestApi(<impl RestApiCapability>)"),
37            Capability::ApiGateway(_) => write!(f, "ApiGateway(<impl ApiGatewayCapability>)"),
38            Capability::Runnable(_) => write!(f, "Runnable(<impl RunnableCapability>)"),
39            Capability::System(_) => write!(f, "System(<impl SystemCapability>)"),
40            Capability::GrpcHub(_) => write!(f, "GrpcHub(<impl GrpcHubCapability>)"),
41            Capability::GrpcService(_) => write!(f, "GrpcService(<impl GrpcServiceCapability>)"),
42            Capability::GtsPublication(_) => {
43                write!(f, "GtsPublication(<impl GtsPublicationCapability>)")
44            }
45        }
46    }
47}
48
49/// Trait for capability tags that allow type-safe querying.
50pub trait CapTag {
51    type Out: ?Sized + 'static;
52    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>>;
53}
54
55/// Tag for querying `DatabaseCapability`.
56#[cfg(feature = "db")]
57pub struct DatabaseCap;
58#[cfg(feature = "db")]
59impl CapTag for DatabaseCap {
60    type Out = dyn contracts::DatabaseCapability;
61    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
62        match cap {
63            Capability::Database(v) => Some(v),
64            _ => None,
65        }
66    }
67}
68
69/// Tag for querying `RestApiCapability`.
70pub struct RestApiCap;
71impl CapTag for RestApiCap {
72    type Out = dyn contracts::RestApiCapability;
73    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
74        match cap {
75            Capability::RestApi(v) => Some(v),
76            _ => None,
77        }
78    }
79}
80
81/// Tag for querying `ApiGatewayCapability`.
82pub struct ApiGatewayCap;
83impl CapTag for ApiGatewayCap {
84    type Out = dyn contracts::ApiGatewayCapability;
85    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
86        match cap {
87            Capability::ApiGateway(v) => Some(v),
88            _ => None,
89        }
90    }
91}
92
93/// Tag for querying `RunnableCapability`.
94pub struct RunnableCap;
95impl CapTag for RunnableCap {
96    type Out = dyn contracts::RunnableCapability;
97    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
98        match cap {
99            Capability::Runnable(v) => Some(v),
100            _ => None,
101        }
102    }
103}
104
105/// Tag for querying `SystemCapability`.
106pub struct SystemCap;
107impl CapTag for SystemCap {
108    type Out = dyn contracts::SystemCapability;
109    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
110        match cap {
111            Capability::System(v) => Some(v),
112            _ => None,
113        }
114    }
115}
116
117/// Tag for querying `GrpcHubCapability`.
118pub struct GrpcHubCap;
119impl CapTag for GrpcHubCap {
120    type Out = dyn contracts::GrpcHubCapability;
121    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
122        match cap {
123            Capability::GrpcHub(v) => Some(v),
124            _ => None,
125        }
126    }
127}
128
129/// Tag for querying `GrpcServiceCapability`.
130pub struct GrpcServiceCap;
131impl CapTag for GrpcServiceCap {
132    type Out = dyn contracts::GrpcServiceCapability;
133    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
134        match cap {
135            Capability::GrpcService(v) => Some(v),
136            _ => None,
137        }
138    }
139}
140
141/// Tag for querying `GtsPublicationCapability`.
142pub struct GtsPublicationCap;
143impl CapTag for GtsPublicationCap {
144    type Out = dyn crate::gts_publication::GtsPublicationCapability;
145    fn try_get(cap: &Capability) -> Option<&Arc<Self::Out>> {
146        match cap {
147            Capability::GtsPublication(v) => Some(v),
148            _ => None,
149        }
150    }
151}
152
153/// A set of capabilities that a gear provides.
154#[derive(Clone)]
155pub struct CapabilitySet {
156    caps: Vec<Capability>,
157}
158
159impl std::fmt::Debug for CapabilitySet {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        f.debug_struct("CapabilitySet")
162            .field("caps", &self.caps)
163            .finish()
164    }
165}
166
167impl CapabilitySet {
168    /// Create an empty capability set.
169    #[must_use]
170    pub fn new() -> Self {
171        Self { caps: Vec::new() }
172    }
173
174    /// Add a capability to the set.
175    pub fn push(&mut self, cap: Capability) {
176        self.caps.push(cap);
177    }
178
179    /// Check if the set contains a specific capability type.
180    #[must_use]
181    pub fn has<T: CapTag>(&self) -> bool {
182        self.caps.iter().any(|cap| T::try_get(cap).is_some())
183    }
184
185    /// Query for a specific capability type.
186    #[must_use]
187    pub fn query<T: CapTag>(&self) -> Option<Arc<T::Out>> {
188        self.caps.iter().find_map(|cap| T::try_get(cap).cloned())
189    }
190
191    /// Returns human-readable capability labels (e.g. `"rest"`, `"db"`, `"system"`).
192    #[must_use]
193    pub fn labels(&self) -> Vec<&'static str> {
194        self.caps
195            .iter()
196            .map(|cap| match cap {
197                #[cfg(feature = "db")]
198                Capability::Database(_) => "db",
199                Capability::RestApi(_) => "rest",
200                Capability::ApiGateway(_) => "rest_host",
201                Capability::Runnable(_) => "stateful",
202                Capability::System(_) => "system",
203                Capability::GrpcHub(_) => "grpc_hub",
204                Capability::GrpcService(_) => "grpc",
205                Capability::GtsPublication(_) => "gts_publication",
206            })
207            .collect()
208    }
209
210    /// Convenience helper for DB presence.
211    #[must_use]
212    pub fn has_db(&self) -> bool {
213        #[cfg(feature = "db")]
214        {
215            self.has::<DatabaseCap>()
216        }
217        #[cfg(not(feature = "db"))]
218        {
219            false
220        }
221    }
222}
223
224impl Default for CapabilitySet {
225    fn default() -> Self {
226        Self::new()
227    }
228}
229
230pub struct GearEntry {
231    /// Gear name.
232    pub(crate) name: &'static str,
233    /// Names of gears this gear depends on.
234    pub(crate) deps: &'static [&'static str],
235    /// Core gear implementation.
236    pub(crate) core: Arc<dyn contracts::Gear>,
237    /// Capabilities declared by this gear.
238    pub(crate) caps: CapabilitySet,
239}
240
241impl GearEntry {
242    /// Returns the gear name.
243    #[must_use]
244    pub fn name(&self) -> &'static str {
245        self.name
246    }
247
248    /// Returns the gear dependency names.
249    #[must_use]
250    pub fn deps(&self) -> &'static [&'static str] {
251        self.deps
252    }
253
254    /// Returns the capability set.
255    #[must_use]
256    pub fn caps(&self) -> &CapabilitySet {
257        &self.caps
258    }
259
260    /// Whether this gear has the `system` capability, and so belongs to the
261    /// system group that starts before the application group is prepared.
262    #[must_use]
263    pub fn is_system(&self) -> bool {
264        self.caps.has::<SystemCap>()
265    }
266
267    /// Validate publication capabilities/configuration for startup and deployment jobs.
268    pub(crate) fn validate_gts_publication_config(
269        &self,
270        config: &dyn crate::config::ConfigProvider,
271    ) -> anyhow::Result<()> {
272        if self.caps.has::<GtsPublicationCap>() {
273            anyhow::ensure!(
274                !self.is_system(),
275                "a system gear initializes before the GTS barrier, so it cannot \
276                 publish GTS documents with `gts_publication(...)`"
277            );
278        } else {
279            anyhow::ensure!(
280                config
281                    .get_gear_config(self.name)
282                    .and_then(|gear| gear.get("config"))
283                    .and_then(|config| config.get(crate::config::GTS_PUBLICATION_CONFIG_KEY))
284                    .is_none(),
285                "gears.{}.config.{} is set, but this gear publishes no GTS \
286                 documents: it declares no `gts_publication(...)`",
287                self.name,
288                crate::config::GTS_PUBLICATION_CONFIG_KEY
289            );
290        }
291        Ok(())
292    }
293}
294
295impl std::fmt::Debug for GearEntry {
296    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297        f.debug_struct("GearEntry")
298            .field("name", &self.name)
299            .field("deps", &self.deps)
300            .field("has_rest", &self.caps.has::<RestApiCap>())
301            .field("is_rest_host", &self.caps.has::<ApiGatewayCap>())
302            .field("has_db", &self.caps.has_db())
303            .field("has_stateful", &self.caps.has::<RunnableCap>())
304            .field("is_system", &self.caps.has::<SystemCap>())
305            .field("is_grpc_hub", &self.caps.has::<GrpcHubCap>())
306            .field("has_grpc_service", &self.caps.has::<GrpcServiceCap>())
307            .finish_non_exhaustive()
308    }
309}
310
311/// The function type submitted by the macro via `inventory::submit!`.
312/// NOTE: It now takes a *builder*, not the final registry.
313pub struct Registrator(pub fn(&mut RegistryBuilder));
314
315inventory::collect!(Registrator);
316
317/// The final, topo-sorted runtime registry.
318pub struct GearRegistry {
319    gears: Vec<GearEntry>, // topo-sorted
320    pub grpc_hub: Option<String>,
321    pub grpc_services: Vec<(String, Arc<dyn contracts::GrpcServiceCapability>)>,
322}
323
324impl std::fmt::Debug for GearRegistry {
325    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326        let names: Vec<&'static str> = self.gears.iter().map(|m| m.name).collect();
327        f.debug_struct("GearRegistry")
328            .field("gears", &names)
329            .field("has_grpc_hub", &self.grpc_hub.is_some())
330            .field("grpc_services_count", &self.grpc_services.len())
331            .finish()
332    }
333}
334
335impl GearRegistry {
336    #[must_use]
337    pub fn gears(&self) -> &[GearEntry] {
338        &self.gears
339    }
340
341    /// Discover via inventory, have registrators fill the builder, then build & topo-sort.
342    ///
343    /// # Errors
344    /// Returns `RegistryError` if gear discovery or dependency resolution fails.
345    pub fn discover_and_build() -> Result<Self, RegistryError> {
346        let mut b = RegistryBuilder::default();
347        for r in ::inventory::iter::<Registrator> {
348            r.0(&mut b);
349        }
350        b.build_topo_sorted()
351    }
352
353    /// (Optional) quick lookup if you need it.
354    #[must_use]
355    pub fn get_gear(&self, name: &str) -> Option<Arc<dyn contracts::Gear>> {
356        self.gears
357            .iter()
358            .find(|e| e.name == name)
359            .map(|e| e.core.clone())
360    }
361}
362
363/// Type alias for gRPC hub gear configuration.
364type GrpcHubEntry = (&'static str, Arc<dyn contracts::GrpcHubCapability>);
365
366/// Internal builder that macro registrators will feed.
367/// Keys are gear **names**; uniqueness enforced at build time.
368#[derive(Default)]
369pub struct RegistryBuilder {
370    core: HashMap<&'static str, Arc<dyn contracts::Gear>>,
371    deps: HashMap<&'static str, &'static [&'static str]>,
372    capabilities: HashMap<&'static str, Vec<Capability>>,
373    rest_host: Option<RestHostEntry>,
374    grpc_hub: Option<GrpcHubEntry>,
375    errors: Vec<String>,
376}
377
378/// Type alias for dependency graph: (names, adjacency list, index map)
379type DependencyGraph = (
380    Vec<&'static str>,
381    Vec<Vec<usize>>,
382    HashMap<&'static str, usize>,
383);
384
385impl RegistryBuilder {
386    pub fn register_core_with_meta(
387        &mut self,
388        name: &'static str,
389        deps: &'static [&'static str],
390        m: Arc<dyn contracts::Gear>,
391    ) {
392        if self.core.contains_key(name) {
393            self.errors
394                .push(format!("Gear '{name}' is already registered"));
395            return;
396        }
397        self.core.insert(name, m);
398        self.deps.insert(name, deps);
399    }
400
401    pub fn register_rest_with_meta(
402        &mut self,
403        name: &'static str,
404        m: Arc<dyn contracts::RestApiCapability>,
405    ) {
406        self.capabilities
407            .entry(name)
408            .or_default()
409            .push(Capability::RestApi(m));
410    }
411
412    pub fn register_rest_host_with_meta(
413        &mut self,
414        name: &'static str,
415        m: Arc<dyn contracts::ApiGatewayCapability>,
416    ) {
417        if let Some((existing, _)) = &self.rest_host {
418            self.errors.push(format!(
419                "Multiple REST host gears detected: '{existing}' and '{name}'. Only one REST host is allowed."
420            ));
421            return;
422        }
423        self.rest_host = Some((name, m));
424    }
425
426    #[cfg(feature = "db")]
427    pub fn register_db_with_meta(
428        &mut self,
429        name: &'static str,
430        m: Arc<dyn contracts::DatabaseCapability>,
431    ) {
432        self.capabilities
433            .entry(name)
434            .or_default()
435            .push(Capability::Database(m));
436    }
437
438    pub fn register_stateful_with_meta(
439        &mut self,
440        name: &'static str,
441        m: Arc<dyn contracts::RunnableCapability>,
442    ) {
443        self.capabilities
444            .entry(name)
445            .or_default()
446            .push(Capability::Runnable(m));
447    }
448
449    pub fn register_system_with_meta(
450        &mut self,
451        name: &'static str,
452        m: Arc<dyn contracts::SystemCapability>,
453    ) {
454        self.capabilities
455            .entry(name)
456            .or_default()
457            .push(Capability::System(m));
458    }
459
460    pub fn register_gts_publication_with_meta(
461        &mut self,
462        name: &'static str,
463        m: Arc<dyn crate::gts_publication::GtsPublicationCapability>,
464    ) {
465        self.capabilities
466            .entry(name)
467            .or_default()
468            .push(Capability::GtsPublication(m));
469    }
470
471    pub fn register_grpc_hub_with_meta(
472        &mut self,
473        name: &'static str,
474        m: Arc<dyn contracts::GrpcHubCapability>,
475    ) {
476        if let Some((existing, _)) = &self.grpc_hub {
477            self.errors.push(format!(
478                "Multiple gRPC hub gears detected: '{existing}' and '{name}'. Only one gRPC hub is allowed."
479            ));
480            return;
481        }
482        self.grpc_hub = Some((name, m));
483    }
484
485    pub fn register_grpc_service_with_meta(
486        &mut self,
487        name: &'static str,
488        m: Arc<dyn contracts::GrpcServiceCapability>,
489    ) {
490        self.capabilities
491            .entry(name)
492            .or_default()
493            .push(Capability::GrpcService(m));
494    }
495
496    /// Detect cycles in the dependency graph using DFS with path tracking.
497    /// Returns the cycle path if found, None otherwise.
498    fn detect_cycle_with_path(
499        names: &[&'static str],
500        adj: &[Vec<usize>],
501    ) -> Option<Vec<&'static str>> {
502        #[derive(Clone, Copy, PartialEq)]
503        enum Color {
504            White, // unvisited
505            Gray,  // visiting (on current path)
506            Black, // visited (finished)
507        }
508
509        fn dfs(
510            node: usize,
511            names: &[&'static str],
512            adj: &[Vec<usize>],
513            colors: &mut [Color],
514            path: &mut Vec<usize>,
515        ) -> Option<Vec<&'static str>> {
516            colors[node] = Color::Gray;
517            path.push(node);
518
519            for &neighbor in &adj[node] {
520                match colors[neighbor] {
521                    Color::Gray => {
522                        // Found a back edge - cycle detected
523                        // Find the cycle start in the current path
524                        if let Some(cycle_start) = path.iter().position(|&n| n == neighbor) {
525                            let cycle_indices = &path[cycle_start..];
526                            let mut cycle_path: Vec<&'static str> =
527                                cycle_indices.iter().map(|&i| names[i]).collect();
528                            // Close the cycle by adding the first node again
529                            cycle_path.push(names[neighbor]);
530                            return Some(cycle_path);
531                        }
532                    }
533                    Color::White => {
534                        if let Some(cycle) = dfs(neighbor, names, adj, colors, path) {
535                            return Some(cycle);
536                        }
537                    }
538                    Color::Black => {
539                        // Already processed, no cycle through this path
540                    }
541                }
542            }
543
544            path.pop();
545            colors[node] = Color::Black;
546            None
547        }
548
549        let mut colors = vec![Color::White; names.len()];
550        let mut path = Vec::new();
551
552        for i in 0..names.len() {
553            if colors[i] == Color::White
554                && let Some(cycle) = dfs(i, names, adj, &mut colors, &mut path)
555            {
556                return Some(cycle);
557            }
558        }
559
560        None
561    }
562
563    /// Validate that all capabilities reference known core gears.
564    fn validate_capabilities(&self) -> Result<(), RegistryError> {
565        // Check rest_host early
566        if let Some((host_name, _)) = &self.rest_host
567            && !self.core.contains_key(host_name)
568        {
569            return Err(RegistryError::UnknownGear((*host_name).to_owned()));
570        }
571
572        // Check for configuration errors
573        if !self.errors.is_empty() {
574            return Err(RegistryError::InvalidRegistryConfiguration {
575                errors: self.errors.clone(),
576            });
577        }
578
579        // Validate all capability gear names reference known core gears
580        for name in self.capabilities.keys() {
581            if !self.core.contains_key(name) {
582                return Err(RegistryError::UnknownGear((*name).to_owned()));
583            }
584        }
585
586        // Validate grpc_hub
587        if let Some((name, _)) = &self.grpc_hub
588            && !self.core.contains_key(name)
589        {
590            return Err(RegistryError::UnknownGear((*name).to_owned()));
591        }
592
593        Ok(())
594    }
595
596    /// A system gear runs before the application group is prepared, so it
597    /// cannot depend on an application gear.
598    fn validate_system_deps(&self) -> Result<(), RegistryError> {
599        let is_system = |name: &str| {
600            self.capabilities
601                .get(name)
602                .is_some_and(|caps| caps.iter().any(|cap| matches!(cap, Capability::System(_))))
603        };
604        let mut names: Vec<_> = self.deps.keys().copied().collect();
605        names.sort_unstable();
606        for gear in names {
607            if !is_system(gear) {
608                continue;
609            }
610            for dep in self.deps[gear] {
611                if self.core.contains_key(dep) && !is_system(dep) {
612                    return Err(RegistryError::SystemDependsOnApplication {
613                        gear: gear.to_owned(),
614                        depends_on: (*dep).to_owned(),
615                    });
616                }
617            }
618        }
619        Ok(())
620    }
621
622    /// Build dependency graph and return gear names, adjacency list, and index mapping.
623    fn build_dependency_graph(&self) -> Result<DependencyGraph, RegistryError> {
624        let names: Vec<&'static str> = self.core.keys().copied().collect();
625        let mut idx: HashMap<&'static str, usize> = HashMap::new();
626        for (i, &n) in names.iter().enumerate() {
627            idx.insert(n, i);
628        }
629
630        let mut adj = vec![Vec::<usize>::new(); names.len()];
631
632        for (&n, &deps) in &self.deps {
633            let u = *idx
634                .get(n)
635                .ok_or_else(|| RegistryError::UnknownGear(n.to_owned()))?;
636            for &d in deps {
637                let v = *idx.get(d).ok_or_else(|| RegistryError::UnknownDependency {
638                    gear: n.to_owned(),
639                    depends_on: d.to_owned(),
640                })?;
641                // edge d -> n (dep before gear)
642                adj[v].push(u);
643            }
644        }
645
646        Ok((names, adj, idx))
647    }
648
649    /// Assemble final gear entries in topological order.
650    fn assemble_entries(
651        &self,
652        order: &[usize],
653        names: &[&'static str],
654    ) -> Result<Vec<GearEntry>, RegistryError> {
655        let mut entries = Vec::with_capacity(order.len());
656        for &i in order {
657            let name = names[i];
658            let deps = *self
659                .deps
660                .get(name)
661                .ok_or_else(|| RegistryError::MissingDeps(name.to_owned()))?;
662
663            let core = self
664                .core
665                .get(name)
666                .cloned()
667                .ok_or_else(|| RegistryError::CoreNotFound(name.to_owned()))?;
668
669            // Build the capability set for this gear
670            let mut caps = CapabilitySet::new();
671
672            // Add capabilities from the main capabilities map
673            if let Some(gear_caps) = self.capabilities.get(name) {
674                for cap in gear_caps {
675                    caps.push(cap.clone());
676                }
677            }
678
679            // Add rest_host if this gear is the host
680            if let Some((host_name, gear)) = &self.rest_host
681                && *host_name == name
682            {
683                caps.push(Capability::ApiGateway(gear.clone()));
684            }
685
686            // Add grpc_hub if this gear is the hub
687            if let Some((hub_name, gear)) = &self.grpc_hub
688                && *hub_name == name
689            {
690                caps.push(Capability::GrpcHub(gear.clone()));
691            }
692
693            let entry = GearEntry {
694                name,
695                deps,
696                core,
697                caps,
698            };
699            entries.push(entry);
700        }
701        Ok(entries)
702    }
703
704    /// Finalize & topo-sort; verify deps & capability binding to known cores.
705    ///
706    /// # Errors
707    /// Returns `RegistryError` if validation fails or a dependency cycle is detected.
708    pub fn build_topo_sorted(self) -> Result<GearRegistry, RegistryError> {
709        // 1) Validate all capabilities
710        self.validate_capabilities()?;
711
712        // 2) Build dependency graph
713        let (names, adj, _idx) = self.build_dependency_graph()?;
714        self.validate_system_deps()?;
715
716        // 3) Cycle detection using DFS with path tracking
717        if let Some(cycle_path) = Self::detect_cycle_with_path(&names, &adj) {
718            return Err(RegistryError::CycleDetected { path: cycle_path });
719        }
720
721        // 4) Kahn's algorithm for topological sorting
722        let mut indeg = vec![0usize; names.len()];
723        for adj_list in &adj {
724            for &target in adj_list {
725                indeg[target] += 1;
726            }
727        }
728
729        let mut q = VecDeque::new();
730        for (i, &degree) in indeg.iter().enumerate() {
731            if degree == 0 {
732                q.push_back(i);
733            }
734        }
735
736        let mut order = Vec::with_capacity(names.len());
737        while let Some(u) = q.pop_front() {
738            order.push(u);
739            for &w in &adj[u] {
740                indeg[w] -= 1;
741                if indeg[w] == 0 {
742                    q.push_back(w);
743                }
744            }
745        }
746
747        // 5) Assemble final entries
748        let entries = self.assemble_entries(&order, &names)?;
749
750        // Collect grpc_hub and grpc_services for the final registry
751        let grpc_hub = self.grpc_hub.as_ref().map(|(name, _)| (*name).to_owned());
752
753        // Collect grpc_services from capabilities
754        let mut grpc_services: Vec<(String, Arc<dyn contracts::GrpcServiceCapability>)> =
755            Vec::new();
756        for (name, caps) in &self.capabilities {
757            for cap in caps {
758                if let Capability::GrpcService(service) = cap {
759                    grpc_services.push(((*name).to_owned(), service.clone()));
760                }
761            }
762        }
763
764        tracing::info!(
765            gears = ?entries.iter().map(|e| e.name).collect::<Vec<_>>(),
766            "Gear dependency order resolved (topo)"
767        );
768
769        Ok(GearRegistry {
770            gears: entries,
771            grpc_hub,
772            grpc_services,
773        })
774    }
775}
776
777/// Structured errors for the gear registry.
778#[derive(Debug, Error)]
779pub enum RegistryError {
780    // Phase errors with gear context
781    #[error("pre-init failed for gear '{gear}'")]
782    PreInit {
783        gear: &'static str,
784        #[source]
785        source: anyhow::Error,
786    },
787    #[error("initialization failed for gear '{gear}'")]
788    Init {
789        gear: &'static str,
790        #[source]
791        source: anyhow::Error,
792    },
793    #[error("post-init failed for gear '{gear}'")]
794    PostInit {
795        gear: &'static str,
796        #[source]
797        source: anyhow::Error,
798    },
799    #[error("GTS publication setup failed for gear '{gear}'")]
800    Publication {
801        gear: &'static str,
802        #[source]
803        source: anyhow::Error,
804    },
805    /// Two publishing gears declare one GTS id; the source names both.
806    #[error("GTS publication setup failed: a GTS id has two publishers")]
807    GtsOwnership {
808        #[source]
809        source: anyhow::Error,
810    },
811    /// A GTS publication of the application group failed (refused or expired):
812    /// no application gear initialized. Returned after the system group, which
813    /// keeps serving, is shut down.
814    #[error(
815        "the application group did not start: {}",
816        .failures.iter().map(|e| format!("{e:#}")).collect::<Vec<_>>().join("; ")
817    )]
818    ApplicationGroupNotStarted {
819        failures: Vec<crate::gts_publication::GtsPublicationError>,
820    },
821    #[error("start failed for '{gear}'")]
822    Start {
823        gear: &'static str,
824        #[source]
825        source: anyhow::Error,
826    },
827
828    #[error("DB migration failed for gear '{gear}'")]
829    DbMigrate {
830        gear: &'static str,
831        #[source]
832        source: anyhow::Error,
833    },
834    #[error("REST prepare failed for host gear '{gear}'")]
835    RestPrepare {
836        gear: &'static str,
837        #[source]
838        source: anyhow::Error,
839    },
840    #[error("REST registration failed for gear '{gear}'")]
841    RestRegister {
842        gear: &'static str,
843        #[source]
844        source: anyhow::Error,
845    },
846    #[error("REST finalize failed for host gear '{gear}'")]
847    RestFinalize {
848        gear: &'static str,
849        #[source]
850        source: anyhow::Error,
851    },
852    #[error("consumer proxy-wiring failed for gear '{gear}': {source}")]
853    ProxyWiring {
854        gear: &'static str,
855        #[source]
856        source: anyhow::Error,
857    },
858    #[error(
859        "REST phase requires an gateway host: gears with capability 'rest' found, but no gear with capability 'rest_host'"
860    )]
861    RestRequiresHost,
862    #[error("multiple 'rest_host' gears detected; exactly one is allowed")]
863    MultipleRestHosts,
864    #[error("REST host gear not found after validation")]
865    RestHostNotFoundAfterValidation,
866    #[error("REST host missing from entry")]
867    RestHostMissingFromEntry,
868
869    // gRPC-related errors
870    #[error("gRPC registration failed for gear '{gear}'")]
871    GrpcRegister {
872        gear: String,
873        #[source]
874        source: anyhow::Error,
875    },
876    #[error(
877        "gRPC phase requires a hub: gears with capability 'grpc' found, but no gear with capability 'grpc_hub'"
878    )]
879    GrpcRequiresHub,
880    #[error("multiple 'grpc_hub' gears detected; exactly one is allowed")]
881    MultipleGrpcHubs,
882
883    // OoP spawn errors
884    #[error("OoP spawn failed for gear '{gear}'")]
885    OopSpawn {
886        gear: String,
887        #[source]
888        source: anyhow::Error,
889    },
890
891    // Cancellation error
892    #[error("operation cancelled by termination signal")]
893    Cancelled,
894
895    /// A gear's context construction + `init()` did not finish within the
896    /// configured init deadline (the async path; a synchronous block that wedges
897    /// a runtime worker is caught by the force-exit watchdog instead).
898    #[error("initialization timed out for gear '{gear}' after {timeout:?}")]
899    InitTimeout {
900        gear: &'static str,
901        timeout: std::time::Duration,
902    },
903
904    // Build/topo-sort errors
905    #[error("unknown gear '{0}'")]
906    UnknownGear(String),
907    #[error("gear '{gear}' depends on unknown '{depends_on}'")]
908    UnknownDependency { gear: String, depends_on: String },
909    #[error(
910        "system gear '{gear}' depends on application gear '{depends_on}'; \
911         the system group starts before the application group is prepared"
912    )]
913    SystemDependsOnApplication { gear: String, depends_on: String },
914    #[error("cyclic dependency detected: {}", path.join(" -> "))]
915    CycleDetected { path: Vec<&'static str> },
916    #[error("missing deps for '{0}'")]
917    MissingDeps(String),
918    #[error("core not found for '{0}'")]
919    CoreNotFound(String),
920    #[error("invalid registry configuration:\n{errors:#?}")]
921    InvalidRegistryConfiguration { errors: Vec<String> },
922}
923
924#[cfg(test)]
925#[cfg_attr(coverage_nightly, coverage(off))]
926mod tests {
927    use super::*;
928    use std::sync::Arc;
929
930    // Use the real contracts/context APIs from the crate to avoid type mismatches.
931    use crate::context::GearCtx;
932    use crate::contracts;
933
934    /* --------------------------- Test helpers ------------------------- */
935    #[derive(Default)]
936    struct DummyCore;
937    #[async_trait::async_trait]
938    impl contracts::Gear for DummyCore {
939        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
940            Ok(())
941        }
942    }
943
944    /* ------------------------------- Tests ---------------------------- */
945
946    #[test]
947    fn topo_sort_happy_path() {
948        let mut b = RegistryBuilder::default();
949        // cores
950        b.register_core_with_meta("core_a", &[], Arc::new(DummyCore));
951        b.register_core_with_meta("core_b", &["core_a"], Arc::new(DummyCore));
952
953        let reg = b.build_topo_sorted().unwrap();
954        let order: Vec<_> = reg.gears().iter().map(|m| m.name).collect();
955        assert_eq!(order, vec!["core_a", "core_b"]);
956    }
957
958    #[test]
959    fn unknown_dependency_error() {
960        let mut b = RegistryBuilder::default();
961        b.register_core_with_meta("core_a", &["missing_dep"], Arc::new(DummyCore));
962
963        let err = b.build_topo_sorted().unwrap_err();
964        match err {
965            RegistryError::UnknownDependency { gear, depends_on } => {
966                assert_eq!(gear, "core_a");
967                assert_eq!(depends_on, "missing_dep");
968            }
969            other => panic!("unexpected error: {other:?}"),
970        }
971    }
972
973    #[test]
974    fn cyclic_dependency_detected() {
975        let mut b = RegistryBuilder::default();
976        b.register_core_with_meta("a", &["b"], Arc::new(DummyCore));
977        b.register_core_with_meta("b", &["a"], Arc::new(DummyCore));
978
979        let err = b.build_topo_sorted().unwrap_err();
980        match err {
981            RegistryError::CycleDetected { path } => {
982                // Should contain both gears in the cycle
983                assert!(path.contains(&"a"));
984                assert!(path.contains(&"b"));
985                assert!(path.len() >= 3); // At least a -> b -> a
986            }
987            other => panic!("expected CycleDetected, got: {other:?}"),
988        }
989    }
990
991    #[test]
992    fn complex_cycle_detection_with_path() {
993        let mut b = RegistryBuilder::default();
994        // Create a more complex cycle: a -> b -> c -> a
995        b.register_core_with_meta("a", &["b"], Arc::new(DummyCore));
996        b.register_core_with_meta("b", &["c"], Arc::new(DummyCore));
997        b.register_core_with_meta("c", &["a"], Arc::new(DummyCore));
998        // Add an unrelated gear to ensure we only detect the actual cycle
999        b.register_core_with_meta("d", &[], Arc::new(DummyCore));
1000
1001        let err = b.build_topo_sorted().unwrap_err();
1002        match err {
1003            RegistryError::CycleDetected { path } => {
1004                // Should contain all gears in the cycle
1005                assert!(path.contains(&"a"));
1006                assert!(path.contains(&"b"));
1007                assert!(path.contains(&"c"));
1008                assert!(!path.contains(&"d")); // Should not include unrelated gear
1009                assert!(path.len() >= 4); // At least a -> b -> c -> a
1010
1011                // Verify the error message is helpful
1012                let error_msg = format!("{}", RegistryError::CycleDetected { path: path.clone() });
1013                assert!(error_msg.contains("cyclic dependency detected"));
1014                assert!(error_msg.contains("->"));
1015            }
1016            other => panic!("expected CycleDetected, got: {other:?}"),
1017        }
1018    }
1019
1020    #[test]
1021    fn duplicate_core_reported_in_configuration_errors() {
1022        let mut b = RegistryBuilder::default();
1023        b.register_core_with_meta("a", &[], Arc::new(DummyCore));
1024        // duplicate
1025        b.register_core_with_meta("a", &[], Arc::new(DummyCore));
1026
1027        let err = b.build_topo_sorted().unwrap_err();
1028        match err {
1029            RegistryError::InvalidRegistryConfiguration { errors } => {
1030                assert!(
1031                    errors.iter().any(|e| e.contains("already registered")),
1032                    "expected duplicate registration error, got {errors:?}"
1033                );
1034            }
1035            other => panic!("unexpected error: {other:?}"),
1036        }
1037    }
1038
1039    #[test]
1040    fn rest_capability_without_core_fails() {
1041        let mut b = RegistryBuilder::default();
1042        b.register_core_with_meta("core_a", &[], Arc::new(DummyCore));
1043        // Register a rest capability for a gear that doesn't exist
1044        b.register_rest_with_meta("unknown_gear", Arc::new(DummyRest));
1045
1046        let err = b.build_topo_sorted().unwrap_err();
1047        match err {
1048            RegistryError::UnknownGear(name) => {
1049                assert_eq!(name, "unknown_gear");
1050            }
1051            other => panic!("expected UnknownGear, got: {other:?}"),
1052        }
1053    }
1054
1055    #[test]
1056    #[cfg(feature = "db")]
1057    fn db_capability_without_core_fails() {
1058        let mut b = RegistryBuilder::default();
1059        b.register_core_with_meta("core_a", &[], Arc::new(DummyCore));
1060        // Register a db capability for a gear that doesn't exist
1061        b.register_db_with_meta("unknown_gear", Arc::new(DummyDb));
1062
1063        let err = b.build_topo_sorted().unwrap_err();
1064        match err {
1065            RegistryError::UnknownGear(name) => {
1066                assert_eq!(name, "unknown_gear");
1067            }
1068            other => panic!("expected UnknownGear, got: {other:?}"),
1069        }
1070    }
1071
1072    #[test]
1073    fn stateful_capability_without_core_fails() {
1074        let mut b = RegistryBuilder::default();
1075        b.register_core_with_meta("core_a", &[], Arc::new(DummyCore));
1076        // Register a stateful capability for a gear that doesn't exist
1077        b.register_stateful_with_meta("unknown_gear", Arc::new(DummyStateful));
1078
1079        let err = b.build_topo_sorted().unwrap_err();
1080        match err {
1081            RegistryError::UnknownGear(name) => {
1082                assert_eq!(name, "unknown_gear");
1083            }
1084            other => panic!("expected UnknownGear, got: {other:?}"),
1085        }
1086    }
1087
1088    #[test]
1089    #[cfg(feature = "db")]
1090    fn capability_query_works() {
1091        let mut b = RegistryBuilder::default();
1092        let gear = Arc::new(DummyCore);
1093        b.register_core_with_meta("test", &[], gear);
1094        b.register_db_with_meta("test", Arc::new(DummyDb));
1095        b.register_rest_with_meta("test", Arc::new(DummyRest));
1096
1097        let reg = b.build_topo_sorted().unwrap();
1098        let entry = &reg.gears()[0];
1099
1100        assert!(entry.caps.has::<DatabaseCap>());
1101        assert!(entry.caps.has::<RestApiCap>());
1102        assert!(!entry.caps.has::<SystemCap>());
1103
1104        assert!(entry.caps.query::<DatabaseCap>().is_some());
1105        assert!(entry.caps.query::<RestApiCap>().is_some());
1106        assert!(entry.caps.query::<SystemCap>().is_none());
1107    }
1108
1109    #[test]
1110    fn rest_host_capability_without_core_fails() {
1111        let mut b = RegistryBuilder::default();
1112        b.register_core_with_meta("core_a", &[], Arc::new(DummyCore));
1113        // Set rest_host to a gear that doesn't exist
1114        b.register_rest_host_with_meta("unknown_host", Arc::new(DummyRestHost));
1115
1116        let err = b.build_topo_sorted().unwrap_err();
1117        match err {
1118            RegistryError::UnknownGear(name) => {
1119                assert_eq!(name, "unknown_host");
1120            }
1121            other => panic!("expected UnknownGear, got: {other:?}"),
1122        }
1123    }
1124
1125    #[test]
1126    fn gear_entry_getters_work() {
1127        let mut b = RegistryBuilder::default();
1128        b.register_core_with_meta("alpha", &[], Arc::new(DummyCore));
1129        b.register_core_with_meta("beta", &["alpha"], Arc::new(DummyCore));
1130        b.register_rest_with_meta("beta", Arc::new(DummyRest));
1131
1132        let reg = b.build_topo_sorted().unwrap();
1133        let beta = reg.gears().iter().find(|e| e.name() == "beta").unwrap();
1134
1135        assert_eq!(beta.name(), "beta");
1136        assert_eq!(beta.deps(), &["alpha"]);
1137        assert!(beta.caps().has::<RestApiCap>());
1138    }
1139
1140    #[test]
1141    fn test_gear_registry_builds() {
1142        let registry = GearRegistry::discover_and_build();
1143        assert!(registry.is_ok(), "Registry should build successfully");
1144    }
1145
1146    /* Test helper implementations */
1147    #[derive(Default, Clone)]
1148    struct DummyRest;
1149    impl contracts::RestApiCapability for DummyRest {
1150        fn register_rest(
1151            &self,
1152            _ctx: &crate::context::GearCtx,
1153            _router: axum::Router,
1154            _openapi: &dyn crate::api::OpenApiRegistry,
1155        ) -> anyhow::Result<axum::Router> {
1156            Ok(axum::Router::new())
1157        }
1158    }
1159
1160    #[cfg(feature = "db")]
1161    #[derive(Default)]
1162    struct DummyDb;
1163    #[cfg(feature = "db")]
1164    impl contracts::DatabaseCapability for DummyDb {
1165        fn migrations(&self) -> Vec<Box<dyn sea_orm_migration::MigrationTrait>> {
1166            vec![]
1167        }
1168    }
1169
1170    #[derive(Default)]
1171    struct DummyStateful;
1172    #[async_trait::async_trait]
1173    impl contracts::RunnableCapability for DummyStateful {
1174        async fn start(&self, _cancel: tokio_util::sync::CancellationToken) -> anyhow::Result<()> {
1175            Ok(())
1176        }
1177        async fn stop(&self, _cancel: tokio_util::sync::CancellationToken) -> anyhow::Result<()> {
1178            Ok(())
1179        }
1180    }
1181
1182    #[derive(Default)]
1183    struct DummyRestHost;
1184    impl contracts::ApiGatewayCapability for DummyRestHost {
1185        fn rest_prepare(
1186            &self,
1187            _ctx: &crate::context::GearCtx,
1188            router: axum::Router,
1189            _hc_registry: std::sync::Arc<crate::healthcheck::RestHealthcheckRegistry>,
1190        ) -> anyhow::Result<axum::Router> {
1191            Ok(router)
1192        }
1193        fn rest_finalize(
1194            &self,
1195            _ctx: &crate::context::GearCtx,
1196            router: axum::Router,
1197            _hc_registry: std::sync::Arc<crate::healthcheck::RestHealthcheckRegistry>,
1198        ) -> anyhow::Result<axum::Router> {
1199            Ok(router)
1200        }
1201        fn as_registry(&self) -> &dyn crate::contracts::OpenApiRegistry {
1202            panic!("DummyRestHost::as_registry should not be called in tests")
1203        }
1204    }
1205}