aimdb_core/session/mod.rs
1//! Connector-session substrate — the shared machinery for transport-based
2//! remote access.
3//!
4//! Three layers: transport ([`Connection`]/[`Listener`]/[`Dialer`]), codec
5//! ([`EnvelopeCodec`]), and dispatch ([`Dispatch`]/[`Session`]), over a
6//! role-neutral [`Inbound`]/[`Outbound`] message set shared by the reactive
7//! server engine (`serve`/`run_session`) and the proactive client engine
8//! (`run_client`/`pump_client`).
9//!
10//! All contracts are `dyn`-safe and compile on `std` and `no_std + alloc`.
11
12use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
13
14use crate::clock::Stamp;
15use core::future::Future;
16use core::pin::Pin;
17
18use futures_core::Stream;
19
20// The engines are runtime-neutral (`futures` channels + the adapter's `RuntimeOps`
21// clock, no `tokio`/`embassy-*`), so they cross-compile to `no_std + alloc`.
22#[cfg(feature = "connector-session")]
23mod client;
24#[cfg(feature = "connector-session")]
25mod connector;
26#[cfg(feature = "connector-session")]
27mod endpoint;
28#[cfg(feature = "connector-session")]
29mod io;
30#[cfg(feature = "connector-session")]
31mod server;
32
33// Concrete AimX protocol substrate. The transport lives in a separate connector
34// crate (`aimdb-uds-connector`) — core keeps the protocol plus the generic
35// [`SessionClientConnector`] / [`SessionServerConnector`] spine.
36#[cfg(all(feature = "connector-session", feature = "remote"))]
37pub mod aimx;
38
39mod events;
40
41mod topic_match;
42pub use topic_match::{is_wildcard, pattern_contains, topic_matches};
43
44#[cfg(feature = "connector-session")]
45pub use client::{pump_client, run_client, ClientConfig, ClientHandle};
46#[cfg(feature = "connector-session")]
47pub use connector::{SessionClientConnector, SessionServerConnector};
48#[cfg(feature = "connector-session")]
49pub use endpoint::{split_host_port, split_host_port_opt, EndpointError};
50#[cfg(feature = "connector-session")]
51pub use io::{
52 ByteRead, ByteStream, ByteWrite, Datagram, DatagramBinder, Delay, FrameFault, FramedConnection,
53 Framer, FramerFactory, FramingDialer, FramingListener, IoError, OneShot, OneShotDialer,
54 OneShotListener, StreamDialer, StreamListener,
55};
56#[cfg(feature = "connector-session")]
57pub use server::{run_session, serve, SessionConfig};
58
59// ===========================================================================
60// Shared aliases
61// ===========================================================================
62
63/// Boxed, `Send` future — the object-safe async return shape used throughout.
64pub type BoxFut<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
65
66/// Boxed, `Send` stream — the reply shape of a subscription ([`Session::subscribe`]).
67pub type BoxStream<'a, T> = Pin<Box<dyn Stream<Item = T> + Send + 'a>>;
68
69/// A serialized record value, carried opaquely through the codec.
70///
71/// `Arc<[u8]>` so fan-out is a refcount bump. Bytes stay opaque until a handler
72/// inspects them.
73pub type Payload = Arc<[u8]>;
74
75/// One update delivered on a subscription stream (server [`Session::subscribe`]
76/// and client [`ClientHandle::subscribe`] alike).
77///
78/// `topic` names the concrete record that fired: `Some` on wildcard
79/// subscriptions, which fan in many records under one subscription id, and on
80/// any transport that tags every event; `None` on an exact-topic subscription.
81#[derive(Clone, Debug)]
82pub struct SubUpdate {
83 /// Concrete record topic that fired, when the producer side tags it.
84 pub topic: Option<Arc<str>>,
85 /// The serialized record value.
86 pub data: Payload,
87 /// When the value was written, on the producing instance's clock
88 /// (design 058). Mandatory on AimX 4.0 frames.
89 pub ts: Stamp,
90 /// Count of skipped records
91 pub skipped: u64,
92 /// Set on the last update of the late-join snapshot burst, carrying its total `skipped`.
93 ///
94 /// Only set when the burst produced a final update to carry it — an empty
95 /// burst, an exact-topic subscribe, or a tail that failed to encode end
96 /// without one — so its absence says nothing.
97 pub snapshot_end: bool,
98}
99
100impl SubUpdate {
101 /// An untagged update (exact-topic subscription).
102 pub fn new(data: Payload, ts: Stamp) -> Self {
103 Self {
104 topic: None,
105 data,
106 ts,
107 skipped: 0,
108 snapshot_end: false,
109 }
110 }
111
112 /// A topic-tagged update (wildcard / bus subscription).
113 pub fn tagged(topic: Arc<str>, data: Payload, ts: Stamp) -> Self {
114 Self {
115 topic: Some(topic),
116 data,
117 ts,
118 skipped: 0,
119 snapshot_end: false,
120 }
121 }
122
123 /// Mark that `n` updates were lost on this subscription immediately before
124 /// this one (`0` leaves the update lossless).
125 pub fn with_skipped(mut self, n: u64) -> Self {
126 self.skipped = n;
127 self
128 }
129
130 /// Mark this update as the last of the late-join snapshot burst (see
131 /// [`snapshot_end`](Self::snapshot_end)).
132 pub fn with_snapshot_end(mut self) -> Self {
133 self.snapshot_end = true;
134 self
135 }
136}
137
138/// Result of a transport-layer operation.
139pub type TransportResult<T> = Result<T, TransportError>;
140
141// ===========================================================================
142// Supporting types (stubs — sufficient for the signatures to compile)
143// ===========================================================================
144
145/// Remote-peer metadata carried by a [`Connection`].
146///
147/// A neutral [`peer_addr`](Self::peer_addr) plus a type-erased
148/// [`ext`](Self::ext) slot a connector fills with its own resolved identity
149/// (e.g. WS attaches `ClientInfo` at the HTTP upgrade), keeping core
150/// connector-agnostic. Downcast `ext` with [`ext_as`](Self::ext_as).
151#[derive(Clone, Default)]
152#[non_exhaustive]
153pub struct PeerInfo {
154 /// Remote address, if the transport exposes one.
155 pub peer_addr: Option<String>,
156 /// Connector-resolved identity, type-erased so core need not know the
157 /// connector's auth types. Downcast with [`ext_as`](Self::ext_as).
158 pub ext: Option<Arc<dyn core::any::Any + Send + Sync>>,
159}
160
161impl PeerInfo {
162 /// Attach a connector-resolved identity (consumed by [`Dispatch::authenticate`]).
163 pub fn with_ext(mut self, ext: Arc<dyn core::any::Any + Send + Sync>) -> Self {
164 self.ext = Some(ext);
165 self
166 }
167
168 /// Downcast the [`ext`](Self::ext) identity to a concrete connector type.
169 pub fn ext_as<T: core::any::Any + Send + Sync>(&self) -> Option<Arc<T>> {
170 self.ext.clone()?.downcast::<T>().ok()
171 }
172}
173
174impl core::fmt::Debug for PeerInfo {
175 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
176 f.debug_struct("PeerInfo")
177 .field("peer_addr", &self.peer_addr)
178 .field("ext", &self.ext.as_ref().map(|_| "<opaque>"))
179 .finish()
180 }
181}
182
183/// The authenticated session context produced by [`Dispatch::authenticate`] and
184/// threaded into [`Dispatch::open`].
185///
186/// Carries the resolved principal as a type-erased [`ext`](Self::ext) for
187/// per-operation authorization in the [`Session`]; downcast with
188/// [`ext_as`](Self::ext_as). Connectors that don't authenticate leave it `None`.
189#[derive(Clone, Default)]
190#[non_exhaustive]
191pub struct SessionCtx {
192 /// The resolved principal, type-erased. Downcast with [`ext_as`](Self::ext_as).
193 pub ext: Option<Arc<dyn core::any::Any + Send + Sync>>,
194}
195
196impl SessionCtx {
197 /// Build a context carrying a connector-resolved principal.
198 pub fn with_ext(ext: Arc<dyn core::any::Any + Send + Sync>) -> Self {
199 Self { ext: Some(ext) }
200 }
201
202 /// Downcast the [`ext`](Self::ext) principal to a concrete connector type.
203 pub fn ext_as<T: core::any::Any + Send + Sync>(&self) -> Option<Arc<T>> {
204 self.ext.clone()?.downcast::<T>().ok()
205 }
206}
207
208impl core::fmt::Debug for SessionCtx {
209 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
210 f.debug_struct("SessionCtx")
211 .field("ext", &self.ext.as_ref().map(|_| "<opaque>"))
212 .finish()
213 }
214}
215
216/// Per-session resource bounds consumed by the engines.
217#[derive(Debug, Clone)]
218pub struct SessionLimits {
219 /// Maximum concurrently served connections.
220 pub max_connections: usize,
221 /// Maximum live subscriptions per connection.
222 pub max_subs_per_connection: usize,
223}
224
225impl Default for SessionLimits {
226 fn default() -> Self {
227 Self {
228 max_connections: 16,
229 max_subs_per_connection: 32,
230 }
231 }
232}
233
234/// Transport-layer failure (Layer 1).
235#[derive(Debug, Clone, PartialEq, Eq)]
236#[cfg_attr(feature = "defmt", derive(defmt::Format))]
237#[non_exhaustive]
238pub enum TransportError {
239 /// The connection was closed or reset by the peer.
240 Closed,
241 /// An underlying I/O operation failed.
242 Io,
243 /// The byte stream could not be framed, and the framer cannot resynchronize.
244 Framing,
245 /// The transport's one endpoint resource is already in use — a second dial
246 /// on a single-socket transport while the first connection is live.
247 Busy,
248}
249
250/// Envelope-codec failure — a frame could not be decoded/encoded.
251#[derive(Debug, Clone, PartialEq, Eq)]
252#[cfg_attr(feature = "defmt", derive(defmt::Format))]
253#[non_exhaustive]
254pub enum CodecError {
255 /// The frame was not valid for this envelope format.
256 Malformed,
257 /// A value frame (`event`, `snap`) for subscription `sub` lacks its
258 /// mandatory write stamp (AimX 4.0). Unlike [`Malformed`](Self::Malformed)
259 /// it names the subscription, so the client can end that subscription with
260 /// [`RpcError::Protocol`] instead of dropping the frame unseen.
261 MissingStamp {
262 /// The subscription the frame was for.
263 sub: String,
264 },
265}
266
267/// Dispatch-layer (application) failure for `call` / `subscribe` / `write`.
268#[derive(Debug, Clone, PartialEq, Eq)]
269#[non_exhaustive]
270pub enum RpcError {
271 /// No such method or topic.
272 NotFound,
273 /// The caller lacks permission for this operation.
274 Denied,
275 /// The handler failed.
276 Internal,
277 /// The peer's declared protocol version is incompatible with this server's
278 /// `PROTOCOL_VERSION`. Raised at the handshake, before `hello` completes.
279 VersionMismatch,
280 /// The peer broke the protocol on this subscription, e.g. a value without
281 /// its mandatory `ts` (AimX 4.0). Raised by the client engine; never sent
282 /// on the wire.
283 Protocol,
284}
285
286/// Authentication failure raised by [`Dispatch::authenticate`].
287#[derive(Debug, Clone, PartialEq, Eq)]
288#[cfg_attr(feature = "defmt", derive(defmt::Format))]
289#[non_exhaustive]
290pub enum AuthError {
291 /// Credentials were missing or rejected.
292 Unauthorized,
293}
294
295// ===========================================================================
296// Logical message set — role-neutral: the server's `Inbound` is the client's
297// outbound and vice versa.
298// ===========================================================================
299
300/// A logical request arriving over a [`Connection`] (what the server receives).
301pub enum Inbound {
302 /// An RPC call expecting a single [`Outbound::Reply`].
303 Request {
304 /// Correlation id, echoed in the reply.
305 id: u64,
306 /// Method name (e.g. `"record.set"`, `"query"`).
307 method: String,
308 /// Unparsed method parameters.
309 params: Payload,
310 },
311 /// Open a subscription producing many [`Outbound::Event`]s.
312 Subscribe {
313 /// Correlation id for the subscription handshake.
314 id: u64,
315 /// Topic to subscribe to.
316 topic: String,
317 },
318 /// Close a previously opened subscription.
319 Unsubscribe {
320 /// Subscription id to cancel.
321 sub: String,
322 },
323 /// A fire-and-forget write (no reply).
324 Write {
325 /// Destination topic.
326 topic: String,
327 /// Unparsed record value.
328 payload: Payload,
329 },
330 /// Keepalive.
331 Ping,
332}
333
334/// A logical message sent back over a [`Connection`] (what the server emits).
335pub enum Outbound<'a> {
336 /// Reply to an [`Inbound::Request`].
337 Reply {
338 /// Correlation id of the originating request.
339 id: u64,
340 /// The result, or an [`RpcError`].
341 result: Result<Payload, RpcError>,
342 },
343 /// A subscription update.
344 Event {
345 /// Subscription id this event belongs to.
346 sub: &'a str,
347 /// Monotonic sequence number.
348 seq: u64,
349 /// Concrete record topic that fired, when the subscription tags it
350 /// (wildcard subscriptions fan in many records — see [`SubUpdate`]).
351 topic: Option<&'a str>,
352 /// When the value was written (see [`SubUpdate::ts`]).
353 ts: Stamp,
354 /// Unparsed record value.
355 data: Payload,
356 },
357 /// An initial snapshot emitted when a subscription opens (late-join).
358 Snapshot {
359 /// Subscription id the snapshot belongs to, so the client demux routes
360 /// it like an [`Event`](Outbound::Event) (a wildcard subscription's
361 /// snapshots carry topics that don't string-match the pattern key).
362 sub: &'a str,
363 /// Monotonic sequence number, in the **same space** as this
364 /// subscription's [`Event`](Outbound::Event)s: the burst is numbered
365 /// `1..=N` and the first event continues at `N + 1`, so a lost snapshot
366 /// surfaces in the next update's [`SubUpdate::skipped`].
367 seq: u64,
368 /// Set on the last snapshot of the burst, so the loss total lands on an
369 /// update the subscriber is guaranteed to see. The client engine
370 /// reserves a sink slot for this frame.
371 last: bool,
372 /// Topic the snapshot is for.
373 topic: &'a str,
374 /// When the value was written (see [`SubUpdate::ts`]).
375 ts: Stamp,
376 /// Unparsed record value.
377 data: Payload,
378 },
379 /// An explicit acknowledgement that a subscription opened. Emitted by
380 /// [`run_session`] only when [`SessionConfig::acks_subscribe`] is set.
381 /// The `sub` is the subscription's routing id — the same value that tags its
382 /// [`Event`](Outbound::Event)s.
383 Subscribed {
384 /// Subscription id that was opened.
385 sub: &'a str,
386 },
387 /// Keepalive response.
388 Pong,
389}
390
391// ===========================================================================
392// Layer 1 — transport. Framing lives in the transport: `recv` returns one
393// logical frame. `Dialer` is the client-side dual of `Listener`.
394// ===========================================================================
395
396/// A framed, bidirectional pipe — role-neutral (yielded by either
397/// [`Listener::accept`] or [`Dialer::connect`]).
398pub trait Connection: Send {
399 /// Receive one logical frame. `Ok(None)` signals the peer closed.
400 ///
401 /// # Cancellation
402 ///
403 /// Must be cancel-safe: the session loops drop this future whenever another
404 /// `select` arm wins, so a partly read frame must stay with the connection.
405 fn recv(&mut self) -> BoxFut<'_, TransportResult<Option<Vec<u8>>>>;
406
407 /// Send one logical frame.
408 fn send<'a>(&'a mut self, frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>>;
409
410 /// Peer metadata (remote addr, headers, pre-resolved auth).
411 fn peer(&self) -> &PeerInfo;
412}
413
414/// The accepting (server) side — produces [`Connection`]s we did not initiate.
415pub trait Listener: Send {
416 /// Accept the next inbound connection.
417 fn accept(&mut self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>>;
418}
419
420/// The initiating (client) side — the dual of [`Listener`]; dials out and
421/// produces the same [`Connection`].
422pub trait Dialer: Send {
423 /// Open a connection to the configured remote.
424 fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>>;
425}
426
427/// A boxed dialer is itself a [`Dialer`], so a runtime-selected
428/// `Box<dyn Dialer>` — from a `scheme://` URL resolver, say — can be passed
429/// where [`run_client`]`<D: Dialer>` is expected. The `Send` supertrait makes
430/// the box `Send + 'static`.
431impl Dialer for Box<dyn Dialer> {
432 fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
433 (**self).connect()
434 }
435}
436
437// ===========================================================================
438// Layer 3 — dispatch. RPC and streaming unify in one per-connection role with
439// three reply cardinalities: `call` (one) / `subscribe` (many) / `write` (none).
440// Split across two traits: the shared, immutable [`Dispatch`] (one
441// `Arc<dyn Dispatch>` per server) and the per-connection, `&mut`-threaded
442// [`Session`] that can hold mutable state without a lock.
443// ===========================================================================
444
445/// The shared application dispatch: authenticate a connection, then open a
446/// per-connection [`Session`]. One `Arc<dyn Dispatch>` is shared across every
447/// accepted connection, so it stays `Send + Sync` and behind `&self`.
448pub trait Dispatch: Send + Sync {
449 /// Resolve a [`SessionCtx`] from peer metadata and/or the first frame
450 /// (a pre-resolved identity in [`PeerInfo`], or an in-band Hello in `first`).
451 fn authenticate<'a>(
452 &'a self,
453 peer: &'a PeerInfo,
454 first: Option<&'a [u8]>,
455 ) -> BoxFut<'a, Result<SessionCtx, AuthError>>;
456
457 /// Open the per-connection [`Session`] once, after [`authenticate`](Self::authenticate). It owns
458 /// the connection's mutable dispatch state that the shared `Arc<Self>` cannot
459 /// hold behind `&self`; the engine threads `&mut` into it.
460 fn open(&self, ctx: &SessionCtx) -> Box<dyn Session>;
461}
462
463/// The per-connection session: serves calls, subscriptions, and writes for one
464/// accepted [`Connection`]. The engine owns the `Box<dyn Session>` and threads
465/// `&mut self` into each method, so it can hold per-connection state without a
466/// lock; the shared, immutable role stays on [`Dispatch`].
467pub trait Session: Send {
468 /// One-shot RPC: one request → one reply.
469 fn call<'a>(
470 &'a mut self,
471 method: &'a str,
472 params: Payload,
473 ) -> BoxFut<'a, Result<Payload, RpcError>>;
474
475 /// Open a subscription yielding many [`SubUpdate`]s. The stream is `'static`
476 /// (it captures cloned handles) so it outlives the `&mut` borrow and lives in
477 /// the engine. Async so a connector can await per-operation authorization.
478 /// Defaulted to [`RpcError::NotFound`] for dispatches with no streaming.
479 fn subscribe<'a>(
480 &'a mut self,
481 topic: &'a str,
482 ) -> BoxFut<'a, Result<BoxStream<'static, SubUpdate>, RpcError>> {
483 let _ = topic;
484 Box::pin(async { Err(RpcError::NotFound) })
485 }
486
487 /// Late-join snapshots: one `(topic, value)` per record covered by `topic`
488 /// (several for a wildcard subscription), each emitted as an
489 /// [`Outbound::Snapshot`] right after a successful
490 /// [`subscribe`](Session::subscribe) and before the first event. Defaulted
491 /// to empty (no snapshots).
492 ///
493 /// The engine numbers the burst `1..=N` and starts the event stream at
494 /// `N + 1`, so a snapshot dropped in transit shows up as
495 /// [`SubUpdate::skipped`] on the next delivered update.
496 ///
497 /// The burst's last snapshot is flagged and reaches the subscriber as the
498 /// one update with [`SubUpdate::snapshot_end`] set, carrying the burst's
499 /// whole loss; the client engine reserves a sink slot so it survives a slow
500 /// consumer.
501 ///
502 /// **Do not block on that flag.** It is absent when `topic` matches no
503 /// records, and when the final snapshot fails to encode or its frame is
504 /// rejected — the flag rides that frame. Loss accounting survives all of
505 /// these; only the end-of-burst signal is lost.
506 ///
507 /// Each entry is the record's topic, its payload, and the stamp of the
508 /// write that payload was read from (one read, design 058 §4.4).
509 fn snapshots(&mut self, topic: &str) -> Vec<(String, Payload, Stamp)> {
510 let _ = topic;
511 Vec::new()
512 }
513
514 /// Whether a request for `method` is a client's handshake, which starts a
515 /// new session. Defaulted to `false`.
516 ///
517 /// When a handshake arrives on a connection that already had one,
518 /// [`run_session`] treats it as a new client: it
519 /// cancels every subscription, discards their queued events and opens a
520 /// fresh session before answering. A transport that carries one peer for
521 /// its whole life (a serial line) has no other way to tell that the client
522 /// behind it changed.
523 fn starts_session(&self, method: &str) -> bool {
524 let _ = method;
525 false
526 }
527
528 /// Fire-and-forget write: no reply. Routes through the producer/arbiter path,
529 /// so single-writer-per-key stays intact.
530 fn write<'a>(
531 &'a mut self,
532 topic: &'a str,
533 payload: Payload,
534 ) -> BoxFut<'a, Result<(), RpcError>>;
535}
536
537/// The protocol-envelope codec: frame bytes ↔ the logical message set. Layered
538/// above (and nesting) the record-value `JsonCodec`, so the wire format stays
539/// pluggable; `decode`/`encode` keep the record value as an opaque [`Payload`]
540/// sliced from / spliced into the frame.
541///
542/// Symmetric, so one codec object serves both engines: `decode`/`encode` are the
543/// server direction (read requests / write replies) and
544/// [`encode_inbound`](EnvelopeCodec::encode_inbound) /
545/// [`decode_outbound`](EnvelopeCodec::decode_outbound) the client direction.
546pub trait EnvelopeCodec: Send + Sync {
547 /// Decode one frame into a logical [`Inbound`] message (server reads a request).
548 fn decode(&self, frame: &[u8]) -> Result<Inbound, CodecError>;
549
550 /// Encode a logical [`Outbound`] message, appending its bytes to `out`
551 /// (server writes a reply/event).
552 fn encode(&self, msg: Outbound<'_>, out: &mut Vec<u8>) -> Result<(), CodecError>;
553
554 /// Encode a logical [`Inbound`] message, appending its bytes to `out`
555 /// (client writes a request). The dual of [`decode`](EnvelopeCodec::decode).
556 fn encode_inbound(&self, msg: Inbound, out: &mut Vec<u8>) -> Result<(), CodecError>;
557
558 /// Decode one frame into a logical [`Outbound`] message (client reads a
559 /// reply/event). The dual of [`encode`](EnvelopeCodec::encode); the result
560 /// borrows the frame (`Outbound`'s `sub`/`topic` are `&str` slices into it).
561 fn decode_outbound<'a>(&self, frame: &'a [u8]) -> Result<Outbound<'a>, CodecError>;
562}
563
564// ===========================================================================
565// Taking each trait as `&dyn Trait` forces the dyn-compatibility check on all
566// targets, not just under `cargo test`.
567// ===========================================================================
568
569#[allow(dead_code, clippy::too_many_arguments)]
570fn _assert_object_safe(
571 _connection: &dyn Connection,
572 _listener: &dyn Listener,
573 _dialer: &dyn Dialer,
574 _dispatch: &dyn Dispatch,
575 _session: &dyn Session,
576 _codec: &dyn EnvelopeCodec,
577) {
578}
579
580#[cfg(test)]
581mod tests {
582 use super::*;
583
584 struct MockConnection;
585 impl Connection for MockConnection {
586 fn recv(&mut self) -> BoxFut<'_, TransportResult<Option<Vec<u8>>>> {
587 unimplemented!()
588 }
589 fn send<'a>(&'a mut self, _frame: &'a [u8]) -> BoxFut<'a, TransportResult<()>> {
590 unimplemented!()
591 }
592 fn peer(&self) -> &PeerInfo {
593 unimplemented!()
594 }
595 }
596
597 struct MockListener;
598 impl Listener for MockListener {
599 fn accept(&mut self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
600 unimplemented!()
601 }
602 }
603
604 struct MockDialer;
605 impl Dialer for MockDialer {
606 fn connect(&self) -> BoxFut<'_, TransportResult<Box<dyn Connection>>> {
607 unimplemented!()
608 }
609 }
610
611 struct MockDispatch;
612 impl Dispatch for MockDispatch {
613 fn authenticate<'a>(
614 &'a self,
615 _peer: &'a PeerInfo,
616 _first: Option<&'a [u8]>,
617 ) -> BoxFut<'a, Result<SessionCtx, AuthError>> {
618 unimplemented!()
619 }
620 fn open(&self, _ctx: &SessionCtx) -> Box<dyn Session> {
621 unimplemented!()
622 }
623 }
624
625 struct MockSession;
626 impl Session for MockSession {
627 fn call<'a>(
628 &'a mut self,
629 _method: &'a str,
630 _params: Payload,
631 ) -> BoxFut<'a, Result<Payload, RpcError>> {
632 unimplemented!()
633 }
634 fn subscribe<'a>(
635 &'a mut self,
636 _topic: &'a str,
637 ) -> BoxFut<'a, Result<BoxStream<'static, SubUpdate>, RpcError>> {
638 unimplemented!()
639 }
640 fn write<'a>(
641 &'a mut self,
642 _topic: &'a str,
643 _payload: Payload,
644 ) -> BoxFut<'a, Result<(), RpcError>> {
645 unimplemented!()
646 }
647 }
648
649 struct MockCodec;
650 impl EnvelopeCodec for MockCodec {
651 fn decode(&self, _frame: &[u8]) -> Result<Inbound, CodecError> {
652 unimplemented!()
653 }
654 fn encode(&self, _msg: Outbound<'_>, _out: &mut Vec<u8>) -> Result<(), CodecError> {
655 unimplemented!()
656 }
657 fn encode_inbound(&self, _msg: Inbound, _out: &mut Vec<u8>) -> Result<(), CodecError> {
658 unimplemented!()
659 }
660 fn decode_outbound<'a>(&self, _frame: &'a [u8]) -> Result<Outbound<'a>, CodecError> {
661 unimplemented!()
662 }
663 }
664
665 /// Every trait is `dyn`-usable.
666 #[test]
667 fn traits_are_object_safe() {
668 let _connection: Box<dyn Connection> = Box::new(MockConnection);
669 let _listener: Box<dyn Listener> = Box::new(MockListener);
670 let _dialer: Box<dyn Dialer> = Box::new(MockDialer);
671 let _dispatch: Box<dyn Dispatch> = Box::new(MockDispatch);
672 let _session: Box<dyn Session> = Box::new(MockSession);
673 let _codec: Box<dyn EnvelopeCodec> = Box::new(MockCodec);
674 }
675
676 /// `Box<dyn Dialer>` satisfies the `Dialer` bound, so a runtime-selected
677 /// dialer can be passed where `D: Dialer` is expected.
678 #[test]
679 fn boxed_dialer_is_a_dialer() {
680 fn takes_dialer<D: Dialer + 'static>(_d: D) {}
681 let boxed: Box<dyn Dialer> = Box::new(MockDialer);
682 takes_dialer(boxed);
683 }
684}