hyprstream_rpc/transport/rpc_session.rs
1//! Transport-generic RPC plane core — Epic #131 / moq M1 (#151).
2//!
3//! This module generalises the iroh-specific RPC server/client (originally in
4//! [`super::iroh_rpc`] and [`super::iroh_transport`]) over the
5//! [`web_transport_trait::Session`] abstraction, so the RPC plane is
6//! transport-pluggable: any `Session` impl (iroh's `web-transport-iroh`,
7//! quinn's `web-transport-quinn`, or a future WASM `web-transport-web`) can
8//! carry the exact same Cap'n Proto bidi wire protocol with identical DoS
9//! bounds, graceful-drain, and error-envelope semantics.
10//!
11//! - [`serve_rpc_connection`] — the generic server accept loop. Terminates
12//! `SignedEnvelope` bidi streams on a [`Session`], dispatches each through an
13//! [`IrohRequestProcessor`], caps concurrent streams per connection (DoS
14//! bound) and drains in-flight requests on `shutdown`.
15//! - [`SessionRpcTransport`] — the generic client transport implementing
16//! [`crate::transport_traits::Transport`] over a [`Session`]. Each `send()`
17//! opens a fresh bidi stream.
18//! - [`IrohRequestProcessor`] — the pluggable request-processing trait
19//! (retained under its original name to avoid churn in callers).
20//! - [`build_error_envelope`] — signed error-envelope synthesis.
21//!
22//! **Wire framing**: each request/response is the opaque bytes of a
23//! Cap'n Proto-encoded envelope written to a freshly-opened bidi stream. The
24//! length is delimited by stream FIN (no explicit length prefix); reads are
25//! bounded by [`MAX_FRAME_BYTES`] via [`read_to_cap`].
26
27use std::future::Future;
28use std::sync::Arc;
29use std::time::Duration;
30
31use anyhow::{anyhow, bail, Result};
32use async_trait::async_trait;
33use bytes::Bytes;
34use ed25519_dalek::SigningKey;
35use tokio::sync::Semaphore;
36use tokio_util::sync::CancellationToken;
37use web_transport_trait::{RecvStream, SendStream, Session};
38
39use crate::transport::carrier::CarrierContext;
40use crate::transport_traits::{PublishSink, Transport};
41
42/// Hard cap on per-frame size (request or response) for the RPC control plane.
43///
44/// SECURITY (#162): the original 64 MiB cap would let an attacker buffer up to
45/// `64 MiB × DEFAULT_STREAM_LIMIT` (= 4 GiB) across concurrent streams before
46/// any application-layer rejection. The RPC plane carries control messages only
47/// (SQL queries, metric batches, Cap'n Proto envelopes) — no ingest blobs,
48/// no streaming chunks. Those belong on the streaming ALPN (moq-net). 4 MiB is
49/// generous for any realistic control-plane payload.
50pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024; // 4 MiB
51
52/// Default concurrent-stream cap. NOTE: the `Arc<Semaphore>` this sizes is
53/// shared **server-wide** across all connections (one `Arc<HandlerInner>`),
54/// not per-connection — so this bounds total in-flight streams for the whole
55/// server, capping memory to `MAX_FRAME_BYTES × DEFAULT_STREAM_LIMIT` = 256 MiB.
56pub const DEFAULT_STREAM_LIMIT: usize = 64;
57
58/// Grace period for [`SendStream::closed`] after writing the response — if
59/// the peer crashes without acking the FIN, we don't leak a task forever.
60pub const STOPPED_GRACE: Duration = Duration::from_secs(5);
61
62/// Maximum wall-clock time the server will spend reading a single request
63/// frame before abandoning the stream and releasing its semaphore permit.
64///
65/// SECURITY (#159): without this bound an UNAUTHENTICATED peer can open
66/// `DEFAULT_STREAM_LIMIT` bidi streams, send one byte on each, and stall —
67/// each stalled read holds a server-wide permit forever, wedging the whole
68/// server before any envelope is verified (a pre-auth slowloris) and hanging
69/// the shutdown drain. Bounding the *total* read (not just per-`read()` idle)
70/// also defeats a trickle attacker who dribbles one byte per idle window.
71pub const REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(30);
72
73/// Default per-call timeout on the client side when the caller passes `None`.
74/// Distinct from [`REQUEST_READ_TIMEOUT`] (server-side per-request read budget).
75const DEFAULT_CLIENT_TIMEOUT: Duration = Duration::from_secs(30);
76
77/// Upper bound on how long graceful shutdown waits for in-flight streams to
78/// drain before forcing teardown. With [`REQUEST_READ_TIMEOUT`] bounding each
79/// read, well-behaved drains finish quickly; this is a backstop so a wedged
80/// processor or transport can't hang shutdown forever (#159).
81///
82/// Must exceed [`REQUEST_READ_TIMEOUT`] (30 s) so in-flight requests can finish
83/// before the connection tears down. The 10 s margin is intentional.
84pub const DRAIN_TIMEOUT: Duration = Duration::from_secs(40);
85
86/// Default cap on concurrent accepted connections per server (#162). Bounds
87/// fd/memory from a peer that opens many connections that each sit idle (no
88/// streams) — the per-stream [`DEFAULT_STREAM_LIMIT`] does not cover that.
89/// Connections beyond the cap are rejected (dropped) rather than queued, so a
90/// flood can't build unbounded backpressure.
91pub const DEFAULT_CONNECTION_LIMIT: usize = 256;
92
93/// Maximum time the server waits for a peer's WebTransport/QUIC handshake to
94/// complete before abandoning it (#162). Bounds a peer that completes the QUIC
95/// handshake then stalls the WebTransport CONNECT. Resolved inside the
96/// per-connection task so a slow handshake never blocks the accept loop.
97pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15);
98
99// ============================================================================
100// RpcConfig — unified server-side tunables (#197)
101// ============================================================================
102
103/// Unified RPC transport tunables for server builders.
104///
105/// All values default to the process-global constants; override via
106/// `with_rpc_config()` on any server builder. This consolidates the
107/// previously scattered `with_stream_limit` / `with_connection_limit` /
108/// `with_read_timeout` builder methods behind one struct so a single
109/// config source (e.g. a loaded `HyprConfig`) can tune all planes at once.
110#[derive(Clone, Debug)]
111pub struct RpcConfig {
112 /// Max concurrent in-flight bidi streams (server-wide semaphore).
113 pub stream_limit: usize,
114 /// Max concurrent accepted connections per server.
115 pub connection_limit: usize,
116 /// Max wall-clock time to read a single request frame.
117 pub request_read_timeout: Duration,
118 /// Max time for a peer's QUIC/WebTransport handshake to complete.
119 pub handshake_timeout: Duration,
120 /// Grace period after writing a response for the peer to ack FIN.
121 pub stopped_grace: Duration,
122 /// Max wall-clock time for graceful drain on shutdown.
123 pub drain_timeout: Duration,
124}
125
126impl Default for RpcConfig {
127 fn default() -> Self {
128 Self {
129 stream_limit: DEFAULT_STREAM_LIMIT,
130 connection_limit: DEFAULT_CONNECTION_LIMIT,
131 request_read_timeout: REQUEST_READ_TIMEOUT,
132 handshake_timeout: HANDSHAKE_TIMEOUT,
133 stopped_grace: STOPPED_GRACE,
134 drain_timeout: DRAIN_TIMEOUT,
135 }
136 }
137}
138
139// ============================================================================
140// IrohRequestProcessor — sealed request handling trait
141// ============================================================================
142
143pub(crate) mod sealed {
144 pub trait Sealed {
145 /// True only for the crate-owned canonical envelope pipeline.
146 fn admits_untrusted_carrier(&self) -> bool;
147 }
148}
149
150/// Sealed trait used to wire actual request processing.
151///
152/// The processor receives the raw request bytes (a Cap'n Proto-encoded
153/// `SignedEnvelope`) and returns the raw response bytes.
154///
155/// **Contract for `process`**:
156/// - **`Ok(bytes)`** — `bytes` MUST be a valid Cap'n Proto-encoded
157/// `ResponseEnvelope` and is written verbatim to the bidi stream.
158/// Application-layer errors (verification failure, handler error, etc.)
159/// MUST be returned this way as signed error envelopes — the server
160/// forwards them unchanged.
161/// - **`Err(_)`** — admission or wire-level fatal. Untrusted network carriers
162/// silently reset/drop the stream so unauthenticated input cannot trigger a
163/// signed response. Trusted local carriers retain the legacy signed stub
164/// error for transport-only callers.
165///
166/// Implementations are crate-owned so arbitrary raw-byte callbacks cannot
167/// become an application-facing network boundary. Services use
168/// [`super::iroh_rpc::LocalServiceBridge`], including `!Send` services.
169///
170/// The `carrier` argument is the accept boundary's attestation of which
171/// carrier class the request arrived on (INV-2 receive side, #1042). It is a
172/// **required** parameter — a processor cannot be invoked without a carrier
173/// classification, so a forgotten context is a compile error, not a silent
174/// fail-open. On an untrusted carrier, the serve loop invokes only the
175/// crate-owned canonical [`dispatch`] processor.
176///
177/// [`dispatch`]: crate::service::dispatch::process_request
178///
179/// (Name retained from the iroh-only era to avoid churn in callers.)
180pub trait IrohRequestProcessor: sealed::Sealed + Send + Sync + 'static {
181 /// Close service admission before removing an in-process endpoint. The
182 /// owning bridge performs the bounded drain and join separately.
183 fn close_admission(&self) {
184 self.begin_shutdown(tokio::time::Instant::now() + DRAIN_TIMEOUT);
185 }
186
187 /// Close admission and establish one absolute request-drain deadline. A
188 /// bridge returns its first deadline so later carrier/owner calls cannot
189 /// restart the grace period. Joining remains the service owner's duty.
190 fn begin_shutdown(&self, deadline: tokio::time::Instant) -> tokio::time::Instant {
191 deadline
192 }
193
194 fn process(
195 &self,
196 request: Bytes,
197 carrier: CarrierContext,
198 ) -> std::pin::Pin<Box<dyn Future<Output = Result<Bytes>> + Send + '_>>;
199}
200
201/// Convenience: build an [`IrohRequestProcessor`] from a `Send + Sync`
202/// async closure. Useful for tests.
203/// The closure is carrier-agnostic and is therefore restricted to trusted
204/// inproc/UDS carriers. It cannot receive bytes from an untrusted carrier.
205pub fn from_fn<F, Fut>(f: F) -> impl IrohRequestProcessor
206where
207 F: Fn(Bytes) -> Fut + Send + Sync + 'static,
208 Fut: Future<Output = Result<Bytes>> + Send + 'static,
209{
210 struct FnProcessor<F>(F);
211 impl<F> sealed::Sealed for FnProcessor<F> {
212 fn admits_untrusted_carrier(&self) -> bool {
213 false
214 }
215 }
216 impl<F, Fut> IrohRequestProcessor for FnProcessor<F>
217 where
218 F: Fn(Bytes) -> Fut + Send + Sync + 'static,
219 Fut: Future<Output = Result<Bytes>> + Send + 'static,
220 {
221 fn process(
222 &self,
223 request: Bytes,
224 _carrier: CarrierContext,
225 ) -> std::pin::Pin<Box<dyn Future<Output = Result<Bytes>> + Send + '_>> {
226 Box::pin((self.0)(request))
227 }
228 }
229 FnProcessor(f)
230}
231
232// ============================================================================
233// Bounded read helper
234// ============================================================================
235
236/// Read an entire stream into [`Bytes`], capping the total at `cap` bytes.
237///
238/// Uses [`RecvStream::read_chunk`] (a defaulted trait method): quinn and iroh
239/// override it to return `Bytes` referencing the QUIC receive buffer, so a
240/// control message that arrives as a **single chunk** (the common case) is
241/// returned **fully zero-copy** — no allocation, no copy. The UDS impl inherits
242/// the trait's one-copy default (local socket, fine). Multi-chunk frames pay at
243/// most one concatenation. Errors out if the peer sends more than `cap` bytes
244/// before FIN (`RecvStream::read_all` is unbounded — a hostile peer could
245/// exhaust memory with it).
246///
247/// This is the **control plane** (`MAX_FRAME_BYTES` = 4 MiB). Bulk/tensor
248/// payloads ride the streaming plane, where moq-net already yields `Bytes`.
249pub async fn read_to_cap<R: RecvStream>(recv: &mut R, cap: usize) -> Result<Bytes> {
250 let mut first: Option<Bytes> = None;
251 let mut acc: Option<bytes::BytesMut> = None;
252 let mut total: usize = 0;
253 loop {
254 // +1 so a chunk that would push us over `cap` is still surfaced, then rejected.
255 let max = cap.saturating_sub(total).saturating_add(1);
256 match recv
257 .read_chunk(max)
258 .await
259 .map_err(|e| anyhow!("recv read_chunk: {e}"))?
260 {
261 None => break, // FIN
262 Some(chunk) if chunk.is_empty() => continue,
263 Some(chunk) => {
264 total += chunk.len();
265 if total > cap {
266 bail!("frame exceeds {cap} byte cap");
267 }
268 match (first.take(), acc.as_mut()) {
269 // Keep the first chunk as-is (zero-copy if it's the only one).
270 (None, None) => first = Some(chunk),
271 // Second chunk: start accumulating from the held first.
272 (Some(f), None) => {
273 let mut b = bytes::BytesMut::with_capacity(total);
274 b.extend_from_slice(&f);
275 b.extend_from_slice(&chunk);
276 acc = Some(b);
277 }
278 (None, Some(b)) => b.extend_from_slice(&chunk),
279 (Some(_), Some(_)) => unreachable!("first is taken once acc exists"),
280 }
281 }
282 }
283 }
284 Ok(match (first, acc) {
285 (Some(f), None) => f, // single chunk: fully zero-copy
286 (None, Some(b)) => b.freeze(), // multi-chunk: one concatenation
287 _ => Bytes::new(), // empty / FIN-first
288 })
289}
290
291// ============================================================================
292// serve_rpc_connection — transport-generic server accept loop
293// ============================================================================
294
295/// Serve one accepted [`Session`] until the peer closes it or `shutdown` is
296/// cancelled. Terminates `hyprstream-rpc/1`-style bidi streams, caps concurrent
297/// streams via the shared `stream_limit`, and (in concert with the caller's
298/// drain on that same `stream_limit`) drains in-flight requests on shutdown.
299///
300/// The caller owns the drain: it holds the same `Arc<Semaphore>` and, on
301/// shutdown, cancels `shutdown` then `acquire_many(capacity)`s every permit so
302/// detached `handle_stream` tasks finish before teardown. This fn only acquires
303/// one per-stream permit per accepted bidi stream.
304///
305/// `carrier` is the accept boundary's classification of this session's
306/// carrier (INV-2 receive side, #1042). Untrusted carriers may invoke only the
307/// crate-owned canonical envelope processor; raw closure processors are
308/// silently refused before their callback can observe request bytes.
309pub async fn serve_rpc_connection<S>(
310 session: S,
311 processor: Arc<dyn IrohRequestProcessor>,
312 signing_key: SigningKey,
313 stream_limit: Arc<Semaphore>,
314 read_timeout: Duration,
315 shutdown: CancellationToken,
316 carrier: CarrierContext,
317) -> Result<()>
318where
319 S: Session,
320{
321 loop {
322 tokio::select! {
323 biased;
324 _ = shutdown.cancelled() => {
325 tracing::debug!("rpc-session: accept loop cancelled");
326 return Ok(());
327 }
328 streams = session.accept_bi() => {
329 let (send, recv) = match streams {
330 Ok(pair) => pair,
331 Err(e) => {
332 tracing::debug!(error = ?e, "rpc-session: connection closed");
333 return Ok(());
334 }
335 };
336
337 // Acquire a permit to cap concurrent streams. If the semaphore
338 // is closed (shutdown drained it), exit cleanly.
339 let permit = match Arc::clone(&stream_limit).acquire_owned().await {
340 Ok(p) => p,
341 Err(_) => return Ok(()),
342 };
343
344 let processor = Arc::clone(&processor);
345 let signing_key = signing_key.clone();
346 // Hold a clone of the session in the per-stream task so the
347 // underlying QUIC connection stays alive until the response is
348 // fully written, even if the accept loop exits first on
349 // shutdown (some `Session` impls — e.g. web-transport-quinn —
350 // close the connection when the last `Session` handle drops).
351 let session_keepalive = session.clone();
352 tokio::spawn(async move {
353 let _permit = permit; // released on task end
354 let _keepalive = session_keepalive;
355 handle_stream::<S>(send, recv, processor, signing_key, read_timeout, carrier)
356 .await;
357 });
358 }
359 }
360 }
361}
362
363/// Strictly decode a browser RPC request: one ZMTP `STREAM_TYPE=REQ` command
364/// followed by exactly one multipart frame carrying the sealed envelope, with
365/// no trailing bytes.
366fn decode_browser_zmtp_request(request: &[u8]) -> Result<Bytes> {
367 let (command_frame, command_len) = crate::zmtp_framing::decode_frame(request)?;
368 anyhow::ensure!(
369 command_frame.command,
370 "browser request omitted STREAM_TYPE command"
371 );
372 let command = crate::zmtp_framing::ZmtpCommand::parse(&command_frame.data)?;
373 anyhow::ensure!(
374 command.name == "STREAM_TYPE" && command.body == b"REQ",
375 "browser RPC stream must declare STREAM_TYPE=REQ"
376 );
377 let (parts, consumed) = crate::zmtp_framing::decode_multipart(&request[command_len..])?;
378 anyhow::ensure!(
379 command_len + consumed == request.len(),
380 "browser RPC request has trailing bytes"
381 );
382 let mut parts = parts.into_iter();
383 match (parts.next(), parts.next()) {
384 (Some(envelope), None) => Ok(Bytes::from(envelope)),
385 _ => anyhow::bail!("browser RPC request must contain one frame"),
386 }
387}
388
389/// Handle one bidi stream end-to-end: read request, dispatch to the admitted
390/// processor, and write its response. Admission failures on untrusted carriers
391/// are silently dropped; trusted-local processor failures get a signed stub.
392async fn handle_stream<S>(
393 mut send: S::SendStream,
394 mut recv: S::RecvStream,
395 processor: Arc<dyn IrohRequestProcessor>,
396 signing_key: SigningKey,
397 read_timeout: Duration,
398 carrier: CarrierContext,
399) where
400 S: Session,
401{
402 // SECURITY (#159): bound the request read in wall-clock time. On timeout
403 // we return, dropping `recv`/`send` (which resets the stream) and releasing
404 // the semaphore permit held by the caller — so a stalled/trickling peer
405 // cannot pin a server-wide permit indefinitely.
406 let request =
407 match tokio::time::timeout(read_timeout, read_to_cap(&mut recv, MAX_FRAME_BYTES)).await {
408 Ok(Ok(buf)) => buf,
409 Ok(Err(e)) => {
410 tracing::warn!(error = ?e, "rpc-session: failed reading request");
411 return;
412 }
413 Err(_) => {
414 tracing::warn!(
415 timeout = ?read_timeout,
416 "rpc-session: request read timed out, abandoning stream"
417 );
418 return;
419 }
420 };
421 let request = if carrier.requires_browser_provisioning() {
422 match decode_browser_zmtp_request(&request) {
423 Ok(request) => request,
424 Err(error) => {
425 tracing::warn!(?error, "rpc-session: invalid browser ZMTP request");
426 return;
427 }
428 }
429 } else {
430 request
431 };
432
433 // A raw/custom callback must never become the application boundary for a
434 // network carrier. Only the sealed canonical bridge is allowed to receive
435 // such bytes; it performs bounded parsing, authentication, replay checks,
436 // INV-2 enforcement, and KEM open before handler dispatch.
437 if carrier.forbids_cleartext_envelope() && !processor.admits_untrusted_carrier() {
438 tracing::warn!(
439 carrier = %carrier,
440 "rpc-session: refusing non-canonical raw processor on untrusted carrier"
441 );
442 return;
443 }
444
445 let response = match processor.process(request, carrier).await {
446 Ok(bytes) => bytes,
447 Err(e) if carrier.forbids_cleartext_envelope() => {
448 // Do not sign responses to input that failed canonical network
449 // admission: malformed, unauthenticated, replayed, cleartext, and
450 // undecryptable requests all reset/drop silently.
451 tracing::warn!(
452 error = ?e,
453 carrier = %carrier,
454 "rpc-session: silently dropping request that failed canonical admission"
455 );
456 return;
457 }
458 Err(e) => {
459 tracing::warn!(error = ?e, "rpc-session: trusted-carrier processor error, sending stub error envelope");
460 let pq_signing_key = crate::node_identity::derive_mesh_mldsa_key(&signing_key);
461 build_error_envelope(
462 &signing_key,
463 &pq_signing_key,
464 &format!("processor error: {e}"),
465 )
466 }
467 };
468
469 let response = if carrier.requires_browser_provisioning() {
470 Bytes::from(crate::zmtp_framing::encode_multipart(&[response.as_ref()]))
471 } else {
472 response
473 };
474
475 // Zero-copy reply: `write_chunk` takes the `Bytes` by value; quinn/iroh write it
476 // without copying the buffer (UDS falls back to the trait default). The response
477 // envelope is moved, never cloned.
478 if let Err(e) = send.write_chunk(response).await {
479 tracing::warn!(error = ?e, "rpc-session: failed writing response");
480 return;
481 }
482 if let Err(e) = send.finish() {
483 tracing::warn!(error = ?e, "rpc-session: failed finishing send");
484 return;
485 }
486 // Wait for the peer to ack the FIN, but cap it so a dead peer can't leak
487 // this task forever.
488 let _ = tokio::time::timeout(STOPPED_GRACE, send.closed()).await;
489}
490
491/// Build a signed `ResponseEnvelope` (request_id = 0) carrying `message` as
492/// the payload. Used when the processor itself fails — guarantees the client
493/// sees a parseable envelope rather than EOF.
494///
495/// #275: emits the mandatory Hybrid COSE composite. Callers must supply both
496/// signing components; this constructor has no classical fallback.
497pub fn build_error_envelope(
498 signing_key: &SigningKey,
499 pq_signing_key: &crate::crypto::pq::MlDsaSigningKey,
500 message: &str,
501) -> Bytes {
502 use crate::ToCapnp;
503 use capnp::{message::Builder, serialize};
504 let envelope = match crate::envelope::ResponseEnvelope::new_signed_with_policy(
505 0,
506 message.as_bytes().to_vec(),
507 signing_key,
508 Some(pq_signing_key),
509 crate::crypto::CryptoPolicy::Hybrid,
510 ) {
511 Ok(envelope) => envelope,
512 Err(e) => {
513 // Fail closed: never substitute a weaker envelope. The client sees
514 // EOF instead of a signed error response.
515 tracing::error!(error = ?e, "rpc-session: failed signing error envelope");
516 return Bytes::new();
517 }
518 };
519 let mut msg = Builder::new_default();
520 {
521 let mut builder = msg.init_root::<crate::common_capnp::response_envelope::Builder>();
522 envelope.write_to(&mut builder);
523 }
524 let mut bytes = Vec::new();
525 if let Err(e) = serialize::write_message(&mut bytes, &msg) {
526 // Last-ditch: if even this fails, return empty bytes — client will see
527 // a Cap'n Proto parse error, which is no worse than the original
528 // behaviour. This should be unreachable in practice.
529 tracing::error!(error = ?e, "rpc-session: failed serializing error envelope");
530 return Bytes::new();
531 }
532 Bytes::from(bytes)
533}
534
535// ============================================================================
536// SessionRpcTransport — transport-generic client
537// ============================================================================
538
539/// Wraps a [`web_transport_trait::Session`] as a [`Transport`] for RPC plane
540/// traffic. Generic over the session impl, so the same client logic rides iroh,
541/// quinn, or any future `Session` backend.
542///
543/// Clone-cheap — `Session` is `Clone` (reference-counted internally by the
544/// underlying QUIC connection).
545#[derive(Clone)]
546pub struct SessionRpcTransport<S: Session> {
547 session: S,
548}
549
550impl<S: Session> SessionRpcTransport<S> {
551 /// Build from an already-established session on the RPC ALPN.
552 pub fn new(session: S) -> Self {
553 Self { session }
554 }
555
556 /// Borrow the underlying session (e.g. for inspection).
557 pub fn session(&self) -> &S {
558 &self.session
559 }
560}
561
562/// Stub stream type for [`Transport::Sub`]. Always pending — the RPC plane does
563/// not carry SUB-style topic streams; those live on the streaming plane.
564pub type RpcPendingStream = futures::stream::Pending<Result<Vec<Vec<u8>>>>;
565
566/// Stub publish sink for [`Transport::Pub`]. Errors on any `send_frames` call;
567/// the RPC plane is request-response only.
568pub struct RpcPublishStub;
569
570#[async_trait]
571impl PublishSink for RpcPublishStub {
572 async fn send_frames(&self, _frames: &[&[u8]]) -> Result<()> {
573 bail!("RPC plane does not support PUB/PUSH — use moq-net on the streaming ALPN")
574 }
575}
576
577#[async_trait]
578impl<S: Session> Transport for SessionRpcTransport<S> {
579 type Sub = RpcPendingStream;
580 type Pub = RpcPublishStub;
581
582 async fn send(&self, payload: Vec<u8>, timeout_ms: Option<i32>) -> Result<Vec<u8>> {
583 let timeout = timeout_ms
584 .map(|ms| Duration::from_millis(ms.max(0) as u64))
585 .unwrap_or(DEFAULT_CLIENT_TIMEOUT);
586 let session = self.session.clone();
587 let fut = async move {
588 let (mut send, mut recv) = session
589 .open_bi()
590 .await
591 .map_err(|e| anyhow!("session open_bi: {e}"))?;
592 // Zero-copy request: `Bytes::from(Vec)` is a move (no copy), and
593 // `write_chunk` writes it without copying on quinn/iroh.
594 send.write_chunk(bytes::Bytes::from(payload))
595 .await
596 .map_err(|e| anyhow!("session write_chunk: {e}"))?;
597 send.finish().map_err(|e| anyhow!("session finish: {e}"))?;
598 let buf = read_to_cap(&mut recv, MAX_FRAME_BYTES).await?;
599 Ok::<Vec<u8>, anyhow::Error>(buf.to_vec())
600 };
601 tokio::time::timeout(timeout, fut)
602 .await
603 .map_err(|_| anyhow!("RPC timeout after {timeout:?}"))?
604 }
605
606 async fn subscribe(&self, _topic: &[u8]) -> Result<Self::Sub> {
607 bail!("RPC plane does not support SUB — use moq-net on the streaming ALPN")
608 }
609
610 async fn publish(&self, _topic: &[u8]) -> Result<Self::Pub> {
611 bail!("RPC plane does not support PUB — use moq-net on the streaming ALPN")
612 }
613}
614
615#[cfg(test)]
616#[allow(clippy::expect_used)]
617mod browser_zmtp_tests {
618 use super::*;
619
620 #[test]
621 fn browser_rpc_framing_is_strict_and_returns_only_the_envelope() {
622 let command = crate::zmtp_framing::encode_command("STREAM_TYPE", b"REQ");
623 let multipart = crate::zmtp_framing::encode_multipart(&[b"sealed-envelope"]);
624 let mut wire = command;
625 wire.extend_from_slice(&multipart);
626
627 assert_eq!(
628 decode_browser_zmtp_request(&wire).expect("valid browser framing"),
629 Bytes::from_static(b"sealed-envelope")
630 );
631 assert!(decode_browser_zmtp_request(&multipart).is_err());
632 let mut trailing = wire;
633 trailing.push(0);
634 assert!(decode_browser_zmtp_request(&trailing).is_err());
635 }
636}