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(std::sync::Arc::unwrap_or_clone(metadata)),
104 content_type: Some(content_type.into_owned()),
105 content: content.into_value(),
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 ..
122 } => StreamItem::Error {
123 metadata: meta(metadata),
124 message,
125 code,
126 recoverable,
127 },
128 PlexusStreamItem::Request {
129 request_id,
130 request_data,
131 timeout_ms,
132 } => StreamItem::Request {
133 request_id,
134 request_data,
135 timeout_ms,
136 },
137 PlexusStreamItem::Done { metadata } => StreamItem::Done {
138 metadata: meta(metadata),
139 },
140 }
141}
142
143impl<A: Activation> Transport for InProcessTransport<A> {
144 fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
145 // A `MethodRef` names an activation as well as a method. Dispatching
146 // a `tickets.*` call into a `health` activation because the caller
147 // wired the wrong client to the wrong transport must not silently
148 // "work" for whichever method names happen to collide.
149 if method.namespace() != self.activation.namespace() {
150 let msg = format!(
151 "InProcessTransport is bound to activation `{}`, but the call is for `{}`",
152 self.activation.namespace(),
153 method,
154 );
155 return Box::pin(futures::stream::once(async move {
156 Err(TransportError::protocol(msg))
157 }));
158 }
159
160 Box::pin(
161 futures::stream::once(async move {
162 match self
163 .activation
164 .call(method.method(), params, self.auth.as_ref(), None)
165 .await
166 {
167 // `call` succeeded: the activation owns the outcome from
168 // here, including any in-band `error` item.
169 Ok(stream) => stream.map(|item| Ok(to_client_item(item))).left_stream(),
170 // `call` failed: nothing was answered.
171 Err(e) => futures::stream::once(async move {
172 Err(TransportError::other(e.to_string()))
173 })
174 .right_stream(),
175 }
176 })
177 .flatten(),
178 )
179 }
180}