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