Skip to main content

hyprstream_rpc/registry/
mod.rs

1//! Centralized endpoint registry for service discovery.
2//!
3//! This module provides:
4//! - `EndpointMode` for determining transport type (inproc, ipc, tcp)
5//! - `SocketKind` for identifying RPC socket types (implements Hash)
6//! - `EndpointRegistry` for service endpoint management (supports multiple socket types)
7//! - `ServiceRegistration` RAII guard for automatic cleanup
8//!
9//! # Usage
10//!
11//! ```ignore
12//! use hyprstream_rpc::registry::{init, global, EndpointMode, SocketKind, ServiceRegistration};
13//!
14//! // Initialize at startup
15//! init(EndpointMode::Ipc, Some(runtime_dir));
16//!
17//! // Services self-register (single endpoint, backward compatible)
18//! let _reg = ServiceRegistration::new("policy", endpoint, None)?;
19//!
20//! // Services with multiple endpoints
21//! let _reg = ServiceRegistration::multi("model", vec![
22//!     (SocketKind::Rep, rep_endpoint),
23//!     (SocketKind::Quic, quic_endpoint),
24//! ], None)?;
25//!
26//! // Clients discover local endpoints by socket type
27//! let rep_endpoint = global().endpoint("model", SocketKind::Rep);
28//! let quic_endpoint = global().try_endpoint("model", SocketKind::Quic)?;
29//! ```
30
31use crate::transport::TransportConfig;
32use parking_lot::RwLock;
33use std::collections::HashMap;
34use std::path::PathBuf;
35use std::sync::Arc;
36
37/// Socket type identifier for endpoint registration.
38///
39/// Reduced (#380) from the historical ZMQ-era taxonomy to the variants that are
40/// actually constructed by live code:
41/// - [`SocketKind::Rep`] — the server-side RPC socket used by every service
42///   registration and client resolution today.
43/// - [`SocketKind::Req`] — the client-side RPC socket, the logical counterpart
44///   of `Rep`. Currently no in-tree client constructs it (the resolver/registry
45///   are kind-symmetric), but it is retained to keep the client/server pair
46///   self-documenting and to avoid forcing future clients to misuse `Rep`.
47/// - [`SocketKind::Quic`] — the QUIC/WebTransport transport used by the moq
48///   stream plane. Unlike local REP/REQ endpoints, QUIC has no synthesized
49///   default: network reach must be explicitly registered or announced.
50///
51/// The dropped variants (`Dealer`, `Router`, `Pub`, `Sub`, `XPub`, `XSub`,
52/// `Push`, `Pull`, `Pair`, `Stream`) were ZMQ socket kinds carried by the
53/// pre-moq stack; the moq migration replaced Pub/Sub and the rest were never
54/// constructed by live code (only exhaustive match arms and registry-suffix
55/// tests referenced them). `SocketKind` is an internal identifier — it is not
56/// serialized onto the wire (only its lowercase name string is, in
57/// `ServiceSummary::socket_kinds`), so this reduction is wire-compatible.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59pub enum SocketKind {
60    /// REQ socket (client request) — logical client-side counterpart to `Rep`.
61    Req,
62    /// REP socket (server reply) — the live server-side RPC socket.
63    Rep,
64    /// QUIC/WebTransport transport type — the moq stream-plane socket.
65    Quic,
66}
67
68impl SocketKind {
69    /// Get the endpoint suffix for this socket type.
70    pub fn suffix(&self) -> &'static str {
71        match self {
72            SocketKind::Rep => "",
73            SocketKind::Req => "-req",
74            SocketKind::Quic => "-quic",
75        }
76    }
77}
78
79/// Endpoint mode determines default transport type.
80///
81/// - `Inproc`: In-process endpoints (daemon mode, single process)
82/// - `Ipc`: Unix domain sockets (systemd mode, auto-detects socket activation)
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
84pub enum EndpointMode {
85    /// In-process (daemon mode)
86    #[default]
87    Inproc,
88    /// Unix domain sockets (systemd mode)
89    ///
90    /// When running under systemd socket activation (LISTEN_FDS set),
91    /// automatically uses the systemd-provided file descriptor.
92    /// Otherwise, binds to a new Unix domain socket.
93    Ipc,
94}
95
96/// Service registration entry with multiple endpoints by socket type.
97#[derive(Debug, Clone)]
98pub struct ServiceEntry {
99    /// Service name
100    pub name: String,
101    /// Endpoints by socket type
102    pub endpoints: HashMap<SocketKind, TransportConfig>,
103    /// Optional description
104    pub description: Option<String>,
105    /// Raw `.capnp` schema bytes (compile-time embedded via `include_bytes!`)
106    pub schema: Option<&'static [u8]>,
107}
108
109/// Centralized endpoint registry with self-registration.
110///
111/// Supports services with multiple socket types (REP, ROUTER, PUB, etc.).
112///
113/// # Warning
114///
115/// Do NOT hold the guard from `global()` across `.await` points.
116/// Clone needed data before awaiting:
117///
118/// ```ignore
119/// let endpoint = global().endpoint("foo", SocketType::REP);  // Clone the TransportConfig
120/// some_async_call().await;  // Lock released
121/// ```
122pub struct EndpointRegistry {
123    mode: EndpointMode,
124    runtime_dir: Option<PathBuf>,
125    services: RwLock<HashMap<String, ServiceEntry>>,
126}
127
128impl EndpointRegistry {
129    /// Create a new registry with the specified mode and runtime directory.
130    ///
131    /// # Arguments
132    ///
133    /// * `mode` - Transport mode (Inproc, Ipc, or Tcp)
134    /// * `runtime_dir` - Base directory for IPC sockets (required for Ipc mode)
135    pub fn new(mode: EndpointMode, runtime_dir: Option<PathBuf>) -> Self {
136        Self {
137            mode,
138            runtime_dir,
139            services: RwLock::new(HashMap::new()),
140        }
141    }
142
143    /// Register a service endpoint for a specific socket type.
144    ///
145    /// Called by services on startup to advertise their endpoints.
146    pub fn register(
147        &self,
148        name: &str,
149        socket_kind: SocketKind,
150        endpoint: TransportConfig,
151        description: Option<&str>,
152    ) {
153        let mut services = self.services.write();
154        let entry = services
155            .entry(name.to_owned())
156            .or_insert_with(|| ServiceEntry {
157                name: name.to_owned(),
158                endpoints: HashMap::new(),
159                description: description.map(String::from),
160                schema: None,
161            });
162        // Update description if provided
163        if let Some(desc) = description {
164            entry.description = Some(desc.to_owned());
165        }
166        entry.endpoints.insert(socket_kind, endpoint);
167    }
168
169    /// Unregister a specific socket type for a service.
170    ///
171    /// If all socket types are removed, the service entry is deleted.
172    ///
173    /// D8: Only accessible within this crate — callers should use
174    /// `ServiceRegistration` RAII guard for ownership-enforced cleanup.
175    pub(crate) fn unregister(&self, name: &str, socket_kind: SocketKind) {
176        let mut services = self.services.write();
177        if let Some(entry) = services.get_mut(name) {
178            entry.endpoints.remove(&socket_kind);
179            if entry.endpoints.is_empty() {
180                services.remove(name);
181            }
182        }
183    }
184
185    /// Unregister all socket types for a service.
186    #[allow(dead_code)]
187    pub(crate) fn unregister_all(&self, name: &str) {
188        self.services.write().remove(name);
189    }
190
191    /// Get endpoint for a service and socket type.
192    ///
193    /// Returns the registered endpoint if available, otherwise generates a
194    /// local default for REP/REQ based on the current mode and socket type.
195    ///
196    /// # Panics
197    ///
198    /// Panics for socket kinds that have no local default, such as
199    /// [`SocketKind::Quic`]. New resolver code should prefer
200    /// [`Self::try_endpoint`] so missing network reach is a normal error.
201    pub fn endpoint(&self, name: &str, socket_kind: SocketKind) -> TransportConfig {
202        self.try_endpoint(name, socket_kind)
203            .unwrap_or_else(|err| panic!("{err}"))
204    }
205
206    /// Try to get endpoint for a service and socket type.
207    ///
208    /// Registered endpoints are returned as-is. Missing REP/REQ endpoints keep
209    /// the historical local fallback (`inproc` or same-host UDS), while missing
210    /// QUIC/network endpoints fail closed instead of synthesizing a placeholder.
211    pub fn try_endpoint(
212        &self,
213        name: &str,
214        socket_kind: SocketKind,
215    ) -> anyhow::Result<TransportConfig> {
216        if let Some(endpoint) = self.registered_endpoint(name, socket_kind) {
217            return Ok(endpoint);
218        }
219
220        self.local_default_endpoint(name, socket_kind)
221    }
222
223    /// Get an explicitly registered endpoint without applying any profile
224    /// fallback.
225    pub fn registered_endpoint(
226        &self,
227        name: &str,
228        socket_kind: SocketKind,
229    ) -> Option<TransportConfig> {
230        if let Some(entry) = self.services.read().get(name) {
231            if let Some(ep) = entry.endpoints.get(&socket_kind) {
232                return Some(ep.clone());
233            }
234        }
235        None
236    }
237
238    /// Generate the legacy local default endpoint for a service and socket type.
239    ///
240    /// This remains for direct registry callers. The process-global resolver
241    /// installed by [`init`] uses explicit resolver profile types instead.
242    fn local_default_endpoint(
243        &self,
244        name: &str,
245        socket_kind: SocketKind,
246    ) -> anyhow::Result<TransportConfig> {
247        match self.mode {
248            EndpointMode::Inproc => local_inproc_endpoint(name, socket_kind),
249            EndpointMode::Ipc => {
250                same_host_uds_endpoint(name, socket_kind, self.runtime_dir.as_ref())
251            }
252        }
253    }
254}
255
256fn local_inproc_endpoint(name: &str, socket_kind: SocketKind) -> anyhow::Result<TransportConfig> {
257    if socket_kind == SocketKind::Quic {
258        anyhow::bail!(
259            "no registered QUIC endpoint for service '{name}' — network reach must be announced or explicitly registered"
260        );
261    }
262    Ok(TransportConfig::inproc(format!(
263        "hyprstream/{name}{}",
264        socket_kind.suffix()
265    )))
266}
267
268fn same_host_uds_endpoint(
269    name: &str,
270    socket_kind: SocketKind,
271    runtime_dir: Option<&PathBuf>,
272) -> anyhow::Result<TransportConfig> {
273    if socket_kind == SocketKind::Quic {
274        anyhow::bail!(
275            "no registered QUIC endpoint for service '{name}' — network reach must be announced or explicitly registered"
276        );
277    }
278    let suffix = socket_kind.suffix();
279    let path = runtime_dir
280        .map(|d| d.join(format!("{name}{suffix}.sock")))
281        .unwrap_or_else(|| PathBuf::from(format!("/tmp/hyprstream/{name}{suffix}.sock")));
282    Ok(TransportConfig::ipc(path))
283}
284
285impl EndpointRegistry {
286    // ========================================================================
287    // Backward-compatible convenience methods (default to REP socket)
288    // ========================================================================
289
290    /// Register a REP endpoint (most common case, backward compatible).
291    pub fn register_rep(&self, name: &str, endpoint: TransportConfig, description: Option<&str>) {
292        self.register(name, SocketKind::Rep, endpoint, description);
293    }
294
295    /// Unregister a REP endpoint (backward compatible).
296    ///
297    /// D8: `pub(crate)` — external callers must use `ServiceRegistration` RAII guard.
298    #[allow(dead_code)]
299    pub(crate) fn unregister_rep(&self, name: &str) {
300        self.unregister(name, SocketKind::Rep);
301    }
302
303    /// Get REP endpoint for a service (backward compatible).
304    ///
305    /// Equivalent to `endpoint(name, SocketKind::Rep)`.
306    pub fn rep_endpoint(&self, name: &str) -> TransportConfig {
307        self.endpoint(name, SocketKind::Rep)
308    }
309
310    // ========================================================================
311    // Accessors
312    // ========================================================================
313
314    /// Get the current endpoint mode.
315    pub fn mode(&self) -> EndpointMode {
316        self.mode
317    }
318
319    /// Get the runtime directory (if set).
320    pub fn runtime_dir(&self) -> Option<&PathBuf> {
321        self.runtime_dir.as_ref()
322    }
323
324    /// List all registered services.
325    pub fn list_services(&self) -> Vec<String> {
326        self.services.read().keys().cloned().collect()
327    }
328
329    /// Get a clone of a service entry by name.
330    pub fn service_entry(&self, name: &str) -> Option<ServiceEntry> {
331        self.services.read().get(name).cloned()
332    }
333
334    /// Get all endpoints for a service.
335    pub fn service_endpoints(&self, name: &str) -> Option<HashMap<SocketKind, TransportConfig>> {
336        self.services.read().get(name).map(|e| e.endpoints.clone())
337    }
338
339    /// Register a service endpoint with schema bytes.
340    pub fn register_with_schema(
341        &self,
342        name: &str,
343        socket_kind: SocketKind,
344        endpoint: TransportConfig,
345        description: Option<&str>,
346        schema: Option<&'static [u8]>,
347    ) {
348        let mut services = self.services.write();
349        let entry = services
350            .entry(name.to_owned())
351            .or_insert_with(|| ServiceEntry {
352                name: name.to_owned(),
353                endpoints: HashMap::new(),
354                description: description.map(String::from),
355                schema: None,
356            });
357        if let Some(desc) = description {
358            entry.description = Some(desc.to_owned());
359        }
360        if schema.is_some() {
361            entry.schema = schema;
362        }
363        entry.endpoints.insert(socket_kind, endpoint);
364    }
365
366    /// Get schema bytes for a service (if registered with a schema).
367    pub fn service_schema(&self, name: &str) -> Option<&'static [u8]> {
368        self.services.read().get(name).and_then(|e| e.schema)
369    }
370}
371
372// Implement Resolver for EndpointRegistry (local, sync-internally).
373//
374// EndpointRegistry remains the local resolver. REP/REQ retain local defaults;
375// missing network endpoints fail closed through try_endpoint().
376#[async_trait::async_trait]
377impl crate::resolver::Resolver for EndpointRegistry {
378    async fn resolve(&self, name: &str, kind: SocketKind) -> anyhow::Result<TransportConfig> {
379        self.try_endpoint(name, kind)
380    }
381}
382
383// Global registry
384static REGISTRY: RwLock<Option<EndpointRegistry>> = RwLock::new(None);
385
386fn registered_global_endpoint(
387    name: &str,
388    kind: SocketKind,
389) -> anyhow::Result<Option<TransportConfig>> {
390    let registry = try_global()
391        .ok_or_else(|| anyhow::anyhow!("EndpointRegistry not initialized — call init() first"))?;
392    Ok(registry.registered_endpoint(name, kind))
393}
394
395/// Explicit single-process resolver profile.
396pub struct LocalInprocResolver;
397
398#[async_trait::async_trait]
399impl crate::resolver::Resolver for LocalInprocResolver {
400    async fn resolve(&self, name: &str, kind: SocketKind) -> anyhow::Result<TransportConfig> {
401        if let Some(endpoint) = registered_global_endpoint(name, kind)? {
402            return Ok(endpoint);
403        }
404        local_inproc_endpoint(name, kind)
405    }
406}
407
408/// Explicit IPC resolver profile.
409pub struct IpcResolver {
410    runtime_dir: Option<PathBuf>,
411}
412
413impl IpcResolver {
414    pub fn new(runtime_dir: Option<PathBuf>) -> Self {
415        Self { runtime_dir }
416    }
417}
418
419#[async_trait::async_trait]
420impl crate::resolver::Resolver for IpcResolver {
421    async fn resolve(&self, name: &str, kind: SocketKind) -> anyhow::Result<TransportConfig> {
422        if let Some(endpoint) = registered_global_endpoint(name, kind)? {
423            return Ok(endpoint);
424        }
425        same_host_uds_endpoint(name, kind, self.runtime_dir.as_ref())
426    }
427}
428
429/// Initialize the global endpoint registry.
430///
431/// Idempotent: subsequent calls are no-ops if already initialized.
432///
433/// # Arguments
434///
435/// * `mode` - Transport mode (Inproc, Ipc, or Tcp)
436/// * `runtime_dir` - Base directory for IPC sockets (required for Ipc mode)
437pub fn init(mode: EndpointMode, runtime_dir: Option<PathBuf>) {
438    let mut guard = REGISTRY.write();
439    if guard.is_none() {
440        *guard = Some(EndpointRegistry::new(mode, runtime_dir.clone()));
441        // Also set the global Resolver so async consumers use an explicit
442        // locality profile instead of the registry's legacy direct fallback.
443        let resolver: Arc<dyn crate::resolver::Resolver> = match mode {
444            EndpointMode::Inproc => Arc::new(LocalInprocResolver),
445            EndpointMode::Ipc => Arc::new(IpcResolver::new(runtime_dir)),
446        };
447        crate::resolver::set_global(resolver);
448    }
449}
450
451/// Shutdown the global registry.
452///
453/// Clears all registered services.
454pub fn shutdown() {
455    *REGISTRY.write() = None;
456}
457
458/// Get the global registry.
459///
460/// # Panics
461///
462/// Panics if the registry has not been initialized.
463///
464/// # Warning
465///
466/// Do NOT hold the returned guard across `.await` points.
467/// Clone needed data before awaiting.
468pub fn global() -> impl std::ops::Deref<Target = EndpointRegistry> + 'static {
469    parking_lot::RwLockReadGuard::map(REGISTRY.read(), |r| match r.as_ref() {
470        Some(registry) => registry,
471        None => panic!("EndpointRegistry not initialized - call init() first"),
472    })
473}
474
475/// Try to get the global registry (non-panicking).
476///
477/// Returns `None` if the registry has not been initialized.
478pub fn try_global() -> Option<impl std::ops::Deref<Target = EndpointRegistry> + 'static> {
479    let guard = REGISTRY.read();
480    if guard.is_some() {
481        Some(parking_lot::RwLockReadGuard::map(guard, |r| {
482            // SAFETY: We checked is_some() above, so this is guaranteed to succeed
483            match r.as_ref() {
484                Some(registry) => registry,
485                None => unreachable!("checked is_some() above"),
486            }
487        }))
488    } else {
489        None
490    }
491}
492
493/// RAII guard for service registration.
494///
495/// Automatically unregisters the service when dropped.
496///
497/// # Example
498///
499/// ```ignore
500/// // Single REP endpoint (backward compatible)
501/// let _reg = ServiceRegistration::new("policy", endpoint, None)?;
502///
503/// // Specific socket type
504/// let _reg = ServiceRegistration::with_socket_type("inference", SocketKind::Quic, endpoint, None)?;
505///
506/// // Multiple endpoints
507/// let _reg = ServiceRegistration::multi("model", vec![
508///     (SocketKind::Rep, rep_endpoint),
509///     (SocketKind::Quic, quic_endpoint),
510/// ], None)?;
511/// ```
512pub struct ServiceRegistration {
513    name: String,
514    socket_kinds: Vec<SocketKind>,
515}
516
517impl ServiceRegistration {
518    /// Register a REP endpoint and return a guard (backward compatible).
519    ///
520    /// # Arguments
521    ///
522    /// * `name` - Service name for discovery
523    /// * `endpoint` - The endpoint configuration
524    /// * `description` - Optional human-readable description
525    ///
526    /// # Errors
527    ///
528    /// Returns an error if the registry has not been initialized.
529    pub fn new(
530        name: &str,
531        endpoint: TransportConfig,
532        description: Option<&str>,
533    ) -> anyhow::Result<Self> {
534        Self::with_socket_kind(name, SocketKind::Rep, endpoint, description)
535    }
536
537    /// Register an endpoint with a specific socket type.
538    ///
539    /// # Arguments
540    ///
541    /// * `name` - Service name for discovery
542    /// * `socket_kind` - The socket type
543    /// * `endpoint` - The endpoint configuration
544    /// * `description` - Optional human-readable description
545    pub fn with_socket_kind(
546        name: &str,
547        socket_kind: SocketKind,
548        endpoint: TransportConfig,
549        description: Option<&str>,
550    ) -> anyhow::Result<Self> {
551        let registry = try_global().ok_or_else(|| anyhow::anyhow!("Registry not initialized"))?;
552        registry.register(name, socket_kind, endpoint, description);
553        Ok(Self {
554            name: name.to_owned(),
555            socket_kinds: vec![socket_kind],
556        })
557    }
558
559    /// Register multiple endpoints at once.
560    ///
561    /// # Arguments
562    ///
563    /// * `name` - Service name for discovery
564    /// * `endpoints` - Vec of (socket_kind, endpoint) pairs
565    /// * `description` - Optional human-readable description
566    pub fn multi(
567        name: &str,
568        endpoints: Vec<(SocketKind, TransportConfig)>,
569        description: Option<&str>,
570    ) -> anyhow::Result<Self> {
571        let registry = try_global().ok_or_else(|| anyhow::anyhow!("Registry not initialized"))?;
572        let mut socket_kinds = Vec::with_capacity(endpoints.len());
573        for (socket_kind, endpoint) in endpoints {
574            registry.register(name, socket_kind, endpoint, description);
575            socket_kinds.push(socket_kind);
576        }
577        Ok(Self {
578            name: name.to_owned(),
579            socket_kinds,
580        })
581    }
582
583    /// Add another socket type to an existing registration.
584    pub fn add_socket_kind(
585        &mut self,
586        socket_kind: SocketKind,
587        endpoint: TransportConfig,
588        description: Option<&str>,
589    ) -> anyhow::Result<()> {
590        let registry = try_global().ok_or_else(|| anyhow::anyhow!("Registry not initialized"))?;
591        registry.register(&self.name, socket_kind, endpoint, description);
592        self.socket_kinds.push(socket_kind);
593        Ok(())
594    }
595
596    /// Get the service name.
597    pub fn name(&self) -> &str {
598        &self.name
599    }
600
601    /// Get the registered socket kinds.
602    pub fn socket_kinds(&self) -> &[SocketKind] {
603        &self.socket_kinds
604    }
605}
606
607impl Drop for ServiceRegistration {
608    fn drop(&mut self) {
609        if let Some(registry) = try_global() {
610            for socket_kind in &self.socket_kinds {
611                registry.unregister(&self.name, *socket_kind);
612            }
613        }
614    }
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620    use crate::resolver::Resolver;
621    use parking_lot::Mutex;
622
623    // Serialize tests that use the global registry
624    static TEST_MUTEX: Mutex<()> = Mutex::new(());
625
626    fn reset_registry() {
627        *REGISTRY.write() = None;
628    }
629
630    #[test]
631    fn test_inproc_defaults() {
632        let _lock = TEST_MUTEX.lock();
633        reset_registry();
634        init(EndpointMode::Inproc, None);
635
636        // REP socket (default, no suffix)
637        let endpoint = global().endpoint("policy", SocketKind::Rep);
638        assert_eq!(endpoint.endpoint_string(), "inproc://hyprstream/policy");
639
640        // REQ socket (with suffix)
641        let endpoint = global().endpoint("model", SocketKind::Req);
642        assert_eq!(endpoint.endpoint_string(), "inproc://hyprstream/model-req");
643    }
644
645    #[test]
646    fn test_global_resolver_installs_local_inproc_profile() {
647        let _lock = TEST_MUTEX.lock();
648        reset_registry();
649        init(EndpointMode::Inproc, None);
650
651        let resolver = match crate::resolver::try_global() {
652            Some(resolver) => resolver,
653            None => panic!("global resolver must be installed"),
654        };
655        let endpoint = futures::executor::block_on(resolver.resolve("policy", SocketKind::Rep))
656            .unwrap_or_else(|err| panic!("local-inproc resolver failed: {err}"));
657        assert_eq!(endpoint.endpoint_string(), "inproc://hyprstream/policy");
658    }
659
660    #[test]
661    fn test_ipc_defaults() {
662        let _lock = TEST_MUTEX.lock();
663        reset_registry();
664        init(EndpointMode::Ipc, Some(PathBuf::from("/run/hyprstream")));
665
666        // REP socket (default, no suffix)
667        let endpoint = global().endpoint("policy", SocketKind::Rep);
668        assert_eq!(
669            endpoint.endpoint_string(),
670            "ipc:///run/hyprstream/policy.sock"
671        );
672
673        // REQ socket (with suffix)
674        let endpoint = global().endpoint("model", SocketKind::Req);
675        assert_eq!(
676            endpoint.endpoint_string(),
677            "ipc:///run/hyprstream/model-req.sock"
678        );
679    }
680
681    #[test]
682    fn test_global_resolver_installs_ipc_profile() {
683        let _lock = TEST_MUTEX.lock();
684        reset_registry();
685        init(EndpointMode::Ipc, Some(PathBuf::from("/run/hyprstream")));
686
687        let resolver = match crate::resolver::try_global() {
688            Some(resolver) => resolver,
689            None => panic!("global resolver must be installed"),
690        };
691        let endpoint = futures::executor::block_on(resolver.resolve("policy", SocketKind::Rep))
692            .unwrap_or_else(|err| panic!("same-host-uds resolver failed: {err}"));
693        assert_eq!(
694            endpoint.endpoint_string(),
695            "ipc:///run/hyprstream/policy.sock"
696        );
697    }
698
699    #[test]
700    fn test_single_registration() -> anyhow::Result<()> {
701        let _lock = TEST_MUTEX.lock();
702        reset_registry();
703        init(EndpointMode::Inproc, None);
704
705        {
706            let _reg = ServiceRegistration::new(
707                "test-service",
708                TransportConfig::inproc("custom/endpoint"),
709                Some("Test service"),
710            )?;
711
712            let endpoint = global().endpoint("test-service", SocketKind::Rep);
713            assert_eq!(endpoint.endpoint_string(), "inproc://custom/endpoint");
714        }
715
716        // After drop, falls back to default
717        let endpoint = global().endpoint("test-service", SocketKind::Rep);
718        assert_eq!(
719            endpoint.endpoint_string(),
720            "inproc://hyprstream/test-service"
721        );
722        Ok(())
723    }
724
725    #[test]
726    fn test_multi_registration() -> anyhow::Result<()> {
727        let _lock = TEST_MUTEX.lock();
728        reset_registry();
729        init(EndpointMode::Inproc, None);
730
731        {
732            let _reg = ServiceRegistration::multi(
733                "model",
734                vec![
735                    (SocketKind::Rep, TransportConfig::inproc("model/rep")),
736                    (SocketKind::Quic, TransportConfig::inproc("model/quic")),
737                ],
738                Some("Model service"),
739            )?;
740
741            // Both endpoints registered
742            let rep_ep = global().endpoint("model", SocketKind::Rep);
743            assert_eq!(rep_ep.endpoint_string(), "inproc://model/rep");
744
745            let quic_ep = global().endpoint("model", SocketKind::Quic);
746            assert_eq!(quic_ep.endpoint_string(), "inproc://model/quic");
747        }
748
749        // After drop, Rep falls back to its inproc default; Quic has no
750        // synthesized network default and fails closed.
751        let rep_ep = global().endpoint("model", SocketKind::Rep);
752        assert_eq!(rep_ep.endpoint_string(), "inproc://hyprstream/model");
753
754        let err = match global().try_endpoint("model", SocketKind::Quic) {
755            Ok(endpoint) => panic!("missing QUIC endpoint resolved to {endpoint:?}"),
756            Err(err) => err,
757        };
758        assert!(
759            err.to_string().contains("no registered QUIC endpoint"),
760            "unexpected error: {err}"
761        );
762        Ok(())
763    }
764
765    #[test]
766    fn test_missing_quic_endpoint_fails_closed_through_resolver() {
767        let _lock = TEST_MUTEX.lock();
768        reset_registry();
769        init(EndpointMode::Inproc, None);
770
771        let err = match futures::executor::block_on(global().resolve("model", SocketKind::Quic)) {
772            Ok(endpoint) => panic!("missing QUIC endpoint resolved to {endpoint:?}"),
773            Err(err) => err,
774        };
775        assert!(
776            err.to_string().contains("no registered QUIC endpoint"),
777            "unexpected error: {err}"
778        );
779    }
780
781    #[test]
782    fn test_backward_compat() {
783        let _lock = TEST_MUTEX.lock();
784        reset_registry();
785        init(EndpointMode::Inproc, None);
786
787        // Old-style single endpoint registration
788        let registry = global();
789        registry.register_rep(
790            "compat-service",
791            TransportConfig::inproc("compat/endpoint"),
792            None,
793        );
794
795        // Old-style retrieval
796        let endpoint = registry.rep_endpoint("compat-service");
797        assert_eq!(endpoint.endpoint_string(), "inproc://compat/endpoint");
798
799        // New-style retrieval works too
800        let endpoint = registry.endpoint("compat-service", SocketKind::Rep);
801        assert_eq!(endpoint.endpoint_string(), "inproc://compat/endpoint");
802    }
803
804    #[test]
805    fn test_try_global_uninitialized() {
806        let _lock = TEST_MUTEX.lock();
807        reset_registry();
808        assert!(try_global().is_none());
809    }
810
811    #[test]
812    fn test_list_services() {
813        let _lock = TEST_MUTEX.lock();
814        reset_registry();
815        init(EndpointMode::Inproc, None);
816
817        global().register("svc1", SocketKind::Rep, TransportConfig::inproc("a"), None);
818        global().register("svc2", SocketKind::Quic, TransportConfig::inproc("b"), None);
819
820        let services = global().list_services();
821        assert!(services.contains(&"svc1".to_owned()));
822        assert!(services.contains(&"svc2".to_owned()));
823    }
824}