Skip to main content

hyprstream_rpc/service/
spawnable.rs

1//! The `Spawnable` trait for services that can be spawned.
2//!
3//! This trait lives in `hyprstream-rpc` because types in this crate
4//! (StreamService, QuicServiceLoop) implement it directly. The spawner
5//! infrastructure that consumes Spawnable lives in `hyprstream-service`.
6
7use std::sync::Arc;
8use tokio::sync::Notify;
9
10use crate::error::{Result, RpcError};
11use crate::registry::SocketKind;
12use crate::service::RequestService;
13use crate::transport::TransportConfig;
14
15/// Trait for services that can be spawned by ServiceSpawner.
16///
17/// Implemented by both REQ/REP handlers and XSUB/XPUB proxies.
18/// This provides a unified spawning API regardless of service type.
19pub trait Spawnable: Send + 'static {
20    /// Service name (for logging and registry).
21    fn name(&self) -> &str;
22
23    /// Endpoints to register with EndpointRegistry.
24    ///
25    /// Each tuple is (SocketKind, TransportConfig).
26    /// - Handlers typically register one REP endpoint
27    /// - Proxies register PUB and SUB endpoints (note socket type inversion)
28    fn registrations(&self) -> Vec<(SocketKind, TransportConfig)>;
29
30    /// Run the service on current thread (blocking).
31    ///
32    /// Called by spawner after thread/process setup.
33    /// Should block until shutdown is signaled.
34    ///
35    /// # Arguments
36    /// * `shutdown` - Notification to signal service shutdown
37    /// * `on_ready` - Optional oneshot sender to signal when socket is bound and ready
38    fn run(
39        self: Box<Self>,
40        shutdown: Arc<Notify>,
41        on_ready: Option<tokio::sync::oneshot::Sender<()>>,
42    ) -> Result<()>;
43}
44
45// ============================================================================
46// Blanket Spawnable impl for RequestService
47// ============================================================================
48
49/// Every `RequestService + Send + Sync` is automatically `Spawnable`.
50///
51/// This blanket implementation eliminates the need for wrapper types.
52/// Services that implement `RequestService` include their infrastructure
53/// (context, transport, verifying_key) and can be spawned directly.
54///
55/// Services not satisfying `Send + Sync` (e.g., those using `Rc` or `!Send` fields)
56/// must implement `Spawnable` directly (as `InferenceServiceConfig` does).
57impl<S: RequestService + Send + Sync> Spawnable for S {
58    fn name(&self) -> &str {
59        RequestService::name(self)
60    }
61
62    fn registrations(&self) -> Vec<(SocketKind, TransportConfig)> {
63        vec![(SocketKind::Rep, RequestService::transport(self).clone())]
64    }
65
66    fn run(
67        self: Box<Self>,
68        shutdown: Arc<Notify>,
69        on_ready: Option<tokio::sync::oneshot::Sender<()>>,
70    ) -> Result<()> {
71        let transport = RequestService::transport(&*self).clone();
72        let signing_key = RequestService::signing_key(&*self);
73
74        let rt = tokio::runtime::Builder::new_multi_thread()
75            .enable_all()
76            .build()
77            .map_err(|e| RpcError::SpawnFailed(format!("runtime: {e}")))?;
78
79        // Post-ZMQ serve (#136): bridge the service to a Send processor on its own
80        // LocalSet thread, then serve it over its registered transport (inproc →
81        // in-memory dial registry; ipc/systemd → UdsRpcServer). No ZMQ ROUTER.
82        rt.block_on(async move {
83            let nonce_cache = Arc::new(crate::envelope::InMemoryNonceCache::new());
84            let bridge =
85                crate::transport::iroh_rpc::LocalServiceBridge::spawn(*self, nonce_cache, 0)
86                    .map_err(|e| RpcError::SpawnFailed(format!("bridge: {e}")))?;
87            let bridge = Arc::new(bridge);
88            let processor: Arc<dyn crate::transport::rpc_session::IrohRequestProcessor> =
89                bridge.clone();
90            let result = crate::service::serve::serve_bridged(
91                &transport,
92                processor,
93                signing_key,
94                shutdown,
95                on_ready,
96            )
97            .await
98            .map_err(|e| RpcError::SpawnFailed(e.to_string()));
99            let teardown = bridge.shutdown().await.map_err(|error| {
100                tracing::error!(%error, "bridge shutdown failed");
101                RpcError::SpawnFailed(error.to_string())
102            });
103            // Always join, while retaining the earlier serving error if both fail.
104            result.and(teardown)
105        })
106    }
107}