Skip to main content

subc_daemon/
registry.rs

1use std::{
2    collections::{BTreeMap, HashMap, HashSet},
3    error::Error,
4    fmt,
5    sync::{Mutex, MutexGuard},
6};
7
8use subc_protocol::manifest::{CapabilityDeclarations, ModuleManifest, ProviderRole};
9use tokio::sync::watch;
10use tracing::info;
11
12/// Per-connection identity assigned by [`crate::Router`] while serving a socket.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct ConnectionId(u64);
15
16impl ConnectionId {
17    /// Synthetic connection id used by unit tests. Router-issued connection ids
18    /// start at 1, so this 0 value never collides with a real socket owner.
19    #[cfg(test)]
20    pub const LOCAL: Self = Self(0);
21
22    pub const fn new(raw: u64) -> Self {
23        Self(raw)
24    }
25
26    pub fn get(self) -> u64 {
27        self.0
28    }
29}
30
31/// Lifecycle state for a module's channel allocation.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ChannelState {
34    Active,
35    Closed,
36}
37
38/// Why a module registration stopped belonging to its connection.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub(crate) enum RegistrationEndReason {
41    ConnectionClosed,
42    ExplicitGoodbye,
43    Replaced,
44    SupervisorStop,
45    SupervisorRestart,
46    RegistrationFailed,
47}
48
49impl RegistrationEndReason {
50    fn as_str(self) -> &'static str {
51        match self {
52            Self::ConnectionClosed => "connection_closed",
53            Self::ExplicitGoodbye => "explicit_goodbye",
54            Self::Replaced => "replaced",
55            Self::SupervisorStop => "supervisor_stop",
56            Self::SupervisorRestart => "supervisor_restart",
57            Self::RegistrationFailed => "registration_failed",
58        }
59    }
60}
61
62/// Registry record for one active module registration.
63#[derive(Debug, Clone, PartialEq)]
64pub struct ModuleRegistration {
65    pub manifest: ModuleManifest,
66    pub ready: bool,
67    pub negotiated_ver: u8,
68    pub state: ChannelState,
69    pub connection_id: ConnectionId,
70    pub control_ops: Vec<String>,
71}
72
73/// Active routing registrations and their publication state from one lock.
74pub(crate) struct RouteAdmissionSnapshot {
75    pub(crate) modules: Vec<ModuleRegistration>,
76    pub(crate) unpublished: HashSet<ConnectionId>,
77}
78
79impl std::ops::Deref for RouteAdmissionSnapshot {
80    type Target = [ModuleRegistration];
81
82    fn deref(&self) -> &Self::Target {
83        &self.modules
84    }
85}
86
87/// Which registration a lookup or a lifecycle wait is about.
88///
89/// A module id alone stops naming one process once a blue/green swap runs two
90/// processes under the same id: the incumbent in the active slot, the
91/// replacement in the candidate slot, and, after cutover, the old incumbent
92/// demoted until its connection goes away. A wait keyed on the bare id would
93/// confuse them (a successful swap never empties the id's active slot, and a
94/// candidate's "has it registered yet" would be answered by the incumbent).
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum RegistrationSlot<'a> {
97    /// The routable registration for this module id. This is what every plain
98    /// start, stop and restart path means by "the module is registered".
99    Active(&'a str),
100    /// A swap candidate registered under this module id and not yet promoted.
101    Candidate(&'a str),
102    /// Whatever registration this module connection holds, in any slot.
103    Connection(ConnectionId),
104}
105
106/// The result of promoting a module's candidate registration to active.
107#[derive(Debug, Clone, PartialEq)]
108pub struct RegistryCutover {
109    /// The registration that is now active (the former candidate).
110    pub promoted: ModuleRegistration,
111    /// The former active registration, now demoted. `None` when the incumbent
112    /// had already gone away before the promotion.
113    pub superseded: Option<ModuleRegistration>,
114}
115
116/// Control-plane registry for module manifests and supervision ownership.
117///
118/// Duplicate active `module_id`s are rejected rather than replaced. Rejection is
119/// the safer v1 behavior because replacing a still-connected module could hijack
120/// in-flight routes. Stale registrations are removed by connection cleanup; a
121/// reconnect after the old connection drops can then register the same id again.
122///
123/// A blue/green swap is the one sanctioned way two processes hold the same id.
124/// The replacement registers into a separate candidate slot, which every by-id
125/// lookup ignores, so it stays unroutable until [`Registry::promote_candidate`]
126/// swaps it in. The old incumbent is then kept as "superseded" until its
127/// connection deregisters. Lookups keyed by connection id search all three
128/// slots, because a connection must be able to update and remove its own
129/// registration whichever slot it currently sits in.
130#[derive(Debug, Default)]
131pub struct Registry {
132    inner: Mutex<RegistryInner>,
133    #[cfg(test)]
134    next_lock_attempt: Mutex<Option<std::sync::mpsc::Sender<bool>>>,
135}
136
137#[derive(Debug, Default)]
138struct RegistryInner {
139    /// Only subscribed module ids have a sender. Changes coalesce, and writers
140    /// never wait for a supervisor to receive them.
141    // The value counts accepted active registrations. Keep that evidence even
142    // when register and disconnect coalesce before a supervisor receives them.
143    module_changes: HashMap<String, watch::Sender<u64>>,
144    modules: HashMap<String, ModuleRegistration>,
145    /// Swap candidates by module id: registered, never routable, never listed.
146    candidates: HashMap<String, ModuleRegistration>,
147    /// Former incumbents demoted by a promotion, kept only so their own
148    /// connection can still find and remove them. Never routable, never listed.
149    superseded: Vec<ModuleRegistration>,
150    /// Connections whose HELLO passed the launch-nonce check required for a
151    /// reserved module or swap candidate. Kept outside ModuleRegistration so
152    /// adding this catalog fact does not break callers that construct the public
153    /// registration struct.
154    nonce_verified: HashSet<ConnectionId>,
155    /// The active connection that displaced each superseded registration.
156    superseded_by: HashMap<ConnectionId, ConnectionId>,
157    /// Connections whose registration is reserved but not yet published.
158    ///
159    /// A HELLO registers in the registry before the daemon installs the
160    /// module's forwarding endpoint, and until that endpoint exists a
161    /// `route.open` to the module cannot be relayed. A registration in this set
162    /// already holds its module id (a duplicate HELLO is refused) and is found
163    /// by every lookup except two: [`Registry::list_modules`], which feeds
164    /// `catalog.list`, and [`Registry::published_registration`], which the swap
165    /// supervisor reads to decide that a candidate has registered. Adding a
166    /// registration to this set does not bump the catalog generation;
167    /// [`Registry::publish_registration`] removes it and bumps the generation
168    /// in the same critical section, so a catalog reader sees the module and
169    /// the new generation together.
170    unpublished: HashSet<ConnectionId>,
171    generation: u64,
172    catalog_changes: Option<watch::Sender<u64>>,
173}
174
175impl Registry {
176    /// Capture the current catalog generation and subscribe atomically. Writers
177    /// replace one value; they never wait for discovery clients to receive it.
178    pub(crate) fn subscribe_catalog_changes(&self) -> Result<watch::Receiver<u64>, RegistryError> {
179        let mut inner = self.lock_inner()?;
180        let generation = inner.generation;
181        Ok(inner
182            .catalog_changes
183            .get_or_insert_with(|| watch::channel(generation).0)
184            .subscribe())
185    }
186
187    /// Notify discovery after an approved declaration-set change or a change to
188    /// the spawn's first-party mark (whether it may receive automatic grants).
189    /// The authority owner calls this only after publishing the new state; it
190    /// must not hold a spawn or forwarding lock while taking the registry lock.
191    pub fn catalog_authority_changed(&self) -> Result<(), RegistryError> {
192        self.lock_inner()?.bump_generation();
193        Ok(())
194    }
195
196    /// Subscribe before reading a registration so a change between the read
197    /// and the supervisor's wait remains pending on this receiver.
198    pub(crate) fn subscribe_module_changes(
199        &self,
200        module_id: &str,
201    ) -> Result<watch::Receiver<u64>, RegistryError> {
202        let mut inner = self.lock_inner()?;
203        // Retired supervisors must not leave an ever-growing set of ids.
204        inner
205            .module_changes
206            .retain(|_, sender| sender.receiver_count() > 0);
207        Ok(inner
208            .module_changes
209            .entry(module_id.to_string())
210            .or_insert_with(|| watch::channel(0).0)
211            .subscribe())
212    }
213
214    /// Register a module manifest with the module's effective granted control op set.
215    ///
216    /// The registration is published at once: it is listed by
217    /// [`Self::list_modules`] and bumps the catalog generation. The HELLO path
218    /// uses [`Self::register_unpublished_with_control_ops`] instead, because it
219    /// still has to install the module's forwarding endpoint.
220    pub fn register_with_control_ops(
221        &self,
222        manifest: ModuleManifest,
223        negotiated_ver: u8,
224        connection_id: ConnectionId,
225        control_ops: Vec<String>,
226    ) -> Result<ModuleRegistration, RegistryError> {
227        self.register_active(
228            manifest,
229            negotiated_ver,
230            connection_id,
231            control_ops,
232            true,
233            false,
234        )
235    }
236
237    /// Register a module manifest without listing it yet.
238    ///
239    /// The registration holds its module id and is visible to every lookup
240    /// except [`Self::list_modules`] (and so `catalog.list`) and
241    /// [`Self::published_registration`]. The catalog generation does not move.
242    /// Call [`Self::publish_registration`] once the module can actually be
243    /// routed to; if that never becomes possible, deregistering the connection
244    /// removes the entry without the catalog ever having listed it.
245    pub fn register_unpublished_with_control_ops(
246        &self,
247        manifest: ModuleManifest,
248        negotiated_ver: u8,
249        connection_id: ConnectionId,
250        control_ops: Vec<String>,
251    ) -> Result<ModuleRegistration, RegistryError> {
252        self.register_active(
253            manifest,
254            negotiated_ver,
255            connection_id,
256            control_ops,
257            false,
258            false,
259        )
260    }
261
262    /// Register a module after its HELLO is accepted, without listing it before forwarding is installed.
263    pub(crate) fn register_unpublished_verified_with_control_ops(
264        &self,
265        manifest: ModuleManifest,
266        negotiated_ver: u8,
267        connection_id: ConnectionId,
268        control_ops: Vec<String>,
269        nonce_verified: bool,
270    ) -> Result<ModuleRegistration, RegistryError> {
271        self.register_active(
272            manifest,
273            negotiated_ver,
274            connection_id,
275            control_ops,
276            false,
277            nonce_verified,
278        )
279    }
280
281    fn register_active(
282        &self,
283        manifest: ModuleManifest,
284        negotiated_ver: u8,
285        connection_id: ConnectionId,
286        control_ops: Vec<String>,
287        publish: bool,
288        nonce_verified: bool,
289    ) -> Result<ModuleRegistration, RegistryError> {
290        let module_id = manifest.module_id.clone();
291        if let Err(reason) = module_id_path_hazard(&module_id) {
292            return Err(RegistryError::PathHazardModuleId { module_id, reason });
293        }
294        let mut inner = self.lock_inner()?;
295        if inner.modules.contains_key(&module_id) {
296            return Err(RegistryError::DuplicateModuleId { module_id });
297        }
298
299        let ready = manifest.ready.unwrap_or(true);
300        let registration = ModuleRegistration {
301            manifest,
302            ready,
303            negotiated_ver,
304            state: ChannelState::Active,
305            connection_id,
306            control_ops,
307        };
308
309        inner.modules.insert(module_id, registration.clone());
310        if nonce_verified {
311            inner.nonce_verified.insert(connection_id);
312        } else {
313            inner.nonce_verified.remove(&connection_id);
314        }
315        if publish {
316            inner.bump_generation();
317        } else {
318            inner.unpublished.insert(connection_id);
319        }
320        if let Some(sender) = inner.module_changes.get(&registration.manifest.module_id) {
321            sender.send_modify(|accepted| *accepted = accepted.wrapping_add(1));
322        }
323        Ok(registration)
324    }
325
326    /// Register a swap candidate for `manifest.module_id` into the candidate slot.
327    ///
328    /// The candidate is invisible to [`Self::get_module`], [`Self::list_modules`]
329    /// and every other by-id lookup until [`Self::promote_candidate`]. An active
330    /// registration for the id is not required, because the incumbent may die
331    /// while the swap is open; deciding whether a candidate may register at all
332    /// belongs to the caller that admits it. A second candidate for the same id
333    /// is refused.
334    ///
335    /// The candidate is published at once, meaning candidate-slot lookups
336    /// through [`Self::published_registration`] return it immediately. The
337    /// HELLO path uses
338    /// [`Self::register_unpublished_candidate_with_control_ops`] instead.
339    pub fn register_candidate_with_control_ops(
340        &self,
341        manifest: ModuleManifest,
342        negotiated_ver: u8,
343        connection_id: ConnectionId,
344        control_ops: Vec<String>,
345    ) -> Result<ModuleRegistration, RegistryError> {
346        self.register_candidate(
347            manifest,
348            negotiated_ver,
349            connection_id,
350            control_ops,
351            true,
352            false,
353        )
354    }
355
356    /// Register a swap candidate that [`Self::published_registration`] does not
357    /// return until [`Self::publish_registration`] is called for its
358    /// connection. The swap supervisor reads that lookup to decide the
359    /// candidate has registered, and it promotes a ready candidate straight
360    /// away; promoting one whose forwarding endpoint is not installed yet would
361    /// fail the cutover.
362    pub fn register_unpublished_candidate_with_control_ops(
363        &self,
364        manifest: ModuleManifest,
365        negotiated_ver: u8,
366        connection_id: ConnectionId,
367        control_ops: Vec<String>,
368    ) -> Result<ModuleRegistration, RegistryError> {
369        self.register_candidate(
370            manifest,
371            negotiated_ver,
372            connection_id,
373            control_ops,
374            false,
375            false,
376        )
377    }
378
379    /// Register a blue/green swap candidate after its required launch nonce has been verified.
380    pub(crate) fn register_unpublished_verified_candidate_with_control_ops(
381        &self,
382        manifest: ModuleManifest,
383        negotiated_ver: u8,
384        connection_id: ConnectionId,
385        control_ops: Vec<String>,
386    ) -> Result<ModuleRegistration, RegistryError> {
387        self.register_candidate(
388            manifest,
389            negotiated_ver,
390            connection_id,
391            control_ops,
392            false,
393            true,
394        )
395    }
396
397    fn register_candidate(
398        &self,
399        manifest: ModuleManifest,
400        negotiated_ver: u8,
401        connection_id: ConnectionId,
402        control_ops: Vec<String>,
403        publish: bool,
404        nonce_verified: bool,
405    ) -> Result<ModuleRegistration, RegistryError> {
406        let module_id = manifest.module_id.clone();
407        if let Err(reason) = module_id_path_hazard(&module_id) {
408            return Err(RegistryError::PathHazardModuleId { module_id, reason });
409        }
410        let mut inner = self.lock_inner()?;
411        if inner.candidates.contains_key(&module_id) {
412            return Err(RegistryError::DuplicateModuleId { module_id });
413        }
414        let ready = manifest.ready.unwrap_or(true);
415        let registration = ModuleRegistration {
416            manifest,
417            ready,
418            negotiated_ver,
419            state: ChannelState::Active,
420            connection_id,
421            control_ops,
422        };
423        inner.candidates.insert(module_id, registration.clone());
424        if nonce_verified {
425            inner.nonce_verified.insert(connection_id);
426        } else {
427            inner.nonce_verified.remove(&connection_id);
428        }
429        if !publish {
430            inner.unpublished.insert(connection_id);
431        }
432        inner.notify_module_changed(&registration.manifest.module_id);
433        Ok(registration)
434    }
435
436    /// Publish the registration `connection_id` holds, in whichever slot.
437    ///
438    /// For an active registration this is the moment `catalog.list` starts
439    /// listing the module, and the catalog generation advances under the same
440    /// lock, so no reader can see the new generation without the module or the
441    /// module without the new generation. A candidate is not listed either way;
442    /// publishing it only makes it visible to
443    /// [`Self::published_registration`].
444    ///
445    /// Returns `false` when there is nothing to publish: the connection holds
446    /// no registration any more, or it was already published.
447    pub fn publish_registration(&self, connection_id: ConnectionId) -> Result<bool, RegistryError> {
448        let mut inner = self.lock_inner()?;
449        Ok(inner.publish_registration(connection_id))
450    }
451
452    /// Install forwarding and publish without letting a registry reader observe
453    /// the interval after HELLO_ACK is queued but before publication. The install
454    /// callback may take forwarding's lock, but must not re-enter the registry:
455    /// the lock order is Registry -> ForwardingTable::inner.
456    ///
457    /// An install error leaves the registration unpublished. The caller must
458    /// roll it back after this method releases the registry lock. The outer
459    /// result reports registry locking errors; the inner result reports install
460    /// errors or whether the registration was published.
461    pub(crate) fn publish_registration_after<E>(
462        &self,
463        connection_id: ConnectionId,
464        install: impl FnOnce() -> Result<(), E>,
465    ) -> Result<Result<bool, E>, RegistryError> {
466        let mut inner = self.lock_inner()?;
467        if let Err(err) = install() {
468            return Ok(Err(err));
469        }
470        Ok(Ok(inner.publish_registration(connection_id)))
471    }
472
473    #[cfg(test)]
474    pub(crate) fn observe_next_lock_attempt(&self) -> std::sync::mpsc::Receiver<bool> {
475        let (sender, receiver) = std::sync::mpsc::channel();
476        *self.next_lock_attempt.lock().unwrap() = Some(sender);
477        receiver
478    }
479
480    /// Move the candidate for `module_id` into the active slot and demote the
481    /// previous active registration, in one registry critical section.
482    ///
483    /// Returns `Ok(None)` when there is no candidate to promote. Bumps the
484    /// catalog generation, because the listed registration for the id changed.
485    pub fn promote_candidate(
486        &self,
487        module_id: &str,
488    ) -> Result<Option<RegistryCutover>, RegistryError> {
489        let mut inner = self.lock_inner()?;
490        let Some(promoted) = inner.candidates.remove(module_id) else {
491            return Ok(None);
492        };
493        let superseded = inner
494            .modules
495            .insert(module_id.to_string(), promoted.clone());
496        if let Some(superseded) = superseded.clone() {
497            let replaced_connection_id = superseded.connection_id.get();
498            inner
499                .superseded_by
500                .insert(superseded.connection_id, promoted.connection_id);
501            inner.superseded.push(superseded);
502            info!(
503                target: "subc.registry",
504                module_id = %module_id,
505                connection_id = promoted.connection_id.get(),
506                replaced = true,
507                replaced_connection_id,
508                "module registration promoted"
509            );
510        }
511        inner.bump_generation();
512        inner.notify_module_changed(module_id);
513        Ok(Some(RegistryCutover {
514            promoted,
515            superseded,
516        }))
517    }
518
519    /// The ACTIVE registration for `module_id`. Candidates and superseded
520    /// incumbents are never returned: this is the lookup routing decisions use.
521    pub fn get_module(&self, module_id: &str) -> Result<Option<ModuleRegistration>, RegistryError> {
522        Ok(self.lock_inner()?.modules.get(module_id).cloned())
523    }
524
525    /// Unlike the published-only catalog view, admission sees staged active
526    /// registrations too, exactly as `get_module` does. A target whose
527    /// registration is accepted but not yet published in the catalog must
528    /// answer `target_unavailable`, not `unknown_module`, on an ordinary open.
529    pub(crate) fn route_admission_snapshot(&self) -> Result<RouteAdmissionSnapshot, RegistryError> {
530        let inner = self.lock_inner()?;
531        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
532        modules.sort_by(|a, b| a.manifest.module_id.cmp(&b.manifest.module_id));
533        Ok(RouteAdmissionSnapshot {
534            modules,
535            unpublished: inner.unpublished.clone(),
536        })
537    }
538
539    /// The swap candidate registered for `module_id`, if any.
540    pub fn get_candidate(
541        &self,
542        module_id: &str,
543    ) -> Result<Option<ModuleRegistration>, RegistryError> {
544        Ok(self.lock_inner()?.candidates.get(module_id).cloned())
545    }
546
547    /// The registration held in one specific slot. See [`RegistrationSlot`].
548    pub fn registration(
549        &self,
550        slot: RegistrationSlot<'_>,
551    ) -> Result<Option<ModuleRegistration>, RegistryError> {
552        let inner = self.lock_inner()?;
553        Ok(match slot {
554            RegistrationSlot::Active(module_id) => inner.modules.get(module_id).cloned(),
555            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id).cloned(),
556            RegistrationSlot::Connection(connection_id) => inner
557                .find_by_connection(connection_id)
558                .map(|(_, registration)| registration.clone()),
559        })
560    }
561
562    pub fn active_registration_count(&self) -> Result<usize, RegistryError> {
563        Ok(self.lock_inner()?.modules.len())
564    }
565
566    /// The catalog generation and the active registrations `catalog.list`
567    /// shows. Unpublished registrations (see
568    /// [`Self::register_unpublished_with_control_ops`]) are left out.
569    pub fn list_modules(&self) -> Result<(u64, Vec<ModuleRegistration>), RegistryError> {
570        let inner = self.lock_inner()?;
571        let mut modules = inner
572            .modules
573            .values()
574            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
575            .cloned()
576            .collect::<Vec<_>>();
577        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
578        Ok((inner.generation, modules))
579    }
580
581    /// List published active registrations together with their HELLO nonce-verification status.
582    /// Both values are captured under the registry lock so a concurrent swap or
583    /// disconnect cannot separate a registration from its verification fact.
584    pub fn list_modules_with_nonce_verification(
585        &self,
586    ) -> Result<(u64, Vec<(ModuleRegistration, bool)>), RegistryError> {
587        let inner = self.lock_inner()?;
588        let mut registrations = inner
589            .modules
590            .values()
591            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
592            .collect::<Vec<_>>();
593        registrations.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
594        let modules = registrations
595            .into_iter()
596            .map(|registration| {
597                (
598                    registration.clone(),
599                    inner.nonce_verified.contains(&registration.connection_id),
600                )
601            })
602            .collect();
603        Ok((inner.generation, modules))
604    }
605
606    /// Every active registration, including unpublished ones.
607    ///
608    /// For the capability evaluator and the capability deny census, which
609    /// count a module as soon as it has registered. Whether `catalog.list`
610    /// shows the module yet does not change their verdicts.
611    pub fn list_registered_modules(&self) -> Result<Vec<ModuleRegistration>, RegistryError> {
612        let inner = self.lock_inner()?;
613        let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
614        modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
615        Ok(modules)
616    }
617
618    /// Like [`Self::registration`], but a registration that is not published
619    /// yet is reported as absent.
620    pub fn published_registration(
621        &self,
622        slot: RegistrationSlot<'_>,
623    ) -> Result<Option<ModuleRegistration>, RegistryError> {
624        let inner = self.lock_inner()?;
625        let registration = match slot {
626            RegistrationSlot::Active(module_id) => inner.modules.get(module_id),
627            RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id),
628            RegistrationSlot::Connection(connection_id) => inner
629                .find_by_connection(connection_id)
630                .map(|(_, registration)| registration),
631        };
632        Ok(registration
633            .filter(|registration| !inner.unpublished.contains(&registration.connection_id))
634            .cloned())
635    }
636
637    pub fn generation(&self) -> Result<u64, RegistryError> {
638        Ok(self.lock_inner()?.generation)
639    }
640
641    #[cfg(test)]
642    pub(crate) fn set_module_state_for_test(
643        &self,
644        module_id: &str,
645        state: ChannelState,
646    ) -> Result<bool, RegistryError> {
647        let mut inner = self.lock_inner()?;
648        let Some(registration) = inner.modules.get_mut(module_id) else {
649            return Ok(false);
650        };
651        registration.state = state;
652        inner.notify_module_changed(module_id);
653        Ok(true)
654    }
655
656    /// The registration owned by `connection_id`, searching the active,
657    /// candidate and superseded slots in that order.
658    pub fn get_module_by_connection(
659        &self,
660        connection_id: ConnectionId,
661    ) -> Result<Option<ModuleRegistration>, RegistryError> {
662        Ok(self
663            .lock_inner()?
664            .find_by_connection(connection_id)
665            .map(|(_, registration)| registration.clone()))
666    }
667
668    /// Replace only the validated role declarations owned by this connection.
669    pub fn replace_role_declarations_for_connection(
670        &self,
671        connection_id: ConnectionId,
672        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
673    ) -> Result<Option<ModuleRegistration>, RegistryError> {
674        let mut inner = self.lock_inner()?;
675        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
676            return Ok(None);
677        };
678        let registration = inner
679            .registration_mut(slot, connection_id)
680            .expect("registration discovered under the same registry lock must still exist");
681        registration.manifest.role_declarations = role_declarations;
682        let updated = registration.clone();
683        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
684            inner.bump_generation();
685        }
686        inner.notify_module_changed(&updated.manifest.module_id);
687        Ok(Some(updated))
688    }
689
690    /// Replace the provider role list and, when supplied, the attested capability
691    /// declaration for the module owned by `connection_id`.
692    ///
693    /// Searches every slot: a swap candidate declares itself ready through this
694    /// call, and if only the active slot were searched its update would find
695    /// nothing and the candidate would never become ready. Only a change to the
696    /// active slot bumps the catalog generation, because only the active slot is
697    /// listed, and only once that registration is published.
698    pub fn replace_catalog_for_connection(
699        &self,
700        connection_id: ConnectionId,
701        provides: Vec<ProviderRole>,
702        capabilities: Option<CapabilityDeclarations>,
703        ready: Option<bool>,
704    ) -> Result<Option<ModuleRegistration>, RegistryError> {
705        let mut inner = self.lock_inner()?;
706        let Some((slot, _)) = inner.find_by_connection(connection_id) else {
707            return Ok(None);
708        };
709        let registration = inner
710            .registration_mut(slot, connection_id)
711            .expect("registration discovered under the same registry lock must still exist");
712        if let Some(capabilities) = capabilities.as_ref() {
713            let declares_federated = |caps: Option<&CapabilityDeclarations>| {
714                caps.is_some_and(|caps| {
715                    caps.provides
716                        .iter()
717                        .any(|cap| cap == subc_protocol::scope::SCOPE_FEDERATED_CAPABILITY)
718                })
719            };
720            // Pending binds rely on this declaration while the target module's outbound queue is full.
721            if declares_federated(registration.manifest.capabilities.as_ref())
722                != declares_federated(Some(capabilities))
723            {
724                return Err(RegistryError::FederatedCapabilityChanged);
725            }
726            // Pending binds also decide from this declaration whether to
727            // carry `caller`, so routes bound before and after an update
728            // could otherwise attest differently.
729            let declares_caller = |caps: Option<&CapabilityDeclarations>| {
730                caps.is_some_and(|caps| {
731                    caps.provides
732                        .iter()
733                        .any(|cap| cap == subc_protocol::peer::CALLER_ATTESTATION_CAPABILITY)
734                })
735            };
736            if declares_caller(registration.manifest.capabilities.as_ref())
737                != declares_caller(Some(capabilities))
738            {
739                return Err(RegistryError::CallerAttestationCapabilityChanged);
740            }
741        }
742        registration.manifest.provides = provides;
743        if let Some(capabilities) = capabilities {
744            registration.manifest.capabilities = Some(capabilities);
745        }
746        if let Some(ready) = ready {
747            registration.ready = ready;
748            registration.manifest.ready = Some(ready);
749        }
750        let updated = registration.clone();
751        if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
752            inner.bump_generation();
753        }
754        inner.notify_module_changed(&updated.manifest.module_id);
755        Ok(Some(updated))
756    }
757
758    /// Deregister every module owned by a dropped connection, in any slot.
759    pub fn deregister_connection(
760        &self,
761        connection_id: ConnectionId,
762    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
763        self.deregister_connection_with_reason(
764            connection_id,
765            RegistrationEndReason::ConnectionClosed,
766        )
767    }
768
769    pub(crate) fn deregister_connection_with_reason(
770        &self,
771        connection_id: ConnectionId,
772        reason: RegistrationEndReason,
773    ) -> Result<Vec<ModuleRegistration>, RegistryError> {
774        let mut inner = self.lock_inner()?;
775        // A registration that was never published was never listed, so
776        // removing it leaves the catalog, and its generation, as they were.
777        let was_published = !inner.unpublished.remove(&connection_id);
778        let module_ids: Vec<String> = inner
779            .modules
780            .iter()
781            .filter(|(_, registration)| registration.connection_id == connection_id)
782            .map(|(module_id, _)| module_id.clone())
783            .collect();
784
785        let mut closed: Vec<ModuleRegistration> = module_ids
786            .into_iter()
787            .filter_map(|module_id| inner.close_module(&module_id, was_published))
788            .collect();
789
790        let candidate_ids: Vec<String> = inner
791            .candidates
792            .iter()
793            .filter(|(_, registration)| registration.connection_id == connection_id)
794            .map(|(module_id, _)| module_id.clone())
795            .collect();
796        for module_id in candidate_ids {
797            if let Some(mut registration) = inner.candidates.remove(&module_id) {
798                registration.state = ChannelState::Closed;
799                closed.push(registration);
800            }
801        }
802
803        let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut inner.superseded)
804            .into_iter()
805            .partition(|registration| registration.connection_id == connection_id);
806        let superseded_connections: std::collections::HashSet<_> = removed
807            .iter()
808            .map(|registration| registration.connection_id)
809            .collect();
810        inner.superseded = kept;
811        closed.extend(removed.into_iter().map(|mut registration| {
812            registration.state = ChannelState::Closed;
813            registration
814        }));
815        for registration in &closed {
816            inner.nonce_verified.remove(&registration.connection_id);
817            inner.notify_module_changed(&registration.manifest.module_id);
818            let replaced = superseded_connections.contains(&registration.connection_id);
819            let end_reason = if replaced {
820                RegistrationEndReason::Replaced
821            } else {
822                reason
823            };
824            let replaced_by_connection_id = if replaced {
825                inner
826                    .superseded_by
827                    .remove(&registration.connection_id)
828                    .map(ConnectionId::get)
829            } else {
830                None
831            };
832            if let Some(replaced_by_connection_id) = replaced_by_connection_id {
833                info!(
834                    target: "subc.registry",
835                    module_id = %registration.manifest.module_id,
836                    connection_id = registration.connection_id.get(),
837                    reason = %end_reason.as_str(),
838                    replaced_by_connection_id,
839                    "module registration ended"
840                );
841                continue;
842            }
843            info!(
844                target: "subc.registry",
845                module_id = %registration.manifest.module_id,
846                connection_id = registration.connection_id.get(),
847                reason = %end_reason.as_str(),
848                "module registration ended"
849            );
850        }
851        Ok(closed)
852    }
853
854    fn lock_inner(&self) -> Result<MutexGuard<'_, RegistryInner>, RegistryError> {
855        #[cfg(test)]
856        {
857            let observer = self.next_lock_attempt.lock().unwrap().take();
858            if let Some(observer) = observer {
859                // Tell a held-publication test whether its reader acquired the
860                // lock or must wait. This lets it release publication only after
861                // the reader actually attempts the lookup, without a timer.
862                match self.inner.try_lock() {
863                    Ok(inner) => {
864                        observer.send(true).unwrap();
865                        return Ok(inner);
866                    }
867                    Err(std::sync::TryLockError::WouldBlock) => observer.send(false).unwrap(),
868                    Err(std::sync::TryLockError::Poisoned(_)) => {
869                        return Err(RegistryError::Poisoned);
870                    }
871                }
872            }
873        }
874        self.inner.lock().map_err(|_| RegistryError::Poisoned)
875    }
876}
877
878/// Which internal slot a connection-keyed lookup found its registration in.
879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
880enum SlotKind {
881    Active,
882    Candidate,
883    Superseded,
884}
885
886impl RegistryInner {
887    fn publish_registration(&mut self, connection_id: ConnectionId) -> bool {
888        if !self.unpublished.remove(&connection_id) {
889            return false;
890        }
891        let Some((slot, registration)) = self.find_by_connection(connection_id) else {
892            return false;
893        };
894        let module_id = registration.manifest.module_id.clone();
895        if matches!(slot, SlotKind::Active) {
896            self.bump_generation();
897        }
898        self.notify_module_changed(&module_id);
899        true
900    }
901
902    fn notify_module_changed(&self, module_id: &str) {
903        if let Some(sender) = self.module_changes.get(module_id) {
904            sender.send_modify(|_| {});
905        }
906    }
907
908    fn find_by_connection(
909        &self,
910        connection_id: ConnectionId,
911    ) -> Option<(SlotKind, &ModuleRegistration)> {
912        let owned_by =
913            |registration: &&ModuleRegistration| registration.connection_id == connection_id;
914        self.modules
915            .values()
916            .find(owned_by)
917            .map(|registration| (SlotKind::Active, registration))
918            .or_else(|| {
919                self.candidates
920                    .values()
921                    .find(owned_by)
922                    .map(|registration| (SlotKind::Candidate, registration))
923            })
924            .or_else(|| {
925                self.superseded
926                    .iter()
927                    .find(owned_by)
928                    .map(|registration| (SlotKind::Superseded, registration))
929            })
930    }
931
932    fn registration_mut(
933        &mut self,
934        slot: SlotKind,
935        connection_id: ConnectionId,
936    ) -> Option<&mut ModuleRegistration> {
937        let owned_by =
938            |registration: &&mut ModuleRegistration| registration.connection_id == connection_id;
939        match slot {
940            SlotKind::Active => self.modules.values_mut().find(owned_by),
941            SlotKind::Candidate => self.candidates.values_mut().find(owned_by),
942            SlotKind::Superseded => self.superseded.iter_mut().find(owned_by),
943        }
944    }
945
946    fn close_module(&mut self, module_id: &str, listed: bool) -> Option<ModuleRegistration> {
947        let mut registration = self.modules.remove(module_id)?;
948        registration.state = ChannelState::Closed;
949        if listed {
950            self.bump_generation();
951        }
952        Some(registration)
953    }
954
955    fn bump_generation(&mut self) {
956        self.generation = self.generation.wrapping_add(1);
957        if let Some(sender) = &self.catalog_changes {
958            sender.send_replace(self.generation);
959        }
960    }
961}
962
963#[derive(Debug, Clone, PartialEq, Eq)]
964pub enum RegistryError {
965    FederatedCapabilityChanged,
966    /// A `catalog.update` tried to add or drop `caller-attestation/v1`, which
967    /// decides whether binds carry `caller` and so is fixed at HELLO.
968    CallerAttestationCapabilityChanged,
969    DuplicateModuleId {
970        module_id: String,
971    },
972    /// The id is unusable as a single path component. Enforced at
973    /// registration because the daemon MINTS A STORAGE DESCRIPTOR from the
974    /// self-claimed id verbatim (`<data_home>/cortexkit/<module_id>/store.db`),
975    /// so an id carrying separators or dot components is a path-traversal or
976    /// store-collision primitive handed to whoever claims it (issue #32). The
977    /// derivations deliberately do NOT sanitize instead: sanitizing here would
978    /// silently re-path every deployed store and desynchronize the Rust and TS
979    /// derivations, while refusal changes nothing for any id that ever worked.
980    PathHazardModuleId {
981        module_id: String,
982        reason: String,
983    },
984    Poisoned,
985}
986
987impl fmt::Display for RegistryError {
988    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989        match self {
990            Self::FederatedCapabilityChanged => write!(
991                f,
992                "scope-federated/v1 is fixed at HELLO; restart the module to change it"
993            ),
994            Self::CallerAttestationCapabilityChanged => write!(
995                f,
996                "caller-attestation/v1 is fixed at HELLO; restart the module to change it"
997            ),
998            Self::DuplicateModuleId { module_id } => {
999                write!(f, "module_id '{module_id}' is already registered")
1000            }
1001            Self::PathHazardModuleId { module_id, reason } => {
1002                write!(
1003                    f,
1004                    "module_id '{}' is not usable as a path component: {reason}",
1005                    module_id.escape_debug()
1006                )
1007            }
1008            Self::Poisoned => write!(f, "registry lock was poisoned"),
1009        }
1010    }
1011}
1012
1013impl Error for RegistryError {}
1014
1015/// Why `module_id` cannot serve as a single path component, or `Ok(())`.
1016///
1017/// This is a REFUSAL predicate, not a sanitizer: every currently-working fleet
1018/// id passes untouched, and anything refused here never worked meaningfully --
1019/// it either escaped `<data_home>/cortexkit/` (separators, dot components) or
1020/// aliased another module's store (`a/b` vs `a//b` collapsing on POSIX).
1021/// Colons are allowed: reserved-namespace children (`mcp:...`) register today
1022/// and a colon cannot traverse. Windows path legality is the store library's
1023/// concern, not an identity rule.
1024pub fn module_id_path_hazard(module_id: &str) -> Result<(), String> {
1025    subc_protocol::module_id::module_id_path_hazard(module_id)
1026}
1027
1028#[cfg(test)]
1029mod change_notification_tests {
1030    use super::*;
1031
1032    fn manifest() -> ModuleManifest {
1033        ModuleManifest::builder("watched", "1.0.0")
1034            .protocol_ver(1)
1035            .build()
1036    }
1037
1038    fn changed(receiver: &mut watch::Receiver<u64>) {
1039        assert!(
1040            receiver.has_changed().unwrap(),
1041            "registry write must notify"
1042        );
1043        receiver.borrow_and_update();
1044    }
1045
1046    #[test]
1047    fn every_registration_write_notifies_only_its_module() {
1048        let registry = Registry::default();
1049        let mut events = registry.subscribe_module_changes("watched").unwrap();
1050        let other = registry.subscribe_module_changes("other").unwrap();
1051        let active = ConnectionId::new(1);
1052        let candidate = ConnectionId::new(2);
1053        registry
1054            .register_with_control_ops(manifest(), 1, active, vec![])
1055            .unwrap();
1056        changed(&mut events);
1057        registry
1058            .set_module_state_for_test("watched", ChannelState::Active)
1059            .unwrap();
1060        changed(&mut events);
1061        registry
1062            .replace_catalog_for_connection(active, vec![], None, Some(true))
1063            .unwrap();
1064        changed(&mut events);
1065        registry
1066            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1067            .unwrap();
1068        changed(&mut events);
1069        registry
1070            .replace_catalog_for_connection(candidate, vec![], None, Some(true))
1071            .unwrap();
1072        changed(&mut events);
1073        registry.promote_candidate("watched").unwrap().unwrap();
1074        changed(&mut events);
1075        // Superseded connections can still update and deregister their slot.
1076        registry
1077            .replace_catalog_for_connection(active, vec![], None, Some(false))
1078            .unwrap();
1079        changed(&mut events);
1080        registry.deregister_connection(active).unwrap();
1081        changed(&mut events);
1082        registry.deregister_connection(candidate).unwrap();
1083        changed(&mut events);
1084        registry
1085            .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1086            .unwrap();
1087        changed(&mut events);
1088        registry.deregister_connection(candidate).unwrap();
1089        changed(&mut events);
1090        assert!(
1091            !other.has_changed().unwrap(),
1092            "other module must stay parked"
1093        );
1094    }
1095
1096    #[test]
1097    fn subscription_before_read_keeps_a_change_until_waited_on() {
1098        let registry = Registry::default();
1099        let mut events = registry.subscribe_module_changes("watched").unwrap();
1100        assert!(registry.get_module("watched").unwrap().is_none());
1101        registry
1102            .register_with_control_ops(manifest(), 1, ConnectionId::new(1), vec![])
1103            .unwrap();
1104        // Neither a later lookup nor a coalesced catalog update consumes it.
1105        registry.get_module("watched").unwrap().unwrap();
1106        registry
1107            .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
1108            .unwrap();
1109        changed(&mut events);
1110        assert!(!events.has_changed().unwrap());
1111    }
1112}
1113
1114#[cfg(test)]
1115mod publication_tests {
1116    use super::*;
1117
1118    fn manifest() -> ModuleManifest {
1119        ModuleManifest::builder("m", "1.0.0")
1120            .protocol_ver(1)
1121            .build()
1122    }
1123
1124    /// An unpublished registration holds its id and answers routing lookups,
1125    /// but `list_modules` leaves it out and the generation stays put until
1126    /// it is published; publishing lists it and bumps the generation once.
1127    #[test]
1128    fn unpublished_registration_is_unlisted_until_published() {
1129        let registry = Registry::default();
1130        let connection = ConnectionId::new(1);
1131        registry
1132            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1133            .unwrap();
1134        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1135        assert!(registry.get_module("m").unwrap().is_some());
1136        assert_eq!(registry.list_registered_modules().unwrap().len(), 1);
1137        assert!(registry
1138            .published_registration(RegistrationSlot::Active("m"))
1139            .unwrap()
1140            .is_none());
1141        assert!(matches!(
1142            registry.register_with_control_ops(manifest(), 1, ConnectionId::new(2), vec![]),
1143            Err(RegistryError::DuplicateModuleId { .. })
1144        ));
1145        // A catalog update before publication does not move the generation.
1146        registry
1147            .replace_catalog_for_connection(connection, vec![], None, Some(true))
1148            .unwrap();
1149        assert_eq!(registry.generation().unwrap(), 0);
1150
1151        assert!(registry.publish_registration(connection).unwrap());
1152        let (generation, listed) = registry.list_modules().unwrap();
1153        assert_eq!(generation, 1);
1154        assert_eq!(listed.len(), 1);
1155        assert!(!registry.publish_registration(connection).unwrap());
1156        assert_eq!(registry.generation().unwrap(), 1);
1157    }
1158
1159    /// Removing a registration that was never published leaves no catalog
1160    /// trace: the generation does not move, and a later publish is a no-op.
1161    #[test]
1162    fn deregistering_an_unpublished_registration_leaves_the_generation() {
1163        let registry = Registry::default();
1164        let connection = ConnectionId::new(1);
1165        registry
1166            .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1167            .unwrap();
1168        assert_eq!(registry.deregister_connection(connection).unwrap().len(), 1);
1169        assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1170        assert!(!registry.publish_registration(connection).unwrap());
1171        assert_eq!(registry.generation().unwrap(), 0);
1172    }
1173
1174    /// An unpublished candidate holds the candidate slot but
1175    /// `published_registration` does not return it until it is published.
1176    /// Publishing a candidate does not bump the generation: candidates are
1177    /// never listed.
1178    #[test]
1179    fn unpublished_candidate_is_hidden_from_published_lookups() {
1180        let registry = Registry::default();
1181        let candidate = ConnectionId::new(2);
1182        registry
1183            .register_unpublished_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1184            .unwrap();
1185        assert!(registry
1186            .registration(RegistrationSlot::Candidate("m"))
1187            .unwrap()
1188            .is_some());
1189        assert!(registry
1190            .published_registration(RegistrationSlot::Candidate("m"))
1191            .unwrap()
1192            .is_none());
1193        assert!(registry
1194            .published_registration(RegistrationSlot::Connection(candidate))
1195            .unwrap()
1196            .is_none());
1197        assert!(registry.publish_registration(candidate).unwrap());
1198        assert!(registry
1199            .published_registration(RegistrationSlot::Candidate("m"))
1200            .unwrap()
1201            .is_some());
1202        assert_eq!(registry.generation().unwrap(), 0);
1203    }
1204}
1205
1206#[cfg(test)]
1207mod path_hazard_tests {
1208    use super::*;
1209    use crate::ConnectionId;
1210    use subc_protocol::manifest::ModuleManifest;
1211
1212    fn manifest(module_id: &str) -> ModuleManifest {
1213        ModuleManifest::builder(module_id, "0.1.0")
1214            .protocol_ver(1)
1215            .build()
1216    }
1217
1218    #[test]
1219    fn path_hazard_ids_are_refused_and_nothing_registers() {
1220        let registry = Registry::default();
1221        for (bad, reason_fragment) in [
1222            ("../escape", "path separator"),
1223            ("a/b", "path separator"),
1224            ("a\\b", "path separator"),
1225            ("..", "dot path component"),
1226            (".", "dot path component"),
1227            ("", "empty"),
1228            ("evil\u{0}id", "control character"),
1229        ] {
1230            let err = registry
1231                .register_with_control_ops(manifest(bad), 1, ConnectionId::new(7), Vec::new())
1232                .expect_err("path-hazard id must refuse");
1233            // Reason asserted so a predicate throwing the WRONG refusal fails.
1234            assert!(
1235                err.to_string().contains(reason_fragment),
1236                "id {bad:?}: expected {reason_fragment:?} in {err}"
1237            );
1238        }
1239        // THE EFFECT, not just the verdicts: no refusal left a registration
1240        // behind, and the generation never moved.
1241        assert_eq!(registry.active_registration_count().unwrap(), 0);
1242        assert_eq!(registry.generation().unwrap(), 0);
1243    }
1244
1245    #[test]
1246    fn module_id_path_component_length_matches_shared_refusal_vectors() {
1247        let doc: serde_json::Value = serde_json::from_str(include_str!(
1248            "../tests/golden/module_id_path_component_refusals.json"
1249        ))
1250        .expect("refusal fixture parses");
1251
1252        for case in doc["vectors"].as_array().expect("vectors array") {
1253            let name = case["name"].as_str().expect("name");
1254            let module_id = case["module_id"]["unit"]
1255                .as_str()
1256                .expect("module_id unit")
1257                .repeat(
1258                    case["module_id"]["repeat"]
1259                        .as_u64()
1260                        .expect("module_id repeat") as usize,
1261                );
1262            assert_eq!(
1263                module_id.len(),
1264                case["utf8_bytes"].as_u64().expect("utf8 bytes") as usize
1265            );
1266
1267            let expected = case["expect_reason"].as_str().map(str::to_owned);
1268            assert_eq!(
1269                module_id_path_hazard(&module_id).err(),
1270                expected,
1271                "shared refusal vector {name:?} diverged"
1272            );
1273        }
1274    }
1275
1276    #[test]
1277    fn working_id_shapes_register_including_namespace_colons() {
1278        let registry = Registry::default();
1279        for (i, good) in ["magic-context", "mcp:everything", "v1.2-module"]
1280            .iter()
1281            .enumerate()
1282        {
1283            registry
1284                .register_with_control_ops(
1285                    manifest(good),
1286                    1,
1287                    ConnectionId::new(10 + i as u64),
1288                    Vec::new(),
1289                )
1290                .unwrap_or_else(|err| panic!("id {good:?} must register: {err}"));
1291        }
1292        assert_eq!(registry.active_registration_count().unwrap(), 3);
1293    }
1294}
1295
1296#[cfg(test)]
1297mod swap_slot_tests {
1298    use super::*;
1299
1300    fn manifest(module_id: &str, ready: Option<bool>) -> ModuleManifest {
1301        let mut manifest = ModuleManifest::builder(module_id, "0.1.0").build();
1302        manifest.ready = ready;
1303        manifest
1304    }
1305
1306    const INCUMBENT: ConnectionId = ConnectionId(1);
1307    const CANDIDATE: ConnectionId = ConnectionId(2);
1308
1309    fn registry_with_candidate() -> Registry {
1310        let registry = Registry::default();
1311        registry
1312            .register_with_control_ops(manifest("m", None), 1, INCUMBENT, Vec::new())
1313            .unwrap();
1314        registry
1315            .register_candidate_with_control_ops(
1316                manifest("m", Some(false)),
1317                1,
1318                CANDIDATE,
1319                Vec::new(),
1320            )
1321            .unwrap();
1322        registry
1323    }
1324
1325    #[test]
1326    fn candidate_is_invisible_to_by_id_lookups_and_listing() {
1327        let registry = registry_with_candidate();
1328        let generation = registry.generation().unwrap();
1329        assert_eq!(
1330            registry.get_module("m").unwrap().unwrap().connection_id,
1331            INCUMBENT
1332        );
1333        let (listed_generation, listed) = registry.list_modules().unwrap();
1334        assert_eq!(listed.len(), 1);
1335        assert_eq!(listed[0].connection_id, INCUMBENT);
1336        assert_eq!(listed_generation, generation);
1337        assert_eq!(registry.active_registration_count().unwrap(), 1);
1338        assert_eq!(
1339            registry.get_candidate("m").unwrap().unwrap().connection_id,
1340            CANDIDATE
1341        );
1342        assert_eq!(
1343            registry
1344                .register_candidate_with_control_ops(
1345                    manifest("m", None),
1346                    1,
1347                    ConnectionId(3),
1348                    Vec::new()
1349                )
1350                .unwrap_err(),
1351            RegistryError::DuplicateModuleId {
1352                module_id: "m".to_string()
1353            }
1354        );
1355    }
1356
1357    #[test]
1358    fn promoted_candidate_keeps_its_verified_nonce_fact() {
1359        let registry = Registry::default();
1360        registry
1361            .register_unpublished_verified_candidate_with_control_ops(
1362                manifest("m", Some(true)),
1363                1,
1364                CANDIDATE,
1365                Vec::new(),
1366            )
1367            .unwrap();
1368        assert!(registry.publish_registration(CANDIDATE).unwrap());
1369        assert!(registry
1370            .list_modules_with_nonce_verification()
1371            .unwrap()
1372            .1
1373            .is_empty());
1374
1375        registry.promote_candidate("m").unwrap().unwrap();
1376        let (_, modules) = registry.list_modules_with_nonce_verification().unwrap();
1377        assert_eq!(modules.len(), 1);
1378        assert!(modules[0].1);
1379    }
1380
1381    /// Without the candidate slot in the connection-keyed search, this update
1382    /// returns `Ok(None)` and the candidate never becomes ready.
1383    #[test]
1384    fn candidate_catalog_update_reaches_the_candidate_registration() {
1385        let registry = registry_with_candidate();
1386        assert!(!registry.get_candidate("m").unwrap().unwrap().ready);
1387
1388        let updated = registry
1389            .replace_catalog_for_connection(CANDIDATE, Vec::new(), None, Some(true))
1390            .unwrap()
1391            .expect("the candidate's own connection finds its registration");
1392
1393        assert_eq!(updated.connection_id, CANDIDATE);
1394        assert!(registry.get_candidate("m").unwrap().unwrap().ready);
1395        assert_eq!(
1396            registry.get_module_by_connection(CANDIDATE).unwrap(),
1397            Some(updated)
1398        );
1399        assert_eq!(
1400            registry.get_module("m").unwrap().unwrap().connection_id,
1401            INCUMBENT,
1402            "a candidate's update must not touch the active registration"
1403        );
1404    }
1405
1406    #[test]
1407    fn promotion_swaps_slots_and_each_connection_still_deregisters_its_own() {
1408        let registry = registry_with_candidate();
1409        let before = registry.generation().unwrap();
1410        let cutover = registry.promote_candidate("m").unwrap().unwrap();
1411        assert_eq!(cutover.promoted.connection_id, CANDIDATE);
1412        assert_eq!(cutover.superseded.unwrap().connection_id, INCUMBENT);
1413        assert_ne!(registry.generation().unwrap(), before);
1414        assert_eq!(registry.promote_candidate("m").unwrap(), None);
1415
1416        assert_eq!(
1417            registry
1418                .registration(RegistrationSlot::Active("m"))
1419                .unwrap()
1420                .unwrap()
1421                .connection_id,
1422            CANDIDATE
1423        );
1424        assert!(registry
1425            .registration(RegistrationSlot::Candidate("m"))
1426            .unwrap()
1427            .is_none());
1428        assert!(registry
1429            .registration(RegistrationSlot::Connection(INCUMBENT))
1430            .unwrap()
1431            .is_some());
1432
1433        let closed = registry.deregister_connection(INCUMBENT).unwrap();
1434        assert_eq!(closed.len(), 1);
1435        assert_eq!(closed[0].connection_id, INCUMBENT);
1436        assert_eq!(closed[0].state, ChannelState::Closed);
1437        assert!(registry
1438            .registration(RegistrationSlot::Connection(INCUMBENT))
1439            .unwrap()
1440            .is_none());
1441        assert_eq!(
1442            registry.get_module("m").unwrap().unwrap().connection_id,
1443            CANDIDATE
1444        );
1445    }
1446
1447    #[test]
1448    fn a_dropped_candidate_deregisters_from_the_candidate_slot_only() {
1449        let registry = registry_with_candidate();
1450        let closed = registry.deregister_connection(CANDIDATE).unwrap();
1451        assert_eq!(closed.len(), 1);
1452        assert_eq!(closed[0].connection_id, CANDIDATE);
1453        assert!(registry.get_candidate("m").unwrap().is_none());
1454        assert_eq!(
1455            registry.get_module("m").unwrap().unwrap().connection_id,
1456            INCUMBENT
1457        );
1458    }
1459}