plexus_core/plexus/in_process.rs
1//! MACRO-2.B3 · the in-process transport.
2//!
3//! A [`plexus_client::Transport`] that dispatches straight into an
4//! [`Activation`] — no socket, no server process, no runtime setup. It is
5//! the test double for a generated client, and the transport an activation
6//! author reaches for first.
7//!
8//! # Why it lives here and not in `plexus-client`
9//!
10//! `plexus-client` must build for `wasm32-unknown-unknown`, so it cannot
11//! depend on `plexus-core`. The dependency only runs one way — `plexus-core
12//! → plexus-client` — so the adapter that needs both lives on this side of
13//! the seam. The other transports follow the same rule: each lives where its
14//! dependencies do.
15//!
16//! # The error layers, preserved
17//!
18//! The three transports are meant to be interchangeable, which means they
19//! must agree on *which layer* a failure belongs to:
20//!
21//! | Failure | Layer | Why |
22//! |---|---|---|
23//! | [`Activation::call`] returns `Err(PlexusError)` | transport | the request never produced a stream — unknown method, dispatch refused, scope gate denied. Same class as "the connection failed". |
24//! | the stream contains a [`PlexusStreamItem::Error`] | in-band | the activation answered, and the answer is an error. |
25//! | the [`MethodRef`]'s namespace is not this activation's | transport | nothing was dispatched. |
26//!
27//! Collapsing the first two would make this transport report a different
28//! error layer than the wire ones for the same failure.
29//!
30//! # Not a way to skip the hub
31//!
32//! `DynamicHub` applies the scope gate, provenance and credential-envelope
33//! assembly. This transport applies none of them: it is `Activation::call`
34//! and nothing else. Reaching for it outside a test is a smell: a program
35//! that imports a whole hub calls it through
36//! [`HubTransport`](super::hub_transport::HubTransport) (LOCAL-6).
37
38use futures::StreamExt;
39use plexus_client::{ItemStream, MethodRef, StreamItem, StreamMetadata, Transport, TransportError};
40use serde_json::Value;
41
42use super::auth::AuthContext;
43use super::plexus::Activation;
44use super::types::PlexusStreamItem;
45
46/// A [`Transport`] backed directly by one [`Activation`].
47///
48/// ```ignore
49/// let client = TicketsClient::new(InProcessTransport::new(Tickets::new(store)));
50/// let tickets = client.list_all(None, None).await?;
51/// ```
52#[derive(Debug, Clone)]
53pub struct InProcessTransport<A> {
54 activation: A,
55 auth: Option<AuthContext>,
56}
57
58impl<A: Activation> InProcessTransport<A> {
59 /// Dispatch anonymously.
60 pub fn new(activation: A) -> Self {
61 Self {
62 activation,
63 auth: None,
64 }
65 }
66
67 /// Dispatch with an auth context attached to every call — the
68 /// equivalent of a transport carrying a session cookie.
69 pub fn with_auth(activation: A, auth: AuthContext) -> Self {
70 Self {
71 activation,
72 auth: Some(auth),
73 }
74 }
75
76 /// Borrow the activation, e.g. to assert on server-side state after a
77 /// call.
78 pub fn activation(&self) -> &A {
79 &self.activation
80 }
81}
82
83/// Translate the server envelope into the client one.
84///
85/// The client type is looser by design (see `plexus-client`'s
86/// `envelope` module): every field the REST bridge drops is optional there.
87/// In-process nothing is dropped, so every field is carried.
88pub(crate) fn to_client_item(item: PlexusStreamItem) -> StreamItem {
89 fn meta(m: super::types::StreamMetadata) -> Option<StreamMetadata> {
90 Some(StreamMetadata {
91 provenance: m.provenance,
92 plexus_hash: m.plexus_hash,
93 timestamp: m.timestamp,
94 })
95 }
96
97 match item {
98 PlexusStreamItem::Data {
99 metadata,
100 content_type,
101 content,
102 } => StreamItem::Data {
103 metadata: meta(metadata),
104 content_type: Some(content_type),
105 content,
106 },
107 PlexusStreamItem::Progress {
108 metadata,
109 message,
110 percentage,
111 } => StreamItem::Progress {
112 metadata: meta(metadata),
113 message,
114 percentage,
115 },
116 PlexusStreamItem::Error {
117 metadata,
118 message,
119 code,
120 recoverable,
121 } => StreamItem::Error {
122 metadata: meta(metadata),
123 message,
124 code,
125 recoverable,
126 },
127 PlexusStreamItem::Request {
128 request_id,
129 request_data,
130 timeout_ms,
131 } => StreamItem::Request {
132 request_id,
133 request_data,
134 timeout_ms,
135 },
136 PlexusStreamItem::Done { metadata } => StreamItem::Done {
137 metadata: meta(metadata),
138 },
139 }
140}
141
142impl<A: Activation> Transport for InProcessTransport<A> {
143 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
144 // A `MethodRef` names an activation as well as a method. Dispatching
145 // a `tickets.*` call into a `health` activation because the caller
146 // wired the wrong client to the wrong transport must not silently
147 // "work" for whichever method names happen to collide.
148 if method.namespace() != self.activation.namespace() {
149 let msg = format!(
150 "InProcessTransport is bound to activation `{}`, but the call is for `{}`",
151 self.activation.namespace(),
152 method,
153 );
154 return Box::pin(futures::stream::once(async move {
155 Err(TransportError::protocol(msg))
156 }));
157 }
158
159 Box::pin(
160 futures::stream::once(async move {
161 match self
162 .activation
163 .call(method.method(), params, self.auth.as_ref(), None)
164 .await
165 {
166 // `call` succeeded: the activation owns the outcome from
167 // here, including any in-band `error` item.
168 Ok(stream) => stream.map(|item| Ok(to_client_item(item))).left_stream(),
169 // `call` failed: nothing was answered.
170 Err(e) => futures::stream::once(async move {
171 Err(TransportError::other(e.to_string()))
172 })
173 .right_stream(),
174 }
175 })
176 .flatten(),
177 )
178 }
179}