Skip to main content

hyprstream_rpc/service/
serve.rs

1//! Bridged serve helper for the post-ZMQ spawn path (#136).
2//!
3//! The RPC cutover replaces every `RequestLoop::new(..).run(service)` (ZMQ
4//! ROUTER) with this: bridge the service to a `Send` processor
5//! ([`LocalServiceBridge`](crate::transport::iroh_rpc::LocalServiceBridge)), then
6//! serve it over its *registered* transport via the same `process_request`
7//! dispatch core the quinn/iroh planes use.
8//!
9//! Spawn-path transports (from `EndpointRegistry::endpoint(name, Rep)`):
10//! - `Inproc{endpoint}` (default daemon mode) → register the processor in the
11//!   in-memory dial registry ([`register_inproc`](crate::dial::register_inproc));
12//!   **no socket**. The registry holds only a `Weak`, so the strong `processor`
13//!   `Arc` is retained here for the service's lifetime.
14//! - `Ipc{path}` (`--ipc`) → bind a `UnixListener` at `path`, run
15//!   [`UdsRpcServer`].
16//! - `SystemdFd{fd,..}` → adopt the systemd-passed listener fd, run [`UdsRpcServer`].
17//! - `Quic`/`Iroh` are *dialed*, never bound on the spawn path → error.
18
19use std::sync::Arc;
20
21use anyhow::{anyhow, bail, Result};
22use ed25519_dalek::SigningKey;
23use tokio::sync::Notify;
24
25use crate::transport::rpc_session::{IrohRequestProcessor, DEFAULT_STREAM_LIMIT};
26use crate::transport::uds_server::UdsRpcServer;
27use crate::transport::{EndpointType, TransportConfig};
28
29/// Signal startup readiness: fire the `on_ready` oneshot (spawner waits on it)
30/// and notify systemd (`Type=notify`).
31fn signal_ready(on_ready: Option<tokio::sync::oneshot::Sender<()>>, notify_systemd: bool) {
32    if let Some(tx) = on_ready {
33        let _ = tx.send(());
34    }
35    if notify_systemd {
36        let _ = crate::notify::ready();
37    }
38}
39
40/// Serve a bridged request `processor` over its registered `transport` until
41/// `shutdown` fires. See the module docs for the per-transport behaviour.
42///
43/// `processor` MUST be the bridge wrapping the spawn-path service (built via
44/// [`LocalServiceBridge::spawn`](crate::transport::iroh_rpc::LocalServiceBridge::spawn)
45/// or `spawn_with`). This fn holds it for the serve lifetime.
46pub async fn serve_bridged(
47    transport: &TransportConfig,
48    processor: Arc<dyn IrohRequestProcessor>,
49    signing_key: SigningKey,
50    shutdown: Arc<Notify>,
51    on_ready: Option<tokio::sync::oneshot::Sender<()>>,
52) -> Result<()> {
53    serve_bridged_with_shutdown_armed(transport, processor, signing_key, shutdown, on_ready, None)
54        .await
55}
56
57/// Variant of [`serve_bridged`] that acknowledges after the shutdown waiter is
58/// registered, before startup readiness is signalled. This closes the window
59/// where an owner can notify shutdown after readiness but before the helper has
60/// begun waiting on the shared [`Notify`].
61pub async fn serve_bridged_with_shutdown_armed(
62    transport: &TransportConfig,
63    processor: Arc<dyn IrohRequestProcessor>,
64    signing_key: SigningKey,
65    shutdown: Arc<Notify>,
66    on_ready: Option<tokio::sync::oneshot::Sender<()>>,
67    shutdown_armed: Option<tokio::sync::oneshot::Sender<()>>,
68) -> Result<()> {
69    serve_bridged_with_shutdown_armed_impl(
70        transport,
71        processor,
72        signing_key,
73        shutdown,
74        on_ready,
75        shutdown_armed,
76        true,
77    )
78    .await
79}
80
81/// Variant of [`serve_bridged_with_shutdown_armed`] for nested helpers whose
82/// parent owns the service readiness boundary. It acknowledges the shutdown
83/// waiter but does not emit a systemd `READY=1` notification.
84pub async fn serve_bridged_with_shutdown_armed_silent(
85    transport: &TransportConfig,
86    processor: Arc<dyn IrohRequestProcessor>,
87    signing_key: SigningKey,
88    shutdown: Arc<Notify>,
89    on_ready: Option<tokio::sync::oneshot::Sender<()>>,
90    shutdown_armed: Option<tokio::sync::oneshot::Sender<()>>,
91) -> Result<()> {
92    serve_bridged_with_shutdown_armed_impl(
93        transport,
94        processor,
95        signing_key,
96        shutdown,
97        on_ready,
98        shutdown_armed,
99        false,
100    )
101    .await
102}
103
104async fn serve_bridged_with_shutdown_armed_impl(
105    transport: &TransportConfig,
106    processor: Arc<dyn IrohRequestProcessor>,
107    signing_key: SigningKey,
108    shutdown: Arc<Notify>,
109    on_ready: Option<tokio::sync::oneshot::Sender<()>>,
110    shutdown_armed: Option<tokio::sync::oneshot::Sender<()>>,
111    notify_systemd: bool,
112) -> Result<()> {
113    match &transport.endpoint {
114        EndpointType::Inproc { endpoint } => {
115            crate::dial::register_inproc(endpoint.clone(), &processor);
116            let notified = shutdown.notified();
117            tokio::pin!(notified);
118            notified.as_mut().enable();
119            if let Some(tx) = shutdown_armed {
120                let _ = tx.send(());
121            }
122            signal_ready(on_ready, notify_systemd);
123            notified.await;
124            processor.close_admission();
125            crate::dial::unregister_inproc(endpoint);
126            // The service owner drains and joins, even with retained clients.
127            drop(processor);
128            Ok(())
129        }
130        EndpointType::Ipc { path } => {
131            if let Some(parent) = path.parent() {
132                std::fs::create_dir_all(parent)
133                    .map_err(|e| anyhow!("create uds dir {}: {e}", parent.display()))?;
134            }
135            // Clear a stale socket left by a prior unclean shutdown.
136            let _ = std::fs::remove_file(path);
137            let listener = tokio::net::UnixListener::bind(path)
138                .map_err(|e| anyhow!("bind uds {}: {e}", path.display()))?;
139            // Restrict to owner-only access (#207): world-accessible sockets would
140            // let any local process connect, undermining same-host trust isolation.
141            {
142                use std::os::unix::fs::PermissionsExt;
143                std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
144                    .map_err(|e| anyhow!("set uds perms {}: {e}", path.display()))?;
145            }
146            run_uds(
147                listener,
148                processor,
149                signing_key,
150                shutdown,
151                on_ready,
152                shutdown_armed,
153                notify_systemd,
154            )
155            .await
156        }
157        EndpointType::SystemdFd { fd, .. } => {
158            use std::os::unix::io::FromRawFd;
159            // The fd is the systemd-passed, already-bound server listener.
160            let std_listener = unsafe { std::os::unix::net::UnixListener::from_raw_fd(*fd) };
161            std_listener
162                .set_nonblocking(true)
163                .map_err(|e| anyhow!("systemd fd set_nonblocking: {e}"))?;
164            let listener = tokio::net::UnixListener::from_std(std_listener)
165                .map_err(|e| anyhow!("adopt systemd uds fd: {e}"))?;
166            run_uds(
167                listener,
168                processor,
169                signing_key,
170                shutdown,
171                on_ready,
172                shutdown_armed,
173                notify_systemd,
174            )
175            .await
176        }
177        other => bail!(
178            "serve_bridged: {other:?} is not a spawn-path RPC endpoint \
179             (Quic/Iroh are dialed via dial(), not bound here)"
180        ),
181    }
182}
183
184/// Run a [`UdsRpcServer`] until it ends or `shutdown` fires (graceful drain).
185async fn run_uds(
186    listener: tokio::net::UnixListener,
187    processor: Arc<dyn IrohRequestProcessor>,
188    signing_key: SigningKey,
189    shutdown: Arc<Notify>,
190    on_ready: Option<tokio::sync::oneshot::Sender<()>>,
191    shutdown_armed: Option<tokio::sync::oneshot::Sender<()>>,
192    notify_systemd: bool,
193) -> Result<()> {
194    let server = UdsRpcServer::with_capacity(
195        listener,
196        Arc::clone(&processor),
197        signing_key,
198        DEFAULT_STREAM_LIMIT,
199    );
200    let token = server.shutdown_token();
201    let limit = server.stream_limit();
202    let cap = server.capacity();
203    let notified = shutdown.notified();
204    tokio::pin!(notified);
205    notified.as_mut().enable();
206    if let Some(tx) = shutdown_armed {
207        let _ = tx.send(());
208    }
209    signal_ready(on_ready, notify_systemd);
210    tokio::select! {
211        r = server.run() => r,
212        _ = notified => {
213            let deadline = processor.begin_shutdown(
214                tokio::time::Instant::now() + crate::transport::rpc_session::DRAIN_TIMEOUT,
215            );
216            UdsRpcServer::shutdown_until(&limit, cap, &token, deadline).await;
217            Ok(())
218        }
219    }
220}