1use std::{
2 collections::{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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct ConnectionId(u64);
15
16impl ConnectionId {
17 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ChannelState {
34 Active,
35 Closed,
36}
37
38#[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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum RegistrationSlot<'a> {
83 Active(&'a str),
86 Candidate(&'a str),
88 Connection(ConnectionId),
90}
91
92#[derive(Debug, Clone, PartialEq)]
94pub struct RegistryCutover {
95 pub promoted: ModuleRegistration,
97 pub superseded: Option<ModuleRegistration>,
100}
101
102#[derive(Debug, Default)]
117pub struct Registry {
118 inner: Mutex<RegistryInner>,
119}
120
121#[derive(Debug, Default)]
122struct RegistryInner {
123 module_changes: HashMap<String, watch::Sender<()>>,
126 modules: HashMap<String, ModuleRegistration>,
127 candidates: HashMap<String, ModuleRegistration>,
129 superseded: Vec<ModuleRegistration>,
132 nonce_verified: HashSet<ConnectionId>,
137 superseded_by: HashMap<ConnectionId, ConnectionId>,
139 unpublished: HashSet<ConnectionId>,
153 generation: u64,
154}
155
156impl Registry {
157 pub(crate) fn subscribe_module_changes(
160 &self,
161 module_id: &str,
162 ) -> Result<watch::Receiver<()>, RegistryError> {
163 let mut inner = self.lock_inner()?;
164 inner
166 .module_changes
167 .retain(|_, sender| sender.receiver_count() > 0);
168 Ok(inner
169 .module_changes
170 .entry(module_id.to_string())
171 .or_insert_with(|| watch::channel(()).0)
172 .subscribe())
173 }
174
175 pub fn register_with_control_ops(
182 &self,
183 manifest: ModuleManifest,
184 negotiated_ver: u8,
185 connection_id: ConnectionId,
186 control_ops: Vec<String>,
187 ) -> Result<ModuleRegistration, RegistryError> {
188 self.register_active(
189 manifest,
190 negotiated_ver,
191 connection_id,
192 control_ops,
193 true,
194 false,
195 )
196 }
197
198 pub fn register_unpublished_with_control_ops(
207 &self,
208 manifest: ModuleManifest,
209 negotiated_ver: u8,
210 connection_id: ConnectionId,
211 control_ops: Vec<String>,
212 ) -> Result<ModuleRegistration, RegistryError> {
213 self.register_active(
214 manifest,
215 negotiated_ver,
216 connection_id,
217 control_ops,
218 false,
219 false,
220 )
221 }
222
223 pub(crate) fn register_unpublished_verified_with_control_ops(
225 &self,
226 manifest: ModuleManifest,
227 negotiated_ver: u8,
228 connection_id: ConnectionId,
229 control_ops: Vec<String>,
230 nonce_verified: bool,
231 ) -> Result<ModuleRegistration, RegistryError> {
232 self.register_active(
233 manifest,
234 negotiated_ver,
235 connection_id,
236 control_ops,
237 false,
238 nonce_verified,
239 )
240 }
241
242 fn register_active(
243 &self,
244 manifest: ModuleManifest,
245 negotiated_ver: u8,
246 connection_id: ConnectionId,
247 control_ops: Vec<String>,
248 publish: bool,
249 nonce_verified: bool,
250 ) -> Result<ModuleRegistration, RegistryError> {
251 let module_id = manifest.module_id.clone();
252 if let Err(reason) = module_id_path_hazard(&module_id) {
253 return Err(RegistryError::PathHazardModuleId { module_id, reason });
254 }
255 let mut inner = self.lock_inner()?;
256 if inner.modules.contains_key(&module_id) {
257 return Err(RegistryError::DuplicateModuleId { module_id });
258 }
259
260 let ready = manifest.ready.unwrap_or(true);
261 let registration = ModuleRegistration {
262 manifest,
263 ready,
264 negotiated_ver,
265 state: ChannelState::Active,
266 connection_id,
267 control_ops,
268 };
269
270 inner.modules.insert(module_id, registration.clone());
271 if nonce_verified {
272 inner.nonce_verified.insert(connection_id);
273 } else {
274 inner.nonce_verified.remove(&connection_id);
275 }
276 if publish {
277 inner.bump_generation();
278 } else {
279 inner.unpublished.insert(connection_id);
280 }
281 inner.notify_module_changed(®istration.manifest.module_id);
282 Ok(registration)
283 }
284
285 pub fn register_candidate_with_control_ops(
299 &self,
300 manifest: ModuleManifest,
301 negotiated_ver: u8,
302 connection_id: ConnectionId,
303 control_ops: Vec<String>,
304 ) -> Result<ModuleRegistration, RegistryError> {
305 self.register_candidate(
306 manifest,
307 negotiated_ver,
308 connection_id,
309 control_ops,
310 true,
311 false,
312 )
313 }
314
315 pub fn register_unpublished_candidate_with_control_ops(
322 &self,
323 manifest: ModuleManifest,
324 negotiated_ver: u8,
325 connection_id: ConnectionId,
326 control_ops: Vec<String>,
327 ) -> Result<ModuleRegistration, RegistryError> {
328 self.register_candidate(
329 manifest,
330 negotiated_ver,
331 connection_id,
332 control_ops,
333 false,
334 false,
335 )
336 }
337
338 pub(crate) fn register_unpublished_verified_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 false,
352 true,
353 )
354 }
355
356 fn register_candidate(
357 &self,
358 manifest: ModuleManifest,
359 negotiated_ver: u8,
360 connection_id: ConnectionId,
361 control_ops: Vec<String>,
362 publish: bool,
363 nonce_verified: bool,
364 ) -> Result<ModuleRegistration, RegistryError> {
365 let module_id = manifest.module_id.clone();
366 if let Err(reason) = module_id_path_hazard(&module_id) {
367 return Err(RegistryError::PathHazardModuleId { module_id, reason });
368 }
369 let mut inner = self.lock_inner()?;
370 if inner.candidates.contains_key(&module_id) {
371 return Err(RegistryError::DuplicateModuleId { module_id });
372 }
373 let ready = manifest.ready.unwrap_or(true);
374 let registration = ModuleRegistration {
375 manifest,
376 ready,
377 negotiated_ver,
378 state: ChannelState::Active,
379 connection_id,
380 control_ops,
381 };
382 inner.candidates.insert(module_id, registration.clone());
383 if nonce_verified {
384 inner.nonce_verified.insert(connection_id);
385 } else {
386 inner.nonce_verified.remove(&connection_id);
387 }
388 if !publish {
389 inner.unpublished.insert(connection_id);
390 }
391 inner.notify_module_changed(®istration.manifest.module_id);
392 Ok(registration)
393 }
394
395 pub fn publish_registration(&self, connection_id: ConnectionId) -> Result<bool, RegistryError> {
407 let mut inner = self.lock_inner()?;
408 if !inner.unpublished.remove(&connection_id) {
409 return Ok(false);
410 }
411 let Some((slot, registration)) = inner.find_by_connection(connection_id) else {
412 return Ok(false);
413 };
414 let module_id = registration.manifest.module_id.clone();
415 if matches!(slot, SlotKind::Active) {
416 inner.bump_generation();
417 }
418 inner.notify_module_changed(&module_id);
419 Ok(true)
420 }
421
422 pub fn promote_candidate(
428 &self,
429 module_id: &str,
430 ) -> Result<Option<RegistryCutover>, RegistryError> {
431 let mut inner = self.lock_inner()?;
432 let Some(promoted) = inner.candidates.remove(module_id) else {
433 return Ok(None);
434 };
435 let superseded = inner
436 .modules
437 .insert(module_id.to_string(), promoted.clone());
438 if let Some(superseded) = superseded.clone() {
439 let replaced_connection_id = superseded.connection_id.get();
440 inner
441 .superseded_by
442 .insert(superseded.connection_id, promoted.connection_id);
443 inner.superseded.push(superseded);
444 info!(
445 target: "subc.registry",
446 module_id = %module_id,
447 connection_id = promoted.connection_id.get(),
448 replaced = true,
449 replaced_connection_id,
450 "module registration promoted"
451 );
452 }
453 inner.bump_generation();
454 inner.notify_module_changed(module_id);
455 Ok(Some(RegistryCutover {
456 promoted,
457 superseded,
458 }))
459 }
460
461 pub fn get_module(&self, module_id: &str) -> Result<Option<ModuleRegistration>, RegistryError> {
464 Ok(self.lock_inner()?.modules.get(module_id).cloned())
465 }
466
467 pub fn get_candidate(
469 &self,
470 module_id: &str,
471 ) -> Result<Option<ModuleRegistration>, RegistryError> {
472 Ok(self.lock_inner()?.candidates.get(module_id).cloned())
473 }
474
475 pub fn registration(
477 &self,
478 slot: RegistrationSlot<'_>,
479 ) -> Result<Option<ModuleRegistration>, RegistryError> {
480 let inner = self.lock_inner()?;
481 Ok(match slot {
482 RegistrationSlot::Active(module_id) => inner.modules.get(module_id).cloned(),
483 RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id).cloned(),
484 RegistrationSlot::Connection(connection_id) => inner
485 .find_by_connection(connection_id)
486 .map(|(_, registration)| registration.clone()),
487 })
488 }
489
490 pub fn active_registration_count(&self) -> Result<usize, RegistryError> {
491 Ok(self.lock_inner()?.modules.len())
492 }
493
494 pub fn list_modules(&self) -> Result<(u64, Vec<ModuleRegistration>), RegistryError> {
498 let inner = self.lock_inner()?;
499 let mut modules = inner
500 .modules
501 .values()
502 .filter(|registration| !inner.unpublished.contains(®istration.connection_id))
503 .cloned()
504 .collect::<Vec<_>>();
505 modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
506 Ok((inner.generation, modules))
507 }
508
509 pub fn list_modules_with_nonce_verification(
513 &self,
514 ) -> Result<(u64, Vec<(ModuleRegistration, bool)>), RegistryError> {
515 let inner = self.lock_inner()?;
516 let mut registrations = inner
517 .modules
518 .values()
519 .filter(|registration| !inner.unpublished.contains(®istration.connection_id))
520 .collect::<Vec<_>>();
521 registrations.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
522 let modules = registrations
523 .into_iter()
524 .map(|registration| {
525 (
526 registration.clone(),
527 inner.nonce_verified.contains(®istration.connection_id),
528 )
529 })
530 .collect();
531 Ok((inner.generation, modules))
532 }
533
534 pub fn list_registered_modules(&self) -> Result<Vec<ModuleRegistration>, RegistryError> {
540 let inner = self.lock_inner()?;
541 let mut modules = inner.modules.values().cloned().collect::<Vec<_>>();
542 modules.sort_by(|left, right| left.manifest.module_id.cmp(&right.manifest.module_id));
543 Ok(modules)
544 }
545
546 pub fn published_registration(
549 &self,
550 slot: RegistrationSlot<'_>,
551 ) -> Result<Option<ModuleRegistration>, RegistryError> {
552 let inner = self.lock_inner()?;
553 let registration = match slot {
554 RegistrationSlot::Active(module_id) => inner.modules.get(module_id),
555 RegistrationSlot::Candidate(module_id) => inner.candidates.get(module_id),
556 RegistrationSlot::Connection(connection_id) => inner
557 .find_by_connection(connection_id)
558 .map(|(_, registration)| registration),
559 };
560 Ok(registration
561 .filter(|registration| !inner.unpublished.contains(®istration.connection_id))
562 .cloned())
563 }
564
565 pub fn generation(&self) -> Result<u64, RegistryError> {
566 Ok(self.lock_inner()?.generation)
567 }
568
569 #[cfg(test)]
570 pub(crate) fn set_module_state_for_test(
571 &self,
572 module_id: &str,
573 state: ChannelState,
574 ) -> Result<bool, RegistryError> {
575 let mut inner = self.lock_inner()?;
576 let Some(registration) = inner.modules.get_mut(module_id) else {
577 return Ok(false);
578 };
579 registration.state = state;
580 inner.notify_module_changed(module_id);
581 Ok(true)
582 }
583
584 pub fn get_module_by_connection(
587 &self,
588 connection_id: ConnectionId,
589 ) -> Result<Option<ModuleRegistration>, RegistryError> {
590 Ok(self
591 .lock_inner()?
592 .find_by_connection(connection_id)
593 .map(|(_, registration)| registration.clone()))
594 }
595
596 pub fn replace_catalog_for_connection(
605 &self,
606 connection_id: ConnectionId,
607 provides: Vec<ProviderRole>,
608 capabilities: Option<CapabilityDeclarations>,
609 ready: Option<bool>,
610 ) -> Result<Option<ModuleRegistration>, RegistryError> {
611 let mut inner = self.lock_inner()?;
612 let Some((slot, _)) = inner.find_by_connection(connection_id) else {
613 return Ok(None);
614 };
615 let registration = inner
616 .registration_mut(slot, connection_id)
617 .expect("registration discovered under the same registry lock must still exist");
618 registration.manifest.provides = provides;
619 if let Some(capabilities) = capabilities {
620 registration.manifest.capabilities = Some(capabilities);
621 }
622 if let Some(ready) = ready {
623 registration.ready = ready;
624 registration.manifest.ready = Some(ready);
625 }
626 let updated = registration.clone();
627 if matches!(slot, SlotKind::Active) && !inner.unpublished.contains(&connection_id) {
628 inner.bump_generation();
629 }
630 inner.notify_module_changed(&updated.manifest.module_id);
631 Ok(Some(updated))
632 }
633
634 pub fn deregister_connection(
636 &self,
637 connection_id: ConnectionId,
638 ) -> Result<Vec<ModuleRegistration>, RegistryError> {
639 self.deregister_connection_with_reason(
640 connection_id,
641 RegistrationEndReason::ConnectionClosed,
642 )
643 }
644
645 pub(crate) fn deregister_connection_with_reason(
646 &self,
647 connection_id: ConnectionId,
648 reason: RegistrationEndReason,
649 ) -> Result<Vec<ModuleRegistration>, RegistryError> {
650 let mut inner = self.lock_inner()?;
651 let was_published = !inner.unpublished.remove(&connection_id);
654 let module_ids: Vec<String> = inner
655 .modules
656 .iter()
657 .filter(|(_, registration)| registration.connection_id == connection_id)
658 .map(|(module_id, _)| module_id.clone())
659 .collect();
660
661 let mut closed: Vec<ModuleRegistration> = module_ids
662 .into_iter()
663 .filter_map(|module_id| inner.close_module(&module_id, was_published))
664 .collect();
665
666 let candidate_ids: Vec<String> = inner
667 .candidates
668 .iter()
669 .filter(|(_, registration)| registration.connection_id == connection_id)
670 .map(|(module_id, _)| module_id.clone())
671 .collect();
672 for module_id in candidate_ids {
673 if let Some(mut registration) = inner.candidates.remove(&module_id) {
674 registration.state = ChannelState::Closed;
675 closed.push(registration);
676 }
677 }
678
679 let (removed, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut inner.superseded)
680 .into_iter()
681 .partition(|registration| registration.connection_id == connection_id);
682 let superseded_connections: std::collections::HashSet<_> = removed
683 .iter()
684 .map(|registration| registration.connection_id)
685 .collect();
686 inner.superseded = kept;
687 closed.extend(removed.into_iter().map(|mut registration| {
688 registration.state = ChannelState::Closed;
689 registration
690 }));
691 for registration in &closed {
692 inner.nonce_verified.remove(®istration.connection_id);
693 inner.notify_module_changed(®istration.manifest.module_id);
694 let replaced = superseded_connections.contains(®istration.connection_id);
695 let end_reason = if replaced {
696 RegistrationEndReason::Replaced
697 } else {
698 reason
699 };
700 let replaced_by_connection_id = if replaced {
701 inner
702 .superseded_by
703 .remove(®istration.connection_id)
704 .map(ConnectionId::get)
705 } else {
706 None
707 };
708 if let Some(replaced_by_connection_id) = replaced_by_connection_id {
709 info!(
710 target: "subc.registry",
711 module_id = %registration.manifest.module_id,
712 connection_id = registration.connection_id.get(),
713 reason = %end_reason.as_str(),
714 replaced_by_connection_id,
715 "module registration ended"
716 );
717 continue;
718 }
719 info!(
720 target: "subc.registry",
721 module_id = %registration.manifest.module_id,
722 connection_id = registration.connection_id.get(),
723 reason = %end_reason.as_str(),
724 "module registration ended"
725 );
726 }
727 Ok(closed)
728 }
729
730 fn lock_inner(&self) -> Result<MutexGuard<'_, RegistryInner>, RegistryError> {
731 self.inner.lock().map_err(|_| RegistryError::Poisoned)
732 }
733}
734
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
737enum SlotKind {
738 Active,
739 Candidate,
740 Superseded,
741}
742
743impl RegistryInner {
744 fn notify_module_changed(&self, module_id: &str) {
745 if let Some(sender) = self.module_changes.get(module_id) {
746 sender.send_replace(());
747 }
748 }
749
750 fn find_by_connection(
751 &self,
752 connection_id: ConnectionId,
753 ) -> Option<(SlotKind, &ModuleRegistration)> {
754 let owned_by =
755 |registration: &&ModuleRegistration| registration.connection_id == connection_id;
756 self.modules
757 .values()
758 .find(owned_by)
759 .map(|registration| (SlotKind::Active, registration))
760 .or_else(|| {
761 self.candidates
762 .values()
763 .find(owned_by)
764 .map(|registration| (SlotKind::Candidate, registration))
765 })
766 .or_else(|| {
767 self.superseded
768 .iter()
769 .find(owned_by)
770 .map(|registration| (SlotKind::Superseded, registration))
771 })
772 }
773
774 fn registration_mut(
775 &mut self,
776 slot: SlotKind,
777 connection_id: ConnectionId,
778 ) -> Option<&mut ModuleRegistration> {
779 let owned_by =
780 |registration: &&mut ModuleRegistration| registration.connection_id == connection_id;
781 match slot {
782 SlotKind::Active => self.modules.values_mut().find(owned_by),
783 SlotKind::Candidate => self.candidates.values_mut().find(owned_by),
784 SlotKind::Superseded => self.superseded.iter_mut().find(owned_by),
785 }
786 }
787
788 fn close_module(&mut self, module_id: &str, listed: bool) -> Option<ModuleRegistration> {
789 let mut registration = self.modules.remove(module_id)?;
790 registration.state = ChannelState::Closed;
791 if listed {
792 self.bump_generation();
793 }
794 Some(registration)
795 }
796
797 fn bump_generation(&mut self) {
798 self.generation = self.generation.wrapping_add(1);
799 }
800}
801
802#[derive(Debug, Clone, PartialEq, Eq)]
803pub enum RegistryError {
804 DuplicateModuleId {
805 module_id: String,
806 },
807 PathHazardModuleId {
816 module_id: String,
817 reason: String,
818 },
819 Poisoned,
820}
821
822impl fmt::Display for RegistryError {
823 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
824 match self {
825 Self::DuplicateModuleId { module_id } => {
826 write!(f, "module_id '{module_id}' is already registered")
827 }
828 Self::PathHazardModuleId { module_id, reason } => {
829 write!(
830 f,
831 "module_id '{}' is not usable as a path component: {reason}",
832 module_id.escape_debug()
833 )
834 }
835 Self::Poisoned => write!(f, "registry lock was poisoned"),
836 }
837 }
838}
839
840impl Error for RegistryError {}
841
842pub fn module_id_path_hazard(module_id: &str) -> Result<(), String> {
852 if module_id.is_empty() {
853 return Err("empty".to_string());
854 }
855 if module_id.contains('/') || module_id.contains('\\') {
856 return Err("contains a path separator".to_string());
857 }
858 if module_id == "." || module_id == ".." {
859 return Err("is a dot path component".to_string());
860 }
861 if module_id.chars().any(|c| c.is_control()) {
862 return Err("contains a control character".to_string());
863 }
864 if module_id.len() > 255 {
868 return Err("is longer than 255 bytes".to_string());
869 }
870 Ok(())
871}
872
873#[cfg(test)]
874mod change_notification_tests {
875 use super::*;
876
877 fn manifest() -> ModuleManifest {
878 ModuleManifest::builder("watched", "1.0.0")
879 .protocol_ver(1)
880 .build()
881 }
882
883 fn changed(receiver: &mut watch::Receiver<()>) {
884 assert!(
885 receiver.has_changed().unwrap(),
886 "registry write must notify"
887 );
888 receiver.borrow_and_update();
889 }
890
891 #[test]
892 fn every_registration_write_notifies_only_its_module() {
893 let registry = Registry::default();
894 let mut events = registry.subscribe_module_changes("watched").unwrap();
895 let other = registry.subscribe_module_changes("other").unwrap();
896 let active = ConnectionId::new(1);
897 let candidate = ConnectionId::new(2);
898 registry
899 .register_with_control_ops(manifest(), 1, active, vec![])
900 .unwrap();
901 changed(&mut events);
902 registry
903 .set_module_state_for_test("watched", ChannelState::Active)
904 .unwrap();
905 changed(&mut events);
906 registry
907 .replace_catalog_for_connection(active, vec![], None, Some(true))
908 .unwrap();
909 changed(&mut events);
910 registry
911 .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
912 .unwrap();
913 changed(&mut events);
914 registry
915 .replace_catalog_for_connection(candidate, vec![], None, Some(true))
916 .unwrap();
917 changed(&mut events);
918 registry.promote_candidate("watched").unwrap().unwrap();
919 changed(&mut events);
920 registry
922 .replace_catalog_for_connection(active, vec![], None, Some(false))
923 .unwrap();
924 changed(&mut events);
925 registry.deregister_connection(active).unwrap();
926 changed(&mut events);
927 registry.deregister_connection(candidate).unwrap();
928 changed(&mut events);
929 registry
930 .register_candidate_with_control_ops(manifest(), 1, candidate, vec![])
931 .unwrap();
932 changed(&mut events);
933 registry.deregister_connection(candidate).unwrap();
934 changed(&mut events);
935 assert!(
936 !other.has_changed().unwrap(),
937 "other module must stay parked"
938 );
939 }
940
941 #[test]
942 fn subscription_before_read_keeps_a_change_until_waited_on() {
943 let registry = Registry::default();
944 let mut events = registry.subscribe_module_changes("watched").unwrap();
945 assert!(registry.get_module("watched").unwrap().is_none());
946 registry
947 .register_with_control_ops(manifest(), 1, ConnectionId::new(1), vec![])
948 .unwrap();
949 registry.get_module("watched").unwrap().unwrap();
951 registry
952 .replace_catalog_for_connection(ConnectionId::new(1), vec![], None, Some(true))
953 .unwrap();
954 changed(&mut events);
955 assert!(!events.has_changed().unwrap());
956 }
957}
958
959#[cfg(test)]
960mod publication_tests {
961 use super::*;
962
963 fn manifest() -> ModuleManifest {
964 ModuleManifest::builder("m", "1.0.0")
965 .protocol_ver(1)
966 .build()
967 }
968
969 #[test]
973 fn unpublished_registration_is_unlisted_until_published() {
974 let registry = Registry::default();
975 let connection = ConnectionId::new(1);
976 registry
977 .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
978 .unwrap();
979 assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
980 assert!(registry.get_module("m").unwrap().is_some());
981 assert_eq!(registry.list_registered_modules().unwrap().len(), 1);
982 assert!(registry
983 .published_registration(RegistrationSlot::Active("m"))
984 .unwrap()
985 .is_none());
986 assert!(matches!(
987 registry.register_with_control_ops(manifest(), 1, ConnectionId::new(2), vec![]),
988 Err(RegistryError::DuplicateModuleId { .. })
989 ));
990 registry
992 .replace_catalog_for_connection(connection, vec![], None, Some(true))
993 .unwrap();
994 assert_eq!(registry.generation().unwrap(), 0);
995
996 assert!(registry.publish_registration(connection).unwrap());
997 let (generation, listed) = registry.list_modules().unwrap();
998 assert_eq!(generation, 1);
999 assert_eq!(listed.len(), 1);
1000 assert!(!registry.publish_registration(connection).unwrap());
1001 assert_eq!(registry.generation().unwrap(), 1);
1002 }
1003
1004 #[test]
1007 fn deregistering_an_unpublished_registration_leaves_the_generation() {
1008 let registry = Registry::default();
1009 let connection = ConnectionId::new(1);
1010 registry
1011 .register_unpublished_with_control_ops(manifest(), 1, connection, vec![])
1012 .unwrap();
1013 assert_eq!(registry.deregister_connection(connection).unwrap().len(), 1);
1014 assert_eq!(registry.list_modules().unwrap(), (0, Vec::new()));
1015 assert!(!registry.publish_registration(connection).unwrap());
1016 assert_eq!(registry.generation().unwrap(), 0);
1017 }
1018
1019 #[test]
1024 fn unpublished_candidate_is_hidden_from_published_lookups() {
1025 let registry = Registry::default();
1026 let candidate = ConnectionId::new(2);
1027 registry
1028 .register_unpublished_candidate_with_control_ops(manifest(), 1, candidate, vec![])
1029 .unwrap();
1030 assert!(registry
1031 .registration(RegistrationSlot::Candidate("m"))
1032 .unwrap()
1033 .is_some());
1034 assert!(registry
1035 .published_registration(RegistrationSlot::Candidate("m"))
1036 .unwrap()
1037 .is_none());
1038 assert!(registry
1039 .published_registration(RegistrationSlot::Connection(candidate))
1040 .unwrap()
1041 .is_none());
1042 assert!(registry.publish_registration(candidate).unwrap());
1043 assert!(registry
1044 .published_registration(RegistrationSlot::Candidate("m"))
1045 .unwrap()
1046 .is_some());
1047 assert_eq!(registry.generation().unwrap(), 0);
1048 }
1049}
1050
1051#[cfg(test)]
1052mod path_hazard_tests {
1053 use super::*;
1054 use crate::ConnectionId;
1055 use subc_protocol::manifest::ModuleManifest;
1056
1057 fn manifest(module_id: &str) -> ModuleManifest {
1058 ModuleManifest::builder(module_id, "0.1.0")
1059 .protocol_ver(1)
1060 .build()
1061 }
1062
1063 #[test]
1064 fn path_hazard_ids_are_refused_and_nothing_registers() {
1065 let registry = Registry::default();
1066 for (bad, reason_fragment) in [
1067 ("../escape", "path separator"),
1068 ("a/b", "path separator"),
1069 ("a\\b", "path separator"),
1070 ("..", "dot path component"),
1071 (".", "dot path component"),
1072 ("", "empty"),
1073 ("evil\u{0}id", "control character"),
1074 ] {
1075 let err = registry
1076 .register_with_control_ops(manifest(bad), 1, ConnectionId::new(7), Vec::new())
1077 .expect_err("path-hazard id must refuse");
1078 assert!(
1080 err.to_string().contains(reason_fragment),
1081 "id {bad:?}: expected {reason_fragment:?} in {err}"
1082 );
1083 }
1084 assert_eq!(registry.active_registration_count().unwrap(), 0);
1087 assert_eq!(registry.generation().unwrap(), 0);
1088 }
1089
1090 #[test]
1091 fn module_id_path_component_length_matches_shared_refusal_vectors() {
1092 let doc: serde_json::Value = serde_json::from_str(include_str!(
1093 "../tests/golden/module_id_path_component_refusals.json"
1094 ))
1095 .expect("refusal fixture parses");
1096
1097 for case in doc["vectors"].as_array().expect("vectors array") {
1098 let name = case["name"].as_str().expect("name");
1099 let module_id = case["module_id"]["unit"]
1100 .as_str()
1101 .expect("module_id unit")
1102 .repeat(
1103 case["module_id"]["repeat"]
1104 .as_u64()
1105 .expect("module_id repeat") as usize,
1106 );
1107 assert_eq!(
1108 module_id.len(),
1109 case["utf8_bytes"].as_u64().expect("utf8 bytes") as usize
1110 );
1111
1112 let expected = case["expect_reason"].as_str().map(str::to_owned);
1113 assert_eq!(
1114 module_id_path_hazard(&module_id).err(),
1115 expected,
1116 "shared refusal vector {name:?} diverged"
1117 );
1118 }
1119 }
1120
1121 #[test]
1122 fn working_id_shapes_register_including_namespace_colons() {
1123 let registry = Registry::default();
1124 for (i, good) in ["magic-context", "mcp:everything", "v1.2-module"]
1125 .iter()
1126 .enumerate()
1127 {
1128 registry
1129 .register_with_control_ops(
1130 manifest(good),
1131 1,
1132 ConnectionId::new(10 + i as u64),
1133 Vec::new(),
1134 )
1135 .unwrap_or_else(|err| panic!("id {good:?} must register: {err}"));
1136 }
1137 assert_eq!(registry.active_registration_count().unwrap(), 3);
1138 }
1139}
1140
1141#[cfg(test)]
1142mod swap_slot_tests {
1143 use super::*;
1144
1145 fn manifest(module_id: &str, ready: Option<bool>) -> ModuleManifest {
1146 let mut manifest = ModuleManifest::builder(module_id, "0.1.0").build();
1147 manifest.ready = ready;
1148 manifest
1149 }
1150
1151 const INCUMBENT: ConnectionId = ConnectionId(1);
1152 const CANDIDATE: ConnectionId = ConnectionId(2);
1153
1154 fn registry_with_candidate() -> Registry {
1155 let registry = Registry::default();
1156 registry
1157 .register_with_control_ops(manifest("m", None), 1, INCUMBENT, Vec::new())
1158 .unwrap();
1159 registry
1160 .register_candidate_with_control_ops(
1161 manifest("m", Some(false)),
1162 1,
1163 CANDIDATE,
1164 Vec::new(),
1165 )
1166 .unwrap();
1167 registry
1168 }
1169
1170 #[test]
1171 fn candidate_is_invisible_to_by_id_lookups_and_listing() {
1172 let registry = registry_with_candidate();
1173 let generation = registry.generation().unwrap();
1174 assert_eq!(
1175 registry.get_module("m").unwrap().unwrap().connection_id,
1176 INCUMBENT
1177 );
1178 let (listed_generation, listed) = registry.list_modules().unwrap();
1179 assert_eq!(listed.len(), 1);
1180 assert_eq!(listed[0].connection_id, INCUMBENT);
1181 assert_eq!(listed_generation, generation);
1182 assert_eq!(registry.active_registration_count().unwrap(), 1);
1183 assert_eq!(
1184 registry.get_candidate("m").unwrap().unwrap().connection_id,
1185 CANDIDATE
1186 );
1187 assert_eq!(
1188 registry
1189 .register_candidate_with_control_ops(
1190 manifest("m", None),
1191 1,
1192 ConnectionId(3),
1193 Vec::new()
1194 )
1195 .unwrap_err(),
1196 RegistryError::DuplicateModuleId {
1197 module_id: "m".to_string()
1198 }
1199 );
1200 }
1201
1202 #[test]
1203 fn promoted_candidate_keeps_its_verified_nonce_fact() {
1204 let registry = Registry::default();
1205 registry
1206 .register_unpublished_verified_candidate_with_control_ops(
1207 manifest("m", Some(true)),
1208 1,
1209 CANDIDATE,
1210 Vec::new(),
1211 )
1212 .unwrap();
1213 assert!(registry.publish_registration(CANDIDATE).unwrap());
1214 assert!(registry
1215 .list_modules_with_nonce_verification()
1216 .unwrap()
1217 .1
1218 .is_empty());
1219
1220 registry.promote_candidate("m").unwrap().unwrap();
1221 let (_, modules) = registry.list_modules_with_nonce_verification().unwrap();
1222 assert_eq!(modules.len(), 1);
1223 assert!(modules[0].1);
1224 }
1225
1226 #[test]
1229 fn candidate_catalog_update_reaches_the_candidate_registration() {
1230 let registry = registry_with_candidate();
1231 assert!(!registry.get_candidate("m").unwrap().unwrap().ready);
1232
1233 let updated = registry
1234 .replace_catalog_for_connection(CANDIDATE, Vec::new(), None, Some(true))
1235 .unwrap()
1236 .expect("the candidate's own connection finds its registration");
1237
1238 assert_eq!(updated.connection_id, CANDIDATE);
1239 assert!(registry.get_candidate("m").unwrap().unwrap().ready);
1240 assert_eq!(
1241 registry.get_module_by_connection(CANDIDATE).unwrap(),
1242 Some(updated)
1243 );
1244 assert_eq!(
1245 registry.get_module("m").unwrap().unwrap().connection_id,
1246 INCUMBENT,
1247 "a candidate's update must not touch the active registration"
1248 );
1249 }
1250
1251 #[test]
1252 fn promotion_swaps_slots_and_each_connection_still_deregisters_its_own() {
1253 let registry = registry_with_candidate();
1254 let before = registry.generation().unwrap();
1255 let cutover = registry.promote_candidate("m").unwrap().unwrap();
1256 assert_eq!(cutover.promoted.connection_id, CANDIDATE);
1257 assert_eq!(cutover.superseded.unwrap().connection_id, INCUMBENT);
1258 assert_ne!(registry.generation().unwrap(), before);
1259 assert_eq!(registry.promote_candidate("m").unwrap(), None);
1260
1261 assert_eq!(
1262 registry
1263 .registration(RegistrationSlot::Active("m"))
1264 .unwrap()
1265 .unwrap()
1266 .connection_id,
1267 CANDIDATE
1268 );
1269 assert!(registry
1270 .registration(RegistrationSlot::Candidate("m"))
1271 .unwrap()
1272 .is_none());
1273 assert!(registry
1274 .registration(RegistrationSlot::Connection(INCUMBENT))
1275 .unwrap()
1276 .is_some());
1277
1278 let closed = registry.deregister_connection(INCUMBENT).unwrap();
1279 assert_eq!(closed.len(), 1);
1280 assert_eq!(closed[0].connection_id, INCUMBENT);
1281 assert_eq!(closed[0].state, ChannelState::Closed);
1282 assert!(registry
1283 .registration(RegistrationSlot::Connection(INCUMBENT))
1284 .unwrap()
1285 .is_none());
1286 assert_eq!(
1287 registry.get_module("m").unwrap().unwrap().connection_id,
1288 CANDIDATE
1289 );
1290 }
1291
1292 #[test]
1293 fn a_dropped_candidate_deregisters_from_the_candidate_slot_only() {
1294 let registry = registry_with_candidate();
1295 let closed = registry.deregister_connection(CANDIDATE).unwrap();
1296 assert_eq!(closed.len(), 1);
1297 assert_eq!(closed[0].connection_id, CANDIDATE);
1298 assert!(registry.get_candidate("m").unwrap().is_none());
1299 assert_eq!(
1300 registry.get_module("m").unwrap().unwrap().connection_id,
1301 INCUMBENT
1302 );
1303 }
1304}