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 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.
35
36use futures::StreamExt;
37use plexus_client::{ItemStream, MethodRef, StreamItem, StreamMetadata, Transport, TransportError};
38use serde_json::Value;
39
40use super::auth::AuthContext;
41use super::plexus::Activation;
42use super::types::PlexusStreamItem;
43
44/// A [`Transport`] backed directly by one [`Activation`].
45///
46/// ```ignore
47/// let client = TicketsClient::new(InProcessTransport::new(Tickets::new(store)));
48/// let tickets = client.list_all(None, None).await?;
49/// ```
50#[derive(Debug, Clone)]
51pub struct InProcessTransport<A> {
52    activation: A,
53    auth: Option<AuthContext>,
54}
55
56impl<A: Activation> InProcessTransport<A> {
57    /// Dispatch anonymously.
58    pub fn new(activation: A) -> Self {
59        Self {
60            activation,
61            auth: None,
62        }
63    }
64
65    /// Dispatch with an auth context attached to every call — the
66    /// equivalent of a transport carrying a session cookie.
67    pub fn with_auth(activation: A, auth: AuthContext) -> Self {
68        Self {
69            activation,
70            auth: Some(auth),
71        }
72    }
73
74    /// Borrow the activation, e.g. to assert on server-side state after a
75    /// call.
76    pub fn activation(&self) -> &A {
77        &self.activation
78    }
79}
80
81/// Translate the server envelope into the client one.
82///
83/// The client type is looser by design (see `plexus-client`'s
84/// `envelope` module): every field the REST bridge drops is optional there.
85/// In-process nothing is dropped, so every field is carried.
86fn to_client_item(item: PlexusStreamItem) -> StreamItem {
87    fn meta(m: super::types::StreamMetadata) -> Option<StreamMetadata> {
88        Some(StreamMetadata {
89            provenance: m.provenance,
90            plexus_hash: m.plexus_hash,
91            timestamp: m.timestamp,
92        })
93    }
94
95    match item {
96        PlexusStreamItem::Data {
97            metadata,
98            content_type,
99            content,
100        } => StreamItem::Data {
101            metadata: meta(metadata),
102            content_type: Some(content_type),
103            content,
104        },
105        PlexusStreamItem::Progress {
106            metadata,
107            message,
108            percentage,
109        } => StreamItem::Progress {
110            metadata: meta(metadata),
111            message,
112            percentage,
113        },
114        PlexusStreamItem::Error {
115            metadata,
116            message,
117            code,
118            recoverable,
119        } => StreamItem::Error {
120            metadata: meta(metadata),
121            message,
122            code,
123            recoverable,
124        },
125        PlexusStreamItem::Request {
126            request_id,
127            request_data,
128            timeout_ms,
129        } => StreamItem::Request {
130            request_id,
131            request_data,
132            timeout_ms,
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: nothing was answered.
168                    Err(e) => futures::stream::once(async move {
169                        Err(TransportError::other(e.to_string()))
170                    })
171                    .right_stream(),
172                }
173            })
174            .flatten(),
175        )
176    }
177}