Skip to main content

ntex_service/
pipeline.rs

1//! Execution containers and shared handles for service pipelines.
2//!
3//! A pipeline owns a service, initializes its binding dependencies, and
4//! coordinates readiness, calls, and shutdown.
5//!
6//! - [`Pipeline`] owns one state value for all operations.
7//! - [`PipelineState`] accepts a state reference for each operation instead.
8//! - [`PipelineBinding`] and [`PipelineStateBinding`] provide independently
9//!   registered handles to the same service and readiness machinery.
10//!   [`PipelineState::bind_state`] attaches an owned state value to a handle.
11//! - [`PipelineCall`] is an owned call future that keeps its pipeline alive
12//!   without borrowing the originating handle.
13//! - [`PipelineFactory`] creates a service and wraps it with its state.
14//!
15//! Calls wait for readiness before dispatch. Successful readiness is shared
16//! by all handles until a subscribed [`crate::ReadyNotifier`] invalidates it;
17//! neither a call nor a different state value consumes that success.
18//! Independent readiness gates require separate pipelines or
19//! [`crate::ReadyBinding`] wrappers.
20//!
21//! Pipelines and their handles are local to a thread. Services whose readiness
22//! changes must subscribe in [`Service::bind`] and notify on those changes;
23//! waking a task alone does not invalidate cached readiness.
24//!
25//! # Example
26//!
27//! ```
28//! use ntex_service::pipeline::{Pipeline, PipelineState};
29//!
30//! # async fn example() -> Result<(), ()> {
31//! let pipeline = Pipeline::new(
32//!     10u32,
33//!     async |state: &u32, req: u32| Ok::<_, ()>(*state + req),
34//! );
35//! let handle = pipeline.bind();
36//! assert_eq!(handle.call(2).await?, 12);
37//!
38//! let stateful = PipelineState::new(
39//!     async |state: &u32, req: u32| Ok::<_, ()>(*state + req),
40//! );
41//! assert_eq!(stateful.call(2, &20).await?, 22);
42//! assert_eq!(stateful.call(2, &30).await?, 32);
43//! # Ok(())
44//! # }
45//! ```
46//!
47//! # Framework guide
48//!
49//! - [Service Pipelines](https://docs.ntex.rs/2-pipeline.html)
50//! - [Service State](https://docs.ntex.rs/3-state.html)
51
52use std::{fmt, future, future::Future, marker::PhantomData, pin::Pin, task::Context, task::Poll};
53
54use crate::pl_inner::PipelineApi;
55use crate::{
56    BindCtx, IntoService, ReadyCallback, ReadyLink, Service, ServiceCaller, util::CallFuture,
57};
58
59pub use crate::pl_factory::PipelineFactory;
60pub use crate::pl_state::{PipelineState, PipelineStateBinding};
61
62/// Execution container for a service and its state.
63///
64/// A pipeline coordinates readiness, calls, and shutdown for the enclosed
65/// service chain.
66/// Successful readiness is shared by every binding until a subscribed
67/// [`crate::ReadyNotifier`] invalidates it. Calls do not consume readiness.
68///
69/// Shutdown is advisory: it shuts down the enclosed service, but does not
70/// reject later calls. Readiness checks return `Ok(())` once shutdown has
71/// started, and calls are still forwarded to the service. Callers that must
72/// stop admitting work check [`Pipeline::is_shutdown`].
73pub struct Pipeline<Req, Res, Err> {
74    api: PipelineApi<Req, Res, Err>,
75}
76
77/// An independently registered handle to a [`Pipeline`].
78///
79/// Bindings share the pipeline and its readiness state. Cloning a binding
80/// registers another handle.
81pub struct PipelineBinding<Req, Res, Err> {
82    idx: u32,
83    api: PipelineApi<Req, Res, Err>,
84}
85
86impl<Req, Res, Err> Pipeline<Req, Res, Err>
87where
88    Req: 'static,
89    Res: 'static,
90    Err: 'static,
91{
92    #[inline]
93    /// Creates a pipeline containing `service` and `state`.
94    pub fn new<S, St>(st: St, service: impl IntoService<S, St, Req>) -> Self
95    where
96        S: Service<St, Req, Res = Res, Error = Err> + 'static,
97        St: 'static,
98    {
99        Pipeline {
100            api: PipelineApi::new(service.into_service(), st),
101        }
102    }
103
104    #[inline]
105    /// Returns when the pipeline is ready to process requests.
106    ///
107    /// Reuses valid shared readiness without allocating a readiness future.
108    /// Cancelling the active caller drops its check and lets another waiter
109    /// take ownership. Returns successfully if pipeline shutdown has started,
110    /// like [`Self::poll_ready`].
111    ///
112    /// The first caller that finds readiness invalid runs the shared check in its
113    /// own future, and other waiters wait for it. Like a held lock, a pending
114    /// future must be polled or dropped: keeping it alive without polling stalls
115    /// every other readiness waiter on this pipeline.
116    pub fn ready(&self) -> impl Future<Output = Result<(), Err>> {
117        let mut ready = self.api.ready(0);
118        future::poll_fn(move |cx| {
119            if self.api.is_shutdown() {
120                Poll::Ready(Ok(()))
121            } else {
122                Pin::new(&mut ready).poll(cx)
123            }
124        })
125    }
126
127    #[inline]
128    /// Returns `true` while the pipeline's shared readiness is valid.
129    ///
130    /// Does not run or register a readiness check. `false` means readiness is
131    /// unknown or was invalidated, not that the service is not ready.
132    pub fn is_ready(&self) -> bool {
133        self.api.is_ready()
134    }
135
136    #[inline]
137    /// Waits for readiness, then calls the service.
138    ///
139    /// Reuses valid shared readiness without consuming it. Calls are forwarded
140    /// even after shutdown has started; see [`Pipeline`].
141    pub fn call(&self, req: Req) -> impl Future<Output = Result<Res, Err>> {
142        self.api.call(req)
143    }
144
145    #[inline]
146    /// Returns an owned future that waits for readiness and calls the service.
147    ///
148    /// Unlike [`Pipeline::call`], the returned future does not borrow the
149    /// pipeline and can be moved between local tasks. Shared readiness is
150    /// consulted when the future is polled and the call is dispatched, not
151    /// when the future is constructed.
152    pub fn call_static(&self, req: Req) -> PipelineCall<Req, Res, Err> {
153        PipelineCall::new(self.api.call_static(req))
154    }
155
156    #[inline]
157    /// Returns `Ready` when the pipeline is ready to process requests.
158    ///
159    /// Registers the task for readiness changes and reuses valid shared
160    /// readiness. A pending check is retained by the pipeline, even if this
161    /// task stops polling; other callers can continue driving it.
162    /// The retained check and its wake sources run on this pipeline's thread.
163    /// Its checker wakers must also be finally dropped on that thread, even
164    /// after the pipeline is dropped; foreign wakes or final drops panic.
165    pub fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Err>> {
166        self.api.poll_ready(cx)
167    }
168
169    #[inline]
170    /// Returns `Ready` when the service has been properly shut down.
171    pub fn poll_shutdown(&self, cx: &mut Context<'_>) -> Poll<()> {
172        self.api.poll_shutdown(cx)
173    }
174
175    #[inline]
176    /// Checks whether pipeline shutdown has been initiated.
177    ///
178    /// The pipeline does not reject calls after shutdown; callers use this to
179    /// stop admitting new work.
180    pub fn is_shutdown(&self) -> bool {
181        self.api.is_shutdown()
182    }
183
184    #[inline]
185    /// Shuts down the enclosed service.
186    ///
187    /// Marks the pipeline as shutting down, then waits for the service's
188    /// shutdown. Later calls are not rejected; see [`Pipeline`].
189    pub fn shutdown(&self) -> impl Future<Output = ()> {
190        future::poll_fn(move |cx| self.api.poll_shutdown(cx))
191    }
192
193    #[inline]
194    /// Creates a new binding to this pipeline.
195    ///
196    /// The binding can be used to check readiness and call the service.
197    pub fn bind(&self) -> PipelineBinding<Req, Res, Err> {
198        PipelineBinding::new(self)
199    }
200
201    #[inline]
202    /// Registers a callback for notifications reaching this pipeline's scope.
203    ///
204    /// Registration is shared with all bindings and persists until the scope
205    /// is dropped. Repeated registration of the same handle is idempotent.
206    /// The callback receives `0` for this root scope.
207    /// See [`ReadyCallback`] for notification semantics.
208    pub fn on_notify(&self, callback: &ReadyCallback) {
209        self.api.on_notify(callback);
210    }
211
212    #[inline]
213    /// Registers this pipeline as a readiness dependency of the enclosing service.
214    ///
215    /// Call from [`Service::bind`] so changes to this pipeline's readiness also
216    /// invalidate the enclosing scope. Repeated registration is idempotent and
217    /// does not rebind the inner service or create another runtime handle.
218    pub fn bind_to(&self, ctx: &BindCtx<'_>) {
219        self.api.bind_to(ctx);
220    }
221
222    /// Returns an explicit, non-owning endpoint for this pipeline's readiness.
223    ///
224    /// Register with [`BindCtx::subscribe_pipeline`], or use [`Self::bind_to`]
225    /// as shorthand. All pipeline bindings share the same endpoint.
226    pub fn readiness_link(&self) -> ReadyLink {
227        self.api.readiness_link()
228    }
229}
230
231impl<Req, Res, Err> ServiceCaller<Req, Res, Err> for Pipeline<Req, Res, Err>
232where
233    Req: 'static,
234    Res: 'static,
235    Err: 'static,
236{
237    #[inline]
238    fn call_service(&self, req: Req) -> impl Future<Output = Result<Res, Err>> {
239        self.api.call(req)
240    }
241}
242
243impl<Req, Res, Err> Drop for Pipeline<Req, Res, Err> {
244    #[inline]
245    fn drop(&mut self) {
246        self.api.unreg(0);
247    }
248}
249
250impl<Req, Res, Err> PipelineBinding<Req, Res, Err>
251where
252    Req: 'static,
253    Res: 'static,
254    Err: 'static,
255{
256    fn new(pl: &Pipeline<Req, Res, Err>) -> Self {
257        Self {
258            idx: pl.api.reg(),
259            api: pl.api.clone(),
260        }
261    }
262
263    pub(crate) fn with(idx: u32, api: PipelineApi<Req, Res, Err>) -> Self {
264        Self { idx, api }
265    }
266
267    #[inline]
268    /// Waits until the pipeline is ready to process a request.
269    ///
270    /// Reuses valid shared readiness without consuming it or allocating a
271    /// readiness future. Returns successfully if pipeline shutdown has
272    /// started, like [`Pipeline::ready`].
273    ///
274    /// The first caller that finds readiness invalid runs the shared check in its
275    /// own future, and other waiters wait for it. Like a held lock, a pending
276    /// future must be polled or dropped: keeping it alive without polling stalls
277    /// every other readiness waiter on this pipeline.
278    pub fn ready(&self) -> impl Future<Output = Result<(), Err>> {
279        self.api.ready(self.idx)
280    }
281
282    #[inline]
283    /// Checks whether pipeline shutdown has been initiated.
284    ///
285    /// See [`Pipeline::is_shutdown`].
286    pub fn is_shutdown(&self) -> bool {
287        self.api.is_shutdown()
288    }
289
290    #[inline]
291    /// Waits for readiness, then calls the service.
292    ///
293    /// Reuses valid shared readiness without consuming it. Calls are forwarded
294    /// even after shutdown has started; see [`Pipeline`].
295    pub fn call(&self, req: Req) -> impl Future<Output = Result<Res, Err>> {
296        self.api.call(req)
297    }
298
299    #[inline]
300    /// Returns an owned future that waits for readiness and calls the service.
301    ///
302    /// The returned future does not borrow this binding and can be moved between
303    /// local tasks. Shared readiness is consulted when the future is polled
304    /// and the call is dispatched, not when the future is constructed.
305    pub fn call_static(&self, req: Req) -> PipelineCall<Req, Res, Err> {
306        PipelineCall::new(self.api.call_static(req))
307    }
308
309    #[inline]
310    /// Registers a callback on the shared pipeline scope.
311    ///
312    /// The callback receives `0` for this root scope.
313    /// Dropping this binding does not remove the registration.
314    /// See [`Pipeline::on_notify`] and [`ReadyCallback`] for details.
315    pub fn on_notify(&self, callback: &ReadyCallback) {
316        self.api.on_notify(callback);
317    }
318
319    #[inline]
320    /// Registers this handle's pipeline as a readiness dependency.
321    ///
322    /// Call from [`Service::bind`]. See [`Pipeline::bind_to`] for details.
323    pub fn bind_to(&self, ctx: &BindCtx<'_>) {
324        self.api.bind_to(ctx);
325    }
326
327    /// Returns the shared pipeline's readiness endpoint.
328    ///
329    /// See [`Pipeline::readiness_link`] and [`ReadyLink`].
330    pub fn readiness_link(&self) -> ReadyLink {
331        self.api.readiness_link()
332    }
333}
334
335impl<Req, Res, Err> Drop for PipelineBinding<Req, Res, Err> {
336    #[inline]
337    fn drop(&mut self) {
338        self.api.unreg(self.idx);
339    }
340}
341
342impl<Req, Res, Err> Clone for PipelineBinding<Req, Res, Err> {
343    fn clone(&self) -> Self {
344        Self {
345            idx: self.api.reg(),
346            api: self.api.clone(),
347        }
348    }
349}
350
351#[must_use = "futures do nothing unless polled"]
352/// An owned future for a pipeline service call.
353///
354/// Created by [`Pipeline::call_static`] and [`PipelineBinding::call_static`]. The
355/// future keeps the pipeline alive. It does not check whether the pipeline is shut
356/// down; the request is passed to the service as usual.
357pub struct PipelineCall<Req, Res, Err> {
358    // owns the pipeline
359    fut: CallFuture<'static, Result<Res, Err>>,
360    _r: PhantomData<fn(Req)>,
361}
362
363impl<Req, Res, Err> PipelineCall<Req, Res, Err> {
364    fn new(fut: CallFuture<'static, Result<Res, Err>>) -> Self {
365        PipelineCall {
366            fut,
367            _r: PhantomData,
368        }
369    }
370}
371
372impl<Req, Res, Err> future::Future for PipelineCall<Req, Res, Err> {
373    type Output = Result<Res, Err>;
374
375    #[inline]
376    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
377        Pin::new(&mut self.fut).poll(cx)
378    }
379}
380
381impl<Req, Res, Err> fmt::Debug for Pipeline<Req, Res, Err> {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        f.debug_struct("Pipeline").finish()
384    }
385}
386
387impl<Req, Res, Err> fmt::Debug for PipelineBinding<Req, Res, Err> {
388    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389        f.debug_struct("PipelineBinding")
390            .field("idx", &self.idx)
391            .finish()
392    }
393}
394
395impl<Req, Res, Err> fmt::Debug for PipelineCall<Req, Res, Err> {
396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397        f.debug_struct("PipelineCall").finish()
398    }
399}