Skip to main content

astrs_node_api/patterns/
service.rs

1//! Request/response over ordinary edges (blueprint §9.4, `request_id`).
2//!
3//! ```text
4//!   client                                     server
5//!     │ service_request(req)  ──► request_id=R ──►│
6//!     │                                           │ ServiceRequest::from_event
7//!     │◄── request_id=R ◄──  service_response(…) ──┤
8//!     │ ServiceResponse::matches(R)               │
9//! ```
10//!
11//! A service is two edges and one metadata key. The client stamps a fresh
12//! `request_id`; the server copies it onto the answer; the client matches it.
13//! Nothing else is needed, and nothing else is provided — which is why a
14//! service in AstRS records, replays and type-checks exactly like any other
15//! edge.
16//!
17//! # What goes wrong without help
18//!
19//! Answering with *no* `request_id`, or with a fresh one, leaves a client
20//! waiting forever. [`Node::service_response`] takes the request's metadata
21//! rather than an id, so the id it copies is the one that arrived; and it
22//! *refuses* — [`crate::NodeError::Pattern`] — when the metadata carries no
23//! request id at all, rather than sending an uncorrelated answer.
24
25use core::fmt;
26
27use astrs_data::AstrsMessage;
28use astrs_wire::{DataId, Metadata};
29
30use crate::error::{NodeError, Result};
31use crate::events::Event;
32use crate::node::Node;
33use crate::output::{Output, RawOutput};
34use crate::payload::Payload;
35
36/// One service exchange's correlation id (§9.4).
37#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
38pub struct RequestId(String);
39
40impl RequestId {
41    /// A fresh id.
42    #[must_use]
43    pub fn generate() -> Self {
44        Self(super::fresh_id())
45    }
46
47    /// Wraps an existing id.
48    #[must_use]
49    pub fn new(id: impl Into<String>) -> Self {
50        Self(id.into())
51    }
52
53    /// The id as text.
54    #[must_use]
55    pub fn as_str(&self) -> &str {
56        &self.0
57    }
58
59    /// Unwraps the id.
60    #[must_use]
61    pub fn into_string(self) -> String {
62        self.0
63    }
64}
65
66impl fmt::Display for RequestId {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(&self.0)
69    }
70}
71
72impl From<String> for RequestId {
73    fn from(id: String) -> Self {
74        Self(id)
75    }
76}
77
78impl PartialEq<str> for RequestId {
79    fn eq(&self, other: &str) -> bool {
80        self.0 == other
81    }
82}
83
84/// An incoming service request, as the server sees it.
85#[derive(Debug)]
86pub struct ServiceRequest {
87    /// The input it arrived on.
88    pub input: DataId,
89    /// Its correlation id.
90    pub id: RequestId,
91    /// The metadata to pass to [`Node::service_response`].
92    pub metadata: Metadata,
93    /// The request payload.
94    pub payload: Payload,
95}
96
97impl ServiceRequest {
98    /// Reads a request out of an event, if it is one.
99    ///
100    /// An input with no `request_id` is not a service request — it is an
101    /// ordinary message, and a server that treated it as one would answer
102    /// into the void.
103    pub fn from_event(event: Event) -> core::result::Result<Self, Box<Event>> {
104        let Event::Input { id, meta, data } = event else {
105            return Err(Box::new(event));
106        };
107        let Some(request_id) = meta.request_id().map(RequestId::new) else {
108            return Err(Box::new(Event::Input { id, meta, data }));
109        };
110        Ok(Self {
111            input: id,
112            id: request_id,
113            metadata: meta,
114            payload: data,
115        })
116    }
117
118    /// Decodes the request body.
119    ///
120    /// # Errors
121    ///
122    /// [`NodeError::Data`] when the payload is not a `T`.
123    pub fn view<T: crate::message::FromPayload>(&self) -> Result<T> {
124        self.payload.view()
125    }
126}
127
128/// An incoming service response, as the client sees it.
129#[derive(Debug)]
130pub struct ServiceResponse {
131    /// The input it arrived on.
132    pub input: DataId,
133    /// The id of the request it answers.
134    pub id: RequestId,
135    /// Its metadata.
136    pub metadata: Metadata,
137    /// The response payload.
138    pub payload: Payload,
139}
140
141impl ServiceResponse {
142    /// Reads a response out of an event, if it is one.
143    pub fn from_event(event: Event) -> core::result::Result<Self, Box<Event>> {
144        let Event::Input { id, meta, data } = event else {
145            return Err(Box::new(event));
146        };
147        let Some(request_id) = meta.request_id().map(RequestId::new) else {
148            return Err(Box::new(Event::Input { id, meta, data }));
149        };
150        Ok(Self {
151            input: id,
152            id: request_id,
153            metadata: meta,
154            payload: data,
155        })
156    }
157
158    /// Whether this answers `request`.
159    #[must_use]
160    pub fn matches(&self, request: &RequestId) -> bool {
161        &self.id == request
162    }
163
164    /// Decodes the response body.
165    ///
166    /// # Errors
167    ///
168    /// [`NodeError::Data`] when the payload is not a `T`.
169    pub fn view<T: crate::message::FromPayload>(&self) -> Result<T> {
170        self.payload.view()
171    }
172}
173
174impl Node {
175    /// Publishes a typed service request, returning its correlation id
176    /// (§9.4).
177    ///
178    /// # Errors
179    ///
180    /// As [`Output::send`].
181    pub fn service_request<T: AstrsMessage>(
182        &self,
183        output: &mut Output<T>,
184        value: impl Into<T>,
185    ) -> Result<RequestId> {
186        let id = RequestId::generate();
187        let mut metadata = self.metadata();
188        metadata.set_request_id(id.as_str());
189        output.send(value, metadata)?;
190        Ok(id)
191    }
192
193    /// Publishes an untyped service request, returning its correlation id.
194    ///
195    /// # Errors
196    ///
197    /// As [`RawOutput::send_bytes`].
198    pub fn service_request_bytes(
199        &self,
200        output: &mut RawOutput,
201        payload: impl AsRef<[u8]>,
202    ) -> Result<RequestId> {
203        let id = RequestId::generate();
204        let mut metadata = self.metadata();
205        metadata.set_request_id(id.as_str());
206        output.send_bytes(payload, metadata)?;
207        Ok(id)
208    }
209
210    /// Publishes a typed response to `request` (§9.4).
211    ///
212    /// `request` is the *request's* metadata; the id is copied from it, so a
213    /// server cannot answer with the wrong one.
214    ///
215    /// # Errors
216    ///
217    /// [`NodeError::Pattern`] when `request` carries no `request_id`, plus
218    /// whatever [`Output::send`] reports.
219    pub fn service_response<T: AstrsMessage>(
220        &self,
221        output: &mut Output<T>,
222        request: &Metadata,
223        value: impl Into<T>,
224    ) -> Result<()> {
225        let metadata = response_metadata(request)?;
226        output.send(value, metadata)
227    }
228
229    /// Publishes an untyped response to `request`.
230    ///
231    /// # Errors
232    ///
233    /// As [`Node::service_response`].
234    pub fn service_response_bytes(
235        &self,
236        output: &mut RawOutput,
237        request: &Metadata,
238        payload: impl AsRef<[u8]>,
239    ) -> Result<()> {
240        let metadata = response_metadata(request)?;
241        output.send_bytes(payload, metadata)
242    }
243
244    /// The metadata a response to `request` must carry.
245    ///
246    /// Exposed for a node that builds its own payload but wants the
247    /// correlation handled for it.
248    ///
249    /// # Errors
250    ///
251    /// [`NodeError::Pattern`] when `request` carries no `request_id`.
252    pub fn response_metadata(&self, request: &Metadata) -> Result<Metadata> {
253        response_metadata(request)
254    }
255}
256
257/// Derives a response's metadata from its request's.
258///
259/// [`Metadata::follow`] keeps the correlation keys and re-stamps the clock, so
260/// the answer is causally after the question and carries the same id.
261fn response_metadata(request: &Metadata) -> Result<Metadata> {
262    if request.request_id().is_none() {
263        return Err(NodeError::Pattern(
264            "a service response needs the request's `request_id`; this metadata has none"
265                .to_owned(),
266        ));
267    }
268    Ok(request.follow())
269}
270
271#[cfg(test)]
272mod tests {
273    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
274
275    use super::*;
276    use crate::message::{AstrsMessage, Scalar};
277    use crate::testing::TestHarness;
278    use astrs_time::HlcTimestamp;
279
280    #[test]
281    fn request_ids_are_fresh_and_comparable() {
282        let first = RequestId::generate();
283        let second = RequestId::generate();
284        assert_ne!(first, second);
285        assert_eq!(first.to_string(), first.as_str());
286        assert_eq!(RequestId::new("abc"), RequestId::from("abc".to_owned()));
287        assert!(RequestId::new("abc") == *"abc");
288        assert_eq!(RequestId::new("abc").into_string(), "abc");
289    }
290
291    #[test]
292    fn an_uncorrelated_input_is_not_a_service_message() {
293        let event = Event::Input {
294            id: DataId::new("in").unwrap(),
295            meta: Metadata::new(HlcTimestamp::new(1, 0)),
296            data: Payload::empty(),
297        };
298        let back = ServiceRequest::from_event(event).unwrap_err();
299        assert!(back.is_input());
300        let back = ServiceResponse::from_event(*back).unwrap_err();
301        assert!(back.is_input());
302
303        let control = ServiceRequest::from_event(Event::AllInputsClosed).unwrap_err();
304        assert!(!control.is_input());
305    }
306
307    #[test]
308    fn a_response_without_a_request_id_is_refused() {
309        let mut harness = TestHarness::start().unwrap();
310        let mut output = harness
311            .node
312            .raw_output(TestHarness::DEFAULT_OUTPUT)
313            .unwrap();
314        let error = harness
315            .node
316            .service_response_bytes(&mut output, &Metadata::default(), vec![1])
317            .unwrap_err();
318        assert!(matches!(error, NodeError::Pattern(_)), "{error}");
319        assert!(
320            harness
321                .node
322                .response_metadata(&Metadata::default())
323                .is_err()
324        );
325    }
326
327    #[test]
328    fn a_full_round_trip_between_two_nodes() {
329        // client --request--> server --response--> client
330        let daemon = crate::testing::MockDaemon::start().unwrap();
331        let client_spec = astrs_wire::NodeSpawnSpec::new(
332            daemon.dataflow(),
333            astrs_wire::NodeId::new("client").unwrap(),
334            0,
335            astrs_wire::NodeSource::Dynamic,
336        )
337        .with_output(astrs_wire::OutputSpec::new(DataId::new("request").unwrap()))
338        .with_input(astrs_wire::InputSpec::new(
339            DataId::new("response").unwrap(),
340            astrs_wire::PortRef::from_parts("server", "response").unwrap(),
341        ));
342        let server_spec = astrs_wire::NodeSpawnSpec::new(
343            daemon.dataflow(),
344            astrs_wire::NodeId::new("server").unwrap(),
345            0,
346            astrs_wire::NodeSource::Dynamic,
347        )
348        .with_input(astrs_wire::InputSpec::new(
349            DataId::new("request").unwrap(),
350            astrs_wire::PortRef::from_parts("client", "request").unwrap(),
351        ))
352        .with_output(astrs_wire::OutputSpec::new(
353            DataId::new("response").unwrap(),
354        ));
355
356        let (mut client, mut client_events) = daemon.connect_node(client_spec).unwrap();
357        let (mut server, mut server_events) = daemon.connect_node(server_spec).unwrap();
358
359        let mut request_out = client.output::<Scalar<f64>>("request").unwrap();
360        let id = client.service_request(&mut request_out, 21.0_f64).unwrap();
361
362        // Server side.
363        let event = server_events
364            .recv_timeout(std::time::Duration::from_secs(5))
365            .unwrap()
366            .expect("the request");
367        let request = ServiceRequest::from_event(event).expect("a correlated request");
368        assert_eq!(request.id, id);
369        assert_eq!(request.input.as_str(), "request");
370        let value = request.view::<Scalar<f64>>().unwrap().into_inner();
371
372        let mut response_out = server.output::<Scalar<f64>>("response").unwrap();
373        server
374            .service_response(&mut response_out, &request.metadata, value * 2.0)
375            .unwrap();
376
377        // Client side.
378        let event = client_events
379            .recv_timeout(std::time::Duration::from_secs(5))
380            .unwrap()
381            .expect("the response");
382        let response = ServiceResponse::from_event(event).expect("a correlated response");
383        assert!(response.matches(&id));
384        assert_eq!(response.view::<Scalar<f64>>().unwrap().into_inner(), 42.0);
385        assert_eq!(response.input.as_str(), "response");
386    }
387
388    #[test]
389    fn an_untyped_request_carries_a_fresh_id() {
390        let mut harness = TestHarness::start().unwrap();
391        let mut output = harness
392            .node
393            .raw_output(TestHarness::DEFAULT_OUTPUT)
394            .unwrap();
395        let id = harness
396            .node
397            .service_request_bytes(&mut output, vec![1, 2, 3])
398            .unwrap();
399        let sends = harness
400            .daemon
401            .wait_for_sends(
402                harness.node.id(),
403                &DataId::new(TestHarness::DEFAULT_OUTPUT).unwrap(),
404                1,
405                std::time::Duration::from_secs(5),
406            )
407            .unwrap();
408        assert_eq!(sends[0].metadata.request_id(), Some(id.as_str()));
409    }
410
411    #[test]
412    fn the_urn_of_a_service_port_is_unchanged_by_correlation() {
413        // Correlation is metadata; the payload type is the payload type.
414        assert_eq!(<Scalar<f64> as AstrsMessage>::URN, "std/core/v1/Float64");
415    }
416}