hyprstream_rpc/transport_traits.rs
1//! Transport and Signer traits for unified RPC communication.
2//!
3//! These traits abstract over the wire transport (ZMQ vs WebTransport) and
4//! signing mechanism (local key vs external callback), enabling a single
5//! `RpcClient<S, T>` implementation that compiles to both native and wasm32.
6
7use anyhow::Result;
8use async_trait::async_trait;
9use futures::Stream;
10
11/// A transport failure proven to have occurred before any request bytes were
12/// dispatched. Only this marker is safe for automatic endpoint retry.
13#[derive(Debug)]
14pub struct PreDispatchTransportError(anyhow::Error);
15
16impl PreDispatchTransportError {
17 pub fn new(error: anyhow::Error) -> Self {
18 Self(error)
19 }
20}
21
22impl std::fmt::Display for PreDispatchTransportError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 write!(f, "pre-dispatch transport failure: {}", self.0)
25 }
26}
27
28impl std::error::Error for PreDispatchTransportError {
29 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
30 Some(self.0.as_ref())
31 }
32}
33
34pub fn is_pre_dispatch_transport_error(error: &anyhow::Error) -> bool {
35 error
36 .chain()
37 .any(|cause| cause.downcast_ref::<PreDispatchTransportError>().is_some())
38}
39
40/// Signing abstraction for Ed25519 envelope signatures.
41///
42/// Native: `LocalSigner` owns the `SigningKey` and signs synchronously.
43/// WASM: `JsSigner` delegates to a JS callback (aegis-vault) and awaits the result.
44///
45/// # Safety (wasm32)
46///
47/// `JsSigner` holds `js_sys::Function` which is `!Send`. We use
48/// `unsafe impl Send + Sync` on it because wasm32 is single-threaded.
49/// The `Send + Sync` bounds on this trait are required so that `RpcClient<S, T>`
50/// can be used with `Arc` and `tokio::spawn` on native.
51#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
52#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
53pub trait Signer: Send + Sync {
54 /// Ed25519 public key (32 bytes).
55 fn pubkey(&self) -> [u8; 32];
56
57 /// Sign canonical envelope bytes. Returns 64-byte Ed25519 signature.
58 async fn sign(&self, canonical_bytes: &[u8]) -> Result<[u8; 64]>;
59
60 /// ML-DSA-65 verifying key bytes (1952 bytes) when PQ hybrid is available.
61 fn pq_pubkey(&self) -> Option<Vec<u8>> {
62 None
63 }
64
65 /// ML-DSA-65 signature over canonical envelope bytes.
66 async fn pq_sign(&self, _canonical_bytes: &[u8]) -> Result<Option<Vec<u8>>> {
67 Ok(None)
68 }
69}
70
71/// Wire transport abstraction.
72///
73/// Native: `ZmqConnection` wraps ZMQ REQ sockets with auto-reconnect.
74/// WASM: `WtConnection` wraps WebTransport bidi streams with ZMTP framing.
75///
76/// Both transports carry ZMTP-framed messages. The `Sub` and `Pub` associated
77/// types provide streaming (server→client) and control (client→server) channels.
78///
79/// `Sub` must implement `futures::Stream` yielding frames as `Vec<Vec<u8>>`,
80/// matching the ZMTP multipart format `[topic, capnp_data, mac]`.
81///
82/// Uses cfg-gated async_trait: Send on native, ?Send on wasm32.
83/// The trait types themselves are `Send + Sync` (via unsafe impl on wasm32),
84/// so `Arc<RpcClient<S, T>>` can be shared across threads on native.
85/// Individual call futures are awaited in place, not spawned.
86#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
87#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
88pub trait Transport: Send + Sync {
89 /// Subscriber type for data streams (server→client).
90 /// Must yield ZMTP multipart frames as `Vec<Vec<u8>>`.
91 type Sub: Stream<Item = Result<Vec<Vec<u8>>>> + Unpin + Send;
92
93 /// Publisher type for control channel (client→server).
94 type Pub: PublishSink + Send;
95
96 /// Send a request and receive a response (REQ/REP pattern).
97 ///
98 /// `timeout_ms`: Optional timeout in milliseconds. Implementations should
99 /// use a default (e.g., 30s) when `None`. On native, this caps the ZMQ
100 /// recv timeout. On WASM, WebTransport stream lifetime handles this.
101 async fn send(&self, payload: Vec<u8>, timeout_ms: Option<i32>) -> Result<Vec<u8>>;
102
103 /// Whether this carrier forbids cleartext request envelopes.
104 ///
105 /// Networked/untrusted carriers require the RPC client to populate
106 /// `SignedEnvelope.encrypted_envelope` with a HyKEM/COSE_Encrypt0 payload.
107 ///
108 /// **Fail-closed default (`true`).** A carrier is treated as untrusted for
109 /// envelope confidentiality unless it explicitly opts out — so a new or
110 /// out-of-tree `Transport` cannot silently inherit cleartext permission
111 /// (epic #550 principle 1: no silent downgrade). Only same-process and
112 /// same-host IPC transports (`InMemoryTransport`, `LazyUdsTransport`)
113 /// override this to `false`. Every QUIC carrier
114 /// (`QuinnTransport`, `LazyQuinnTransport`) and iroh carrier forbids
115 /// cleartext unconditionally — a loopback address earns NO exemption, since
116 /// it is not evidence the bytes stay inside the trust boundary (it can
117 /// terminate at a proxy/tunnel). This mirrors
118 /// [`EndpointType::forbids_cleartext_envelope`](crate::transport::EndpointType::forbids_cleartext_envelope),
119 /// the parallel config-time classification; the two are intentionally
120 /// layered (pre-dial classification vs runtime enforcement) rather than
121 /// delegated, so a runtime transport need not reconstruct an `EndpointType`.
122 fn forbids_cleartext_envelope(&self) -> bool {
123 true
124 }
125
126 /// Subscribe to a topic (SUB pattern). Returns a stream of multipart frames.
127 async fn subscribe(&self, topic: &[u8]) -> Result<Self::Sub>;
128
129 /// Open a publish channel to a topic (PUB/PUSH pattern for ctrl messages).
130 async fn publish(&self, topic: &[u8]) -> Result<Self::Pub>;
131}
132
133/// Trait for sending frames on a publish/control channel.
134///
135/// Abstracted because native uses sync `zmq::Socket::send` with `DONTWAIT`,
136/// while WASM uses async WebTransport writes.
137#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
138#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
139pub trait PublishSink: Send {
140 /// Send ZMTP multipart frames (e.g., `[ctrl_topic, capnp, mac]`).
141 async fn send_frames(&self, frames: &[&[u8]]) -> Result<()>;
142}