Skip to main content

vibe/extension_registry/
registry.rs

1//! Atomic, bounded extension provider registry (`ExtensionRegistry`) for `crates/vibe`.
2
3use vibescript_abi::{
4    q_hash_str, FuncDescriptor, ProviderDescriptor, RegistryGeneration,
5    SubNamespaceDescriptor, VibeNamespaceProvider, VibeOpCode, VibeTrap,
6};
7
8/// Maximum number of concurrently registered extension providers in a fixed-size registry.
9pub const MAX_EXTENSION_PROVIDERS: usize = 32;
10
11/// Fixed-capacity, generational registry of `VibeNamespaceProvider` implementations.
12///
13/// Registration is cold and atomic: if any validation check fails (hash mismatch,
14/// duplicate IRI/alias/ID, `q_hash` collision, or invalid ontology parity/budget),
15/// the registry remains completely unchanged.
16pub struct ExtensionRegistry<'p> {
17    slots: [Option<&'p dyn VibeNamespaceProvider>; MAX_EXTENSION_PROVIDERS],
18    generation: RegistryGeneration,
19    active_count: usize,
20}
21
22impl<'p> Default for ExtensionRegistry<'p> {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28impl<'p> ExtensionRegistry<'p> {
29    /// Creates an empty `ExtensionRegistry` at `RegistryGeneration::INITIAL`.
30    #[inline]
31    pub const fn new() -> Self {
32        Self {
33            slots: [None; MAX_EXTENSION_PROVIDERS],
34            generation: RegistryGeneration::INITIAL,
35            active_count: 0,
36        }
37    }
38
39    /// Current registry generation counter.
40    #[inline]
41    pub const fn generation(&self) -> RegistryGeneration {
42        self.generation
43    }
44
45    /// Number of currently active providers.
46    #[inline]
47    pub const fn active_count(&self) -> usize {
48        self.active_count
49    }
50
51    /// Atomically validates and registers `provider`, returning its assigned `ns_slot`
52    /// and advancing `self.generation`.
53    pub fn register(&mut self, provider: &'p dyn VibeNamespaceProvider) -> Result<u32, VibeTrap> {
54        let free_slot = self
55            .slots
56            .iter()
57            .position(|s| s.is_none())
58            .ok_or(VibeTrap::RegistryCapacityExceeded)?;
59
60        let desc = provider.descriptor();
61        let ontology = provider.static_ontology_nquins();
62
63        // 1. Validate canonical IRI and short alias
64        if desc.canonical_iri.iri.is_empty() || desc.short_alias.is_empty() {
65            return Err(VibeTrap::InvalidCanonicalIri);
66        }
67        if desc.canonical_iri.fnv1a_hash != q_hash_str(desc.canonical_iri.iri) {
68            return Err(VibeTrap::HashMismatch);
69        }
70
71        // 2. Validate 5-axis version compatibility
72        if !desc.versions.is_engine_compatible() {
73            return Err(VibeTrap::IncompatibleVersionAxes);
74        }
75
76        // 3. Validate ontology budget and NQuin48 XOR parity
77        if ontology.len() > desc.max_ontology_quins as usize {
78            return Err(VibeTrap::OntologyBudgetExceeded);
79        }
80        for quin in ontology {
81            if !quin.verify_parity() {
82                return Err(VibeTrap::InvalidQuinParity);
83            }
84        }
85
86        // 4. Validate intra-provider sub-namespaces, functions, and ontology spans
87        for (sub_idx_a, sub_a) in desc.sub_namespaces.iter().enumerate() {
88            if sub_a.name.is_empty() {
89                return Err(VibeTrap::InvalidCanonicalIri);
90            }
91            for sub_b in &desc.sub_namespaces[..sub_idx_a] {
92                if sub_a.sub_id == sub_b.sub_id || sub_a.name == sub_b.name {
93                    return Err(VibeTrap::DuplicateStableFuncId);
94                }
95            }
96            for (fn_idx_a, fn_a) in sub_a.functions.iter().enumerate() {
97                if fn_a.name.is_empty() || fn_a.canonical_iri.iri.is_empty() {
98                    return Err(VibeTrap::InvalidCanonicalIri);
99                }
100                if fn_a.canonical_iri.fnv1a_hash != q_hash_str(fn_a.canonical_iri.iri) {
101                    return Err(VibeTrap::HashMismatch);
102                }
103                if fn_a.stable_id.sub_namespace_id != sub_a.sub_id {
104                    return Err(VibeTrap::DuplicateStableFuncId);
105                }
106                if !fn_a.contract.validate_spans(ontology.len()) {
107                    return Err(VibeTrap::InvalidOntologySpan);
108                }
109                // Check against earlier functions in the same sub-namespace
110                for fn_b in &sub_a.functions[..fn_idx_a] {
111                    Self::check_intra_provider_function_conflict(fn_a, fn_b, true)?;
112                }
113                // Check against functions in earlier sub-namespaces of the same provider
114                for prev_sub in &desc.sub_namespaces[..sub_idx_a] {
115                    for fn_b in prev_sub.functions {
116                        Self::check_intra_provider_function_conflict(fn_a, fn_b, false)?;
117                    }
118                }
119            }
120        }
121
122        // 5. Validate cross-provider collisions against all currently registered providers
123        for existing in self.slots.iter().flatten() {
124            let ex_desc = existing.descriptor();
125            if ex_desc.canonical_iri.iri == desc.canonical_iri.iri {
126                return Err(VibeTrap::DuplicateNamespaceIri);
127            }
128            if ex_desc.canonical_iri.fnv1a_hash == desc.canonical_iri.fnv1a_hash {
129                return Err(VibeTrap::HashCollisionDetected);
130            }
131            if ex_desc.short_alias == desc.short_alias {
132                return Err(VibeTrap::DuplicateShortAlias);
133            }
134            for sub_new in desc.sub_namespaces {
135                for fn_new in sub_new.functions {
136                    for sub_ex in ex_desc.sub_namespaces {
137                        for fn_ex in sub_ex.functions {
138                            Self::check_cross_provider_function_conflict(fn_new, fn_ex)?;
139                        }
140                    }
141                }
142            }
143        }
144
145        // 6. Commit atomically and advance generation
146        self.slots[free_slot] = Some(provider);
147        self.active_count += 1;
148        self.generation = self.generation.next();
149        Ok(free_slot as u32)
150    }
151
152    /// Unregisters the provider at `slot` and advances `self.generation` so all
153    /// previously prepared handles fail closed with `VibeTrap::StaleRegistryGeneration`.
154    pub fn unregister(&mut self, slot: u32) -> Result<(), VibeTrap> {
155        let idx = slot as usize;
156        if idx >= MAX_EXTENSION_PROVIDERS || self.slots[idx].is_none() {
157            return Err(VibeTrap::NamespaceNotFound);
158        }
159        self.slots[idx] = None;
160        self.active_count = self.active_count.saturating_sub(1);
161        self.generation = self.generation.next();
162        Ok(())
163    }
164
165    /// Looks up a registered provider by slot index.
166    #[inline]
167    pub fn provider_at(&self, slot: u32) -> Option<&'p dyn VibeNamespaceProvider> {
168        self.slots.get(slot as usize).copied().flatten()
169    }
170
171    /// Iterates over all active providers currently registered in the registry.
172    #[inline]
173    pub fn iter_providers(&self) -> impl Iterator<Item = &'p dyn VibeNamespaceProvider> + '_ {
174        self.slots.iter().flatten().copied()
175    }
176
177    /// Resolves a `(provider, FuncDescriptor)` in bounded time from a `VibeOpCode`.
178    #[inline]
179    pub fn resolve_opcode(
180        &self,
181        opcode: VibeOpCode,
182    ) -> Result<(&'p dyn VibeNamespaceProvider, &'static FuncDescriptor), VibeTrap> {
183        let provider = self
184            .provider_at(opcode.ns_slot())
185            .ok_or(VibeTrap::NamespaceNotFound)?;
186        let desc = provider.descriptor();
187        let target_sub = opcode.sub_namespace_id();
188        let target_fn = opcode.func_id();
189        let mut s_idx = 0;
190        while s_idx < desc.sub_namespaces.len() {
191            let sub = &desc.sub_namespaces[s_idx];
192            if sub.sub_id == target_sub {
193                let mut f_idx = 0;
194                while f_idx < sub.functions.len() {
195                    let func = &sub.functions[f_idx];
196                    if func.stable_id.func_id == target_fn {
197                        return Ok((provider, func));
198                    }
199                    f_idx += 1;
200                }
201                return Err(VibeTrap::FunctionNotFound);
202            }
203            s_idx += 1;
204        }
205        Err(VibeTrap::FunctionNotFound)
206    }
207
208    /// Finds a registered provider by canonical IRI or short alias.
209    pub fn find_by_namespace_or_alias(
210        &self,
211        namespace_or_alias: &str,
212    ) -> Option<(u32, &'p dyn VibeNamespaceProvider, &'static ProviderDescriptor)> {
213        for (idx, slot) in self.slots.iter().enumerate() {
214            if let Some(provider) = slot {
215                let desc = provider.descriptor();
216                if desc.canonical_iri.iri == namespace_or_alias
217                    || desc.short_alias == namespace_or_alias
218                {
219                    return Some((idx as u32, *provider, desc));
220                }
221            }
222        }
223        None
224    }
225
226    /// Iterates over all active provider descriptors.
227    pub fn find_sub_namespace<'a>(
228        desc: &'a ProviderDescriptor,
229        sub_name: &str,
230    ) -> Option<&'a SubNamespaceDescriptor> {
231        desc.sub_namespaces.iter().find(|s| s.name == sub_name)
232    }
233
234    fn check_intra_provider_function_conflict(
235        a: &FuncDescriptor,
236        b: &FuncDescriptor,
237        same_sub_namespace: bool,
238    ) -> Result<(), VibeTrap> {
239        if a.canonical_iri.iri == b.canonical_iri.iri {
240            return Err(VibeTrap::DuplicateFunctionIri);
241        }
242        if a.canonical_iri.fnv1a_hash == b.canonical_iri.fnv1a_hash {
243            return Err(VibeTrap::HashCollisionDetected);
244        }
245        if a.stable_id == b.stable_id || (same_sub_namespace && a.name == b.name) {
246            return Err(VibeTrap::DuplicateStableFuncId);
247        }
248        Ok(())
249    }
250
251    fn check_cross_provider_function_conflict(
252        a: &FuncDescriptor,
253        b: &FuncDescriptor,
254    ) -> Result<(), VibeTrap> {
255        if a.canonical_iri.iri == b.canonical_iri.iri {
256            return Err(VibeTrap::DuplicateFunctionIri);
257        }
258        if a.canonical_iri.fnv1a_hash == b.canonical_iri.fnv1a_hash {
259            return Err(VibeTrap::HashCollisionDetected);
260        }
261        Ok(())
262    }
263
264    /// Checks whether a `StableFuncId` is duplicated within the same provider.
265    pub fn validate_unique_stable_ids(desc: &ProviderDescriptor) -> Result<(), VibeTrap> {
266        for (i, sub_a) in desc.sub_namespaces.iter().enumerate() {
267            for (j, fn_a) in sub_a.functions.iter().enumerate() {
268                for fn_b in &sub_a.functions[..j] {
269                    if fn_a.stable_id == fn_b.stable_id || fn_a.name == fn_b.name {
270                        return Err(VibeTrap::DuplicateStableFuncId);
271                    }
272                }
273                for sub_b in &desc.sub_namespaces[..i] {
274                    for fn_b in sub_b.functions {
275                        if fn_a.stable_id == fn_b.stable_id {
276                            return Err(VibeTrap::DuplicateStableFuncId);
277                        }
278                    }
279                }
280            }
281        }
282        Ok(())
283    }
284}