Skip to main content

ntex_service/
state.rs

1//! Requests that carry state for a service call.
2//!
3//! [`RequestState`] splits an input into `(state, request)`. Both the named
4//! [`State<St, Req>`] wrapper and the tuple `(St, Req)` implement it, allowing
5//! protocol boundaries to accept either representation.
6//!
7//! These types package data; they do not create a pipeline or automatically
8//! change its state. After unpacking, the caller can pass the state to a
9//! [`crate::pipeline::PipelineState`] operation or use it to construct a
10//! [`crate::Pipeline`]. A service accesses the supplied state through
11//! [`crate::Ctx::st`].
12//!
13//! # Example
14//!
15//! ```
16//! use ntex_service::state::{RequestState, State};
17//!
18//! let input = State {
19//!     state: "connection-1",
20//!     req: 42,
21//! };
22//! let (state, request) = input.unpack();
23//! assert_eq!(state, "connection-1");
24//! assert_eq!(request, 42);
25//!
26//! assert_eq!(("connection-2", 7).unpack(), ("connection-2", 7));
27//! ```
28//!
29//! # Framework guide
30//!
31//! See [Carrying state with a request](https://docs.ntex.rs/3-state.html#carrying-state-with-a-request).
32
33/// A request that carries state for a service call.
34#[diagnostic::on_unimplemented(
35    message = "`{Self}` does not carry state for `{Req}` requests",
36    label = "expected `State {{ state, req }}` or a `(state, req)` tuple",
37    note = "pair the request with its state using `State {{ state, req: {Req} }}` or `(state, req)`"
38)]
39pub trait RequestState<Req> {
40    /// State extracted from the request.
41    type State: 'static;
42
43    /// Splits this value into its state and request components.
44    fn unpack(self) -> (Self::State, Req);
45}
46
47/// A request paired with state for the duration of a service call.
48#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
49pub struct State<St, Req> {
50    /// Request passed to the service.
51    pub req: Req,
52    /// State made available while processing the request.
53    pub state: St,
54}
55
56impl<Req, St: 'static> RequestState<Req> for State<St, Req> {
57    type State = St;
58
59    #[inline]
60    fn unpack(self) -> (St, Req) {
61        let State { state, req } = self;
62        (state, req)
63    }
64}
65
66impl<Req, St: 'static> RequestState<Req> for (St, Req) {
67    type State = St;
68
69    #[inline]
70    fn unpack(self) -> (St, Req) {
71        (self.0, self.1)
72    }
73}