plexus-client 0.11.0

wasm-safe client runtime for Plexus RPC: the wire envelope, the Transport trait, and typed event decoding
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! `WsTransport` — the Plexus WebSocket JSON-RPC transport.
//!
//! One connection, every call multiplexed over it as a JSON-RPC
//! subscription. This is the transport that carries the full
//! [`StreamMetadata`](crate::StreamMetadata) envelope, and the one menger's
//! frontend adopts.
//!
//! ```no_run
//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
//! # use plexus_client::{MethodRef, Transport};
//! use plexus_client::WsTransport;
//!
//! let transport = WsTransport::connect("ws://127.0.0.1:4455", "menger").await?;
//! // let client = TicketsClient::new(transport);   // and reuse it for every activation
//! # let _ = transport.call(MethodRef::new("tickets", "list"), serde_json::json!({}));
//! # Ok(())
//! # }
//! ```
//!
//! # The wire
//!
//! Every [`Transport::call`] becomes exactly one subscribe frame:
//!
//! ```json
//! {"jsonrpc":"2.0","id":1,"method":"menger.call",
//!  "params":{"method":"tickets.watch","params":{"epic":"MACRO"}}}
//! ```
//!
//! The reply's `result` **is** the subscription id. Items then arrive as
//! notifications carrying `params.subscription` and `params.result`, and
//! dropping the returned stream sends `menger.call_unsub`.
//!
//! Three properties are worth stating, because getting any of them wrong is
//! silent:
//!
//! - **Routing is by `params.subscription`, never by the notification's
//!   method name.** `PLEXUS_NOTIF_METHOD` is `"result"`, but plexus-core
//!   0.5.3 emits notifications under the subscribe method's own name
//!   (`"menger.call"`). Both spellings route identically here, and both are
//!   pinned by test.
//! - **The subscribe is written when `call` is invoked, not when the
//!   returned stream is first polled.** menger's own `tests/wire.rs` opens a
//!   `watch` and *then* mutates; a lazily-subscribing transport would miss
//!   the mutation and the bug would look like a server problem.
//! - **The item channel exists before the frame is written**, so an item the
//!   server puts on the wire immediately behind the acknowledgement cannot
//!   be lost.
//!
//! # A call with an input half (BIDIR-6)
//!
//! [`Transport::call_with_input`] is a subscribe like any other. The stream
//! it returns also feeds the input: as it is polled it spends the callee's
//! `credit`, sending what is ready as one `<hub>.input {subscription, seq,
//! items}` and `<hub>.end` when the input ends. `credit`, `ack` and
//! `input_closed` are spent here and never yielded. A caller that stops
//! reading stops feeding; no task runs behind its back, so both backends
//! share this.
//!
//! # One type, two backends
//!
//! `plexus-client`'s default feature set is the four-dependency wasm-clean
//! core; a WebSocket needs I/O, and the I/O a browser has is not the I/O a
//! server has. So the transport ships behind two features that expose the
//! **same** `WsTransport` type and the same constructor:
//!
//! | Feature | Backend | For |
//! |---|---|---|
//! | `ws-native` | `tokio-tungstenite` | servers, CLIs, tests |
//! | `ws-web` | `web_sys::WebSocket` | `wasm32-unknown-unknown`, a browser app |
//!
//! Only the socket differs: request ids, the pending table, the routing
//! table, cancellation and both frame shapes live in one place
//! ([`registry`]), so the two backends cannot drift on protocol. Enabling
//! both picks the native one.
//!
//! [`Transport::call`]: crate::Transport::call

mod registry;

// `ws-web` is a browser backend: its socket is a `web_sys::WebSocket`, which
// is `!Send`, while `ItemStream` off wasm32 requires `Send`. Saying so here
// beats a wall of unsatisfied-bound errors inside `Transport::call`.
#[cfg(all(
    feature = "ws-web",
    not(feature = "ws-native"),
    not(target_arch = "wasm32")
))]
compile_error!(
    "plexus-client: feature `ws-web` is the wasm32 browser backend. Off \
     wasm32-unknown-unknown, enable `ws-native` instead (both features \
     expose the same `WsTransport`)."
);

#[cfg(feature = "ws-native")]
#[path = "native.rs"]
mod backend;

#[cfg(all(feature = "ws-web", not(feature = "ws-native")))]
#[path = "web.rs"]
mod backend;

use crate::error::TransportError;
use crate::transport::{InputItem, InputItems, ItemStream, MethodRef, RawItemStream, Transport};
use futures_util::{stream, Stream, StreamExt};
use registry::{end_frame, input_frame, subscribe_frame, Delivered, InputSignal, Items, Registry, SubSlot};
use serde_json::Value;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

/// Frame tracing, for when a wire question has to be answered with bytes.
///
/// Off unless `PLEXUS_WS_TRACE` is set in the environment; then every frame
/// this transport writes or reads is printed to stderr as `ws → …` / `ws ← …`.
fn trace(direction: &str, frame: &str) {
    use std::sync::OnceLock;
    static ON: OnceLock<bool> = OnceLock::new();
    if *ON.get_or_init(|| std::env::var("PLEXUS_WS_TRACE").is_ok()) {
        eprintln!("ws {direction} {frame}");
    }
}

/// A Plexus client over one WebSocket JSON-RPC connection.
///
/// Cheap to clone and intended to be shared: one connection serves every
/// activation's client, which is the point of multiplexing.
/// `plexus-codegen-rust`'s client opens a fresh connection per call, which
/// cannot hold a `watch` open while issuing a `list`.
#[derive(Debug, Clone)]
pub struct WsTransport {
    conn: backend::Conn,
    registry: Arc<Registry>,
    /// Shuts the socket down when the last handle goes. Streams borrow the
    /// transport, so they are always gone by then.
    _closer: Arc<Closer>,
}

/// Closes the connection when the last [`WsTransport`] handle drops.
///
/// Without it the socket outlives its transport: the reader task holds a
/// writer handle of its own (it answers late acknowledgements with
/// `call_unsub`), so the writer's queue never ends on its own.
#[derive(Debug)]
struct Closer {
    conn: backend::Conn,
}

impl Drop for Closer {
    fn drop(&mut self) {
        self.conn.close();
    }
}

impl WsTransport {
    /// Connect to a Plexus WebSocket endpoint.
    ///
    /// `hub_namespace` is the server's `DynamicHub::new(ns)` namespace —
    /// `"menger"` for menger — **not** an activation namespace. It is
    /// transport configuration because it is a property of the server: the
    /// same `tickets.list` call goes to `menger.call` on one deployment and
    /// to some other hub's `call` on another.
    ///
    /// Fails with [`TransportErrorKind::Connect`] if the socket cannot be
    /// established.
    ///
    /// [`TransportErrorKind::Connect`]: crate::TransportErrorKind::Connect
    pub async fn connect(url: &str, hub_namespace: &str) -> Result<Self, TransportError> {
        let registry = Arc::new(Registry::new(Arc::from(hub_namespace)));
        let conn = backend::connect(url, registry.clone()).await?;
        Ok(Self {
            _closer: Arc::new(Closer { conn: conn.clone() }),
            conn,
            registry,
        })
    }

    /// FRAME-16: [`connect`](Self::connect) over a socket already made —
    /// a page opens it before its wasm is instantiated and hands it over.
    /// Open, it is taken at once; still connecting, when it opens; closing
    /// or closed, refused ([`TransportErrorKind::Connect`]). `ws-web` only.
    ///
    /// [`TransportErrorKind::Connect`]: crate::TransportErrorKind::Connect
    #[cfg(all(feature = "ws-web", not(feature = "ws-native")))]
    pub async fn adopt(socket: web_sys::WebSocket, hub_namespace: &str) -> Result<Self, TransportError> {
        let registry = Arc::new(Registry::new(Arc::from(hub_namespace)));
        let conn = backend::adopt(socket, registry.clone()).await?;
        Ok(Self {
            _closer: Arc::new(Closer { conn: conn.clone() }),
            conn,
            registry,
        })
    }

    /// [`connect`](Self::connect), with headers on the upgrade request — an
    /// `Authorization: Bearer <key proof>` for a server under login, as
    /// synapse signs in. `ws-native` only: a browser's socket takes no
    /// headers (it carries its cookies).
    #[cfg(feature = "ws-native")]
    pub async fn connect_with_headers(
        url: &str,
        hub_namespace: &str,
        headers: &[(String, String)],
    ) -> Result<Self, TransportError> {
        let registry = Arc::new(Registry::new(Arc::from(hub_namespace)));
        let conn = backend::connect_with_headers(url, headers, registry.clone()).await?;
        Ok(Self {
            _closer: Arc::new(Closer { conn: conn.clone() }),
            conn,
            registry,
        })
    }

    /// The hub namespace this transport prefixes `call` / `call_unsub` with.
    pub fn hub_namespace(&self) -> &str {
        self.registry.hub_namespace()
    }

    /// `true` once the socket has gone away. Every stream open at that
    /// moment yielded a [`TransportErrorKind::Closed`] item.
    ///
    /// [`TransportErrorKind::Closed`]: crate::TransportErrorKind::Closed
    pub fn is_closed(&self) -> bool {
        self.registry.is_closed()
    }

    /// Write the subscribe frame and hand back what the returned stream
    /// needs to drain it.
    fn subscribe(&self, method: MethodRef, params: Value, raw: bool) -> Result<Awaiting, TransportError> {
        let request_id = self.registry.next_request_id();
        let slot = SubSlot::new();
        let reply = self.registry.register_pending(request_id, slot.clone(), raw)?;

        let frame = subscribe_frame(
            request_id,
            self.registry.hub_namespace(),
            &method.qualified(),
            &params,
        );
        trace("→", &frame);
        if let Err(e) = self.conn.send(frame) {
            self.registry.forget_pending(request_id);
            return Err(e);
        }

        Ok(Awaiting {
            reply,
            // The guard exists from here on, so a stream dropped before its
            // first poll still cancels the subscription it just opened.
            guard: SubGuard {
                conn: self.conn.clone(),
                registry: self.registry.clone(),
                slot,
            },
        })
    }
}

impl Transport for WsTransport {
    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
        Box::pin(self.items(method, params, false).map(|item| item.map(Delivered::into_item)))
    }

    /// The items with their content as the wire's text, for a typed client
    /// (PERF.115-36).
    fn call_raw(&self, method: MethodRef, params: Value) -> RawItemStream<'_> {
        Box::pin(self.items(method, params, true).map(|item| item.map(Delivered::into_raw)))
    }

    fn call_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> ItemStream<'a> {
        Box::pin(self.items_with_input(method, params, input, false).map(|item| item.map(Delivered::into_item)))
    }

    /// BIDIR-6 on RETURNS-36's typed path: the items with their content as
    /// the wire's text.
    fn call_raw_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>) -> RawItemStream<'a> {
        Box::pin(self.items_with_input(method, params, input, true).map(|item| item.map(Delivered::into_raw)))
    }
}

impl WsTransport {
    /// One call's items, as `raw` says it reads them.
    fn items(&self, method: MethodRef, params: Value, raw: bool) -> impl Stream<Item = Result<Delivered, TransportError>> + '_ {
        // The subscribe goes out NOW, not on first poll — see the module
        // docs: `watch` then mutate is the shape every menger client uses.
        let start = match self.subscribe(method, params, raw) {
            Ok(awaiting) => CallState::Awaiting(awaiting),
            Err(e) => CallState::Failed(e),
        };

        stream::unfold(start, |state| async move {
            match state {
                CallState::Awaiting(awaiting) => match awaiting.established().await {
                    Err(e) => Some((Err(e), CallState::Ended)),
                    Ok(mut active) => active
                        .next_item()
                        .await
                        .map(|item| (item, CallState::Active(active))),
                },
                CallState::Active(mut active) => active
                    .next_item()
                    .await
                    .map(|item| (item, CallState::Active(active))),
                CallState::Failed(e) => Some((Err(e), CallState::Ended)),
                CallState::Ended => None,
            }
        })
    }

    /// One call's items with its input half fed as they are read, as `raw`
    /// says it reads them.
    fn items_with_input<'a>(&'a self, method: MethodRef, params: Value, input: InputItems<'a>, raw: bool) -> impl Stream<Item = Result<Delivered, TransportError>> + 'a {
        let start = match self.subscribe(method, params, raw) {
            Ok(awaiting) => {
                let feed = Feed { input: Some(input), credit: 0, seq: 0, conn: self.conn.clone(), registry: self.registry.clone(), failed: false };
                Feeding::Awaiting(awaiting, feed)
            }
            Err(e) => Feeding::Failed(e),
        };
        stream::unfold(start, |state| async move {
            let (mut active, mut feed) = match state {
                Feeding::Awaiting(awaiting, feed) => match awaiting.established().await {
                    Err(e) => return Some((Err(e), Feeding::Ended)),
                    Ok(active) => (active, feed),
                },
                Feeding::Active(active, feed) => (active, feed),
                Feeding::Failed(e) => return Some((Err(e), Feeding::Ended)),
                Feeding::Ended => return None,
            };
            let item = std::future::poll_fn(|cx| feed.poll_next(&mut active, cx)).await?;
            let failed = feed.failed;
            Some((item, if failed { Feeding::Ended } else { Feeding::Active(active, feed) }))
        })
    }
}

/// [`CallState`], for a call with an input half.
enum Feeding<'a> {
    Awaiting(Awaiting, Feed<'a>),
    Active(Active, Feed<'a>),
    /// The subscribe could not be written: one error, then the end.
    Failed(TransportError),
    Ended,
}

/// The most items one `<hub>.input` carries, and about the most bytes: a
/// frame is what was ready, and stays well under a server's message cap.
const FRAME_ITEMS: usize = 256;
const FRAME_BYTES: usize = 1024 * 1024;

/// The input half of a call, fed as its stream is polled.
struct Feed<'a> {
    /// `None`: ended, or the callee closed the half.
    input: Option<InputItems<'a>>,
    /// Items the callee has granted and this side has not sent.
    credit: u64,
    /// Frames sent.
    seq: u64,
    conn: backend::Conn,
    registry: Arc<Registry>,
    failed: bool,
}

impl Feed<'_> {
    /// The call's next item: the socket first, and between its items
    /// whatever the input has ready and credit allows.
    fn poll_next(&mut self, active: &mut Active, cx: &mut Context<'_>) -> Poll<Option<Result<Delivered, TransportError>>> {
        loop {
            let read = match active.items.poll_next_unpin(cx) {
                Poll::Ready(Some(Ok(Delivered::Input(InputSignal::Credit(n))))) => {
                    self.credit = self.credit.saturating_add(n);
                    true
                }
                Poll::Ready(Some(Ok(Delivered::Input(InputSignal::Ack)))) => true,
                Poll::Ready(Some(Ok(Delivered::Input(InputSignal::Closed)))) => {
                    self.input = None;
                    true
                }
                Poll::Ready(Some(item)) => {
                    if let Ok(item) = &item {
                        if item.is_terminal() {
                            self.input = None;
                            active.guard.slot.mark_finished();
                        }
                    }
                    return Poll::Ready(Some(item));
                }
                Poll::Ready(None) => return Poll::Ready(None),
                Poll::Pending => false,
            };
            match self.feed(active, cx) {
                Err(e) => {
                    self.failed = true;
                    return Poll::Ready(Some(Err(e)));
                }
                Ok(fed) if read || fed => continue,
                Ok(_) => return Poll::Pending,
            }
        }
    }

    /// One frame of what is ready, within the credit; `end` when the input
    /// has ended. `Ok(true)`: something went out, so look again.
    fn feed(&mut self, active: &Active, cx: &mut Context<'_>) -> Result<bool, TransportError> {
        let Some(subscription) = active.guard.slot.subscription() else { return Ok(false) };
        let Some(input) = &mut self.input else { return Ok(false) };
        let mut items = String::new();
        let mut count = 0;
        let mut over = false;
        let ns = self.registry.hub_namespace();
        let mut binaries = 0;
        while self.credit > 0 && count < FRAME_ITEMS && items.len() < FRAME_BYTES {
            match Pin::new(&mut *input).poll_next(cx) {
                Poll::Ready(Some(Ok(InputItem::Json(item)))) => {
                    if count > 0 {
                        items.push(',');
                    }
                    items.push_str(&item.to_string());
                    count += 1;
                    self.credit -= 1;
                }
                // BIDIR-17: one binary frame an item, in the same sequence
                // (what JSON is gathered goes first).
                Poll::Ready(Some(Ok(InputItem::Binary(payload)))) => {
                    if count > 0 {
                        let frame = input_frame(ns, &subscription, self.seq, &items);
                        trace("→", &frame);
                        self.conn.send(frame)?;
                        self.seq += 1;
                        items.clear();
                        count = 0;
                    }
                    self.conn.send_binary(binary_frame(&subscription, self.seq, &payload)?)?;
                    self.seq += 1;
                    self.credit -= 1;
                    binaries += 1;
                }
                Poll::Ready(Some(Err(e))) => return Err(e),
                Poll::Ready(None) => {
                    over = true;
                    break;
                }
                Poll::Pending => break,
            }
        }
        // With no credit the input is not polled: its end is found once there
        // is, as the callee's half-window comes back or the call ends.
        if count > 0 {
            let frame = input_frame(ns, &subscription, self.seq, &items);
            trace("→", &frame);
            self.conn.send(frame)?;
            self.seq += 1;
        }
        if over {
            self.input = None;
            let frame = end_frame(ns, &subscription, self.seq);
            trace("→", &frame);
            self.conn.send(frame)?;
        }
        Ok(count > 0 || binaries > 0 || over)
    }
}

/// BIDIR-17: `[0x01][subscription: u64 BE][seq: u64 BE][payload]`.
fn binary_frame(subscription: &Value, seq: u64, payload: &[u8]) -> Result<Vec<u8>, TransportError> {
    let Some(subscription) = subscription.as_u64() else {
        return Err(TransportError::protocol(format!("a binary input frame needs an integer subscription id, not {subscription}")));
    };
    let mut frame = Vec::with_capacity(17 + payload.len());
    frame.push(0x01);
    frame.extend_from_slice(&subscription.to_be_bytes());
    frame.extend_from_slice(&seq.to_be_bytes());
    frame.extend_from_slice(payload);
    Ok(frame)
}

/// One call's life: the subscribe is on the wire, then the subscription is
/// drained.
enum CallState {
    Awaiting(Awaiting),
    Active(Active),
    /// The subscribe could not be written: one error, then the end.
    Failed(TransportError),
    Ended,
}

/// Subscribe written, reply outstanding.
struct Awaiting {
    reply: futures_channel::oneshot::Receiver<Result<Items, TransportError>>,
    guard: SubGuard,
}

impl Awaiting {
    async fn established(self) -> Result<Active, TransportError> {
        match self.reply.await {
            Ok(Ok(items)) => Ok(Active {
                items,
                guard: self.guard,
            }),
            Ok(Err(e)) => Err(e),
            // The reader dropped the waiter without answering, which only
            // happens if the connection died between the two.
            Err(_) => Err(TransportError::closed(
                "connection closed before the subscription was acknowledged",
            )),
        }
    }
}

/// Acknowledged; items are arriving.
struct Active {
    guard: SubGuard,
    items: Items,
}

impl Active {
    async fn next_item(&mut self) -> Option<Result<Delivered, TransportError>> {
        loop {
            match self.items.next().await {
                // A plain call of a method with an input half: nothing to feed.
                Some(Ok(Delivered::Input(_))) => continue,
                // `done` / `error` end the subscription server-side, so there
                // is nothing left to unsubscribe from.
                Some(Ok(item)) => {
                    if item.is_terminal() {
                        self.guard.slot.mark_finished();
                    }
                    return Some(Ok(item));
                }
                // A transport failure does NOT mark the slot finished: if the
                // socket survived (a malformed item, say) the subscription is
                // still live and the guard must still cancel it. On a dead
                // socket the unsubscribe write simply fails and is ignored.
                Some(Err(e)) => return Some(Err(e)),
                None => return None,
            }
        }
    }
}

/// Cancels the server-side subscription when the caller drops the stream.
///
/// This is the piece `menger/web/index.html` is missing — it never
/// unsubscribes, and leaks a subscription per reload.
struct SubGuard {
    conn: backend::Conn,
    registry: Arc<Registry>,
    slot: Arc<SubSlot>,
}

impl Drop for SubGuard {
    fn drop(&mut self) {
        // `None` is either "nothing to cancel" or "the reply has not landed
        // yet" — in the second case the reader sends the unsubscribe when it
        // learns the id. See `SubSlot`.
        let Some(subscription) = self.slot.on_dropped() else {
            return;
        };
        self.registry.forget_sub(&subscription);
        let frame = self.registry.unsubscribe(&subscription);
        trace("→", &frame);
        // Dropping a stream is not a fallible operation for the caller, and
        // a failed unsubscribe means the socket is already gone — which
        // cancels the subscription anyway.
        let _ = self.conn.send(frame);
    }
}