Skip to main content

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 transports are meant to be interchangeable, which means they must
19//! agree on *which layer* a failure belongs to — and over the wire a service
20//! answers a call it cannot dispatch with a typed error frame, not a broken
21//! connection (RETURNS-9):
22//!
23//! | Failure | Becomes | Why |
24//! |---|---|---|
25//! | [`Activation::call`] returns `Err(PlexusError)` | one error frame: `RemoteError::from(&e)`, provenance the activation, not recoverable, no `done` | what a service's `call` route sends for the same failure — unknown method, missing or malformed param, scope gate denied — so a client sees `ClientError::Remote(RemoteError)` in-process exactly as it would over a socket |
26//! | the stream contains a [`PlexusStreamItem::Error`] | that frame | the activation answered, and the answer is an error. |
27//! | the [`MethodRef`]'s namespace is not this activation's | a `TransportError` (protocol) | nothing was dispatched: the client was wired to the wrong transport, which no server would answer for. |
28//!
29//! # Not a way to skip the hub
30//!
31//! `DynamicHub` applies the scope gate, provenance and credential-envelope
32//! assembly. This transport applies none of them: it is `Activation::call`
33//! and nothing else. Reaching for it outside a test is a smell: a program
34//! that imports a whole hub calls it through
35//! [`HubTransport`](super::hub_transport::HubTransport) (LOCAL-6).
36
37use futures::StreamExt;
38use plexus_client::{
39    ItemStream, MethodRef, StreamItem, StreamMetadata, Transport, TransportError,
40};
41use serde_json::Value;
42
43use super::auth::AuthContext;
44use super::context::PlexusContext;
45use super::plexus::Activation;
46use super::types::PlexusStreamItem;
47
48/// A [`Transport`] backed directly by one [`Activation`].
49///
50/// ```ignore
51/// let client = TicketsClient::new(InProcessTransport::new(Tickets::new(store)));
52/// let health = client.health().await?;                                    // one item
53/// let tickets: Vec<_> = client.list(None, None).try_collect().await?;     // many
54/// ```
55#[derive(Debug, Clone)]
56pub struct InProcessTransport<A> {
57    activation: A,
58    auth: Option<AuthContext>,
59}
60
61impl<A: Activation> InProcessTransport<A> {
62    /// Dispatch anonymously.
63    pub fn new(activation: A) -> Self {
64        Self {
65            activation,
66            auth: None,
67        }
68    }
69
70    /// Dispatch with an auth context attached to every call — the
71    /// equivalent of a transport carrying a session cookie.
72    pub fn with_auth(activation: A, auth: AuthContext) -> Self {
73        Self {
74            activation,
75            auth: Some(auth),
76        }
77    }
78
79    /// Borrow the activation, e.g. to assert on server-side state after a
80    /// call.
81    pub fn activation(&self) -> &A {
82        &self.activation
83    }
84}
85
86/// Translate the server envelope into the client one.
87///
88/// The client type is looser by design (see `plexus-client`'s
89/// `envelope` module): every field the REST bridge drops is optional there.
90/// In-process nothing is dropped, so every field is carried.
91pub(crate) fn to_client_item(item: PlexusStreamItem) -> StreamItem {
92    fn meta(m: super::types::StreamMetadata) -> Option<StreamMetadata> {
93        Some(StreamMetadata {
94            provenance: m.provenance,
95            plexus_hash: m.plexus_hash,
96            timestamp: m.timestamp,
97        })
98    }
99
100    match item {
101        PlexusStreamItem::Data {
102            metadata,
103            content_type,
104            content,
105        } => StreamItem::Data {
106            metadata: meta(std::sync::Arc::unwrap_or_clone(metadata)),
107            content_type: Some(content_type.into_owned()),
108            content: content.into_value(),
109        },
110        PlexusStreamItem::Progress {
111            metadata,
112            content_type,
113            content,
114        } => StreamItem::Progress {
115            metadata: meta(metadata),
116            content_type: Some(content_type),
117            content,
118        },
119        PlexusStreamItem::Error {
120            metadata,
121            recoverable,
122            message,
123            code,
124            error,
125            fields,
126        } => StreamItem::Error {
127            metadata: meta(metadata),
128            recoverable,
129            message: Some(message),
130            code,
131            error,
132            fields,
133        },
134        PlexusStreamItem::Done { metadata } => StreamItem::Done {
135            metadata: meta(metadata),
136        },
137    }
138}
139
140impl<A: Activation> Transport for InProcessTransport<A> {
141    fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
142        // A `MethodRef` names an activation as well as a method. Dispatching
143        // a `tickets.*` call into a `health` activation because the caller
144        // wired the wrong client to the wrong transport must not silently
145        // "work" for whichever method names happen to collide.
146        if method.namespace() != self.activation.namespace() {
147            let msg = format!(
148                "InProcessTransport is bound to activation `{}`, but the call is for `{}`",
149                self.activation.namespace(),
150                method,
151            );
152            return Box::pin(futures::stream::once(async move {
153                Err(TransportError::protocol(msg))
154            }));
155        }
156
157        Box::pin(
158            futures::stream::once(async move {
159                match self
160                    .activation
161                    .call(method.method(), params, self.auth.as_ref(), None)
162                    .await
163                {
164                    // `call` succeeded: the activation owns the outcome from
165                    // here, including any in-band `error` item.
166                    Ok(stream) => stream.map(|item| Ok(to_client_item(item))).left_stream(),
167                    // `call` failed: the call failed, typed — one error
168                    // frame, as a service's `call` route sends it (no `done`).
169                    Err(e) => futures::stream::once(async move {
170                        Ok(to_client_item(PlexusStreamItem::from_plexus_error(
171                            super::types::StreamMetadata::new(
172                                vec![self.activation.namespace().to_string()],
173                                PlexusContext::hash(),
174                            ),
175                            &e,
176                            false,
177                        )))
178                    })
179                    .right_stream(),
180                }
181            })
182            .flatten(),
183        )
184    }
185}