Skip to main content

tower_batch_control/
worker.rs

1//! Batch worker item handling and run loop implementation.
2
3use std::{
4    pin::Pin,
5    sync::{Arc, Mutex},
6};
7
8use futures::{
9    future::{BoxFuture, OptionFuture},
10    stream::FuturesUnordered,
11    FutureExt, StreamExt,
12};
13use pin_project::pin_project;
14use tokio::{
15    sync::mpsc,
16    time::{sleep, sleep_until, Instant, Sleep},
17};
18use tokio_util::sync::PollSemaphore;
19use tower::{Service, ServiceExt};
20use tracing::Instrument;
21
22use crate::RequestWeight;
23
24use super::{
25    error::{Closed, ServiceError},
26    message::{self, Message},
27    BatchControl,
28};
29
30/// Task that handles processing the buffer. This type should not be used
31/// directly, instead `Buffer` requires an `Executor` that can accept this task.
32///
33/// The struct is `pub` in the private module and the type is *not* re-exported
34/// as part of the public API. This is the "sealed" pattern to include "private"
35/// types in public traits that are not meant for consumers of the library to
36/// implement (only call).
37#[pin_project(PinnedDrop)]
38#[derive(Debug)]
39pub struct Worker<T, Request: RequestWeight>
40where
41    T: Service<BatchControl<Request>>,
42    T::Future: Send + 'static,
43    T::Error: Into<crate::BoxError>,
44{
45    // Batch management
46    //
47    /// A semaphore-bounded channel for receiving requests from the batch wrapper service.
48    rx: mpsc::UnboundedReceiver<Message<Request, T::Future>>,
49
50    /// The wrapped service that processes batches.
51    service: T,
52
53    /// The total weight of pending requests sent to `service`, since the last batch flush.
54    pending_items_weight: usize,
55
56    /// The timer for the pending batch, if it has any items.
57    ///
58    /// The deadline is the earlier of the first item's latency bound and the last item's
59    /// idle bound. No timer runs for an empty batch.
60    pending_batch_timer: Option<Pin<Box<Sleep>>>,
61
62    /// The batches that the worker is concurrently executing.
63    concurrent_batches: FuturesUnordered<BoxFuture<'static, Result<T::Response, T::Error>>>,
64
65    // Errors and termination
66    //
67    /// An error that's populated on permanent service failure.
68    failed: Option<ServiceError>,
69
70    /// A shared error handle that's populated on permanent service failure.
71    error_handle: ErrorHandle,
72
73    /// A cloned copy of the wrapper service's semaphore, used to close the semaphore.
74    close: PollSemaphore,
75
76    // Config
77    //
78    /// The maximum weight of pending items in a batch before it should be flushed and
79    /// pending items should be added to a new batch.
80    max_items_weight_in_batch: usize,
81
82    /// The maximum number of batches that are allowed to run concurrently.
83    max_concurrent_batches: usize,
84
85    /// The maximum delay before processing a batch with items that have a total weight
86    /// that is less than `max_items_weight_in_batch`.
87    max_latency: std::time::Duration,
88
89    /// The maximum idle time after the most recent item in a pending batch.
90    max_idle: std::time::Duration,
91}
92
93/// Get the error out
94#[derive(Debug)]
95pub(crate) struct ErrorHandle {
96    inner: Arc<Mutex<Option<ServiceError>>>,
97}
98
99impl<T, Request: RequestWeight> Worker<T, Request>
100where
101    T: Service<BatchControl<Request>>,
102    T::Future: Send + 'static,
103    T::Error: Into<crate::BoxError>,
104{
105    /// Creates a new batch worker.
106    ///
107    /// See [`Batch::new()`](crate::Batch::new) for details.
108    pub(crate) fn new(
109        service: T,
110        rx: mpsc::UnboundedReceiver<Message<Request, T::Future>>,
111        max_items_weight_in_batch: usize,
112        max_concurrent_batches: usize,
113        max_latency: std::time::Duration,
114        max_idle: std::time::Duration,
115        close: PollSemaphore,
116    ) -> (ErrorHandle, Worker<T, Request>) {
117        let error_handle = ErrorHandle {
118            inner: Arc::new(Mutex::new(None)),
119        };
120
121        let worker = Worker {
122            rx,
123            service,
124            pending_items_weight: 0,
125            pending_batch_timer: None,
126            concurrent_batches: FuturesUnordered::new(),
127            failed: None,
128            error_handle: error_handle.clone(),
129            close,
130            max_items_weight_in_batch,
131            max_concurrent_batches,
132            max_latency,
133            max_idle,
134        };
135
136        (error_handle, worker)
137    }
138
139    /// Process a single worker request.
140    async fn process_req(&mut self, req: Request, tx: message::Tx<T::Future>) {
141        if let Some(ref error) = self.failed {
142            tracing::trace!(
143                ?error,
144                "notifying batch request caller about worker failure",
145            );
146            let _ = tx.send(Err(error.clone()));
147            return;
148        }
149
150        match self.service.ready().await {
151            Ok(svc) => {
152                self.pending_items_weight += req.request_weight();
153                let rsp = svc.call(req.into());
154                let _ = tx.send(Ok(rsp));
155            }
156            Err(e) => {
157                self.failed(e.into());
158                let _ = tx.send(Err(self
159                    .failed
160                    .as_ref()
161                    .expect("Worker::failed did not set self.failed?")
162                    .clone()));
163            }
164        }
165    }
166
167    /// Tell the inner service to flush the current batch.
168    ///
169    /// Waits until the inner service is ready,
170    /// then stores a future which resolves when the batch finishes.
171    async fn flush_service(&mut self) {
172        if self.failed.is_some() {
173            tracing::trace!("worker failure: skipping flush");
174            return;
175        }
176
177        match self.service.ready().await {
178            Ok(ready_service) => {
179                let flush_future = ready_service.call(BatchControl::Flush);
180                self.concurrent_batches.push(flush_future.boxed());
181
182                // Now we have an empty batch.
183                self.pending_items_weight = 0;
184                self.pending_batch_timer = None;
185            }
186            Err(error) => {
187                self.failed(error.into());
188            }
189        }
190    }
191
192    /// Is the current number of concurrent batches above the configured limit?
193    fn can_spawn_new_batches(&self) -> bool {
194        self.concurrent_batches.len() < self.max_concurrent_batches
195    }
196
197    /// Run loop for batch requests, which implements the batch policies.
198    ///
199    /// See [`Batch::new()`](crate::Batch::new) for details.
200    pub async fn run(mut self) {
201        let mut batch_deadline = Instant::now();
202        loop {
203            // Wait on either a new message or the batch timer.
204            //
205            // Drain queued input before an idle flush, but never extend the maximum latency.
206            // Timer cancellation preserves queued messages:
207            // https://docs.rs/tokio/latest/tokio/sync/mpsc/struct.UnboundedReceiver.html#cancel-safety
208            tokio::select! {
209                biased;
210
211                batch_result = self.concurrent_batches.next(), if !self.concurrent_batches.is_empty() => match batch_result.expect("only returns None when empty") {
212                    Ok(_response) => {
213                        tracing::trace!(
214                            pending_items_weight = self.pending_items_weight,
215                            batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
216                            running_batches = self.concurrent_batches.len(),
217                            "batch finished executing",
218                        );
219                    }
220                    Err(error) => {
221                        let error = error.into();
222                        tracing::trace!(?error, "batch execution failed");
223                        self.failed(error);
224                    }
225                },
226
227                Some(()) = OptionFuture::from(self.pending_batch_timer.as_mut()),
228                    if self.pending_batch_timer.is_some()
229                        && (self.rx.is_empty() || Instant::now() >= batch_deadline) => {
230                    // The branch guard can predate arrivals while this select was suspended.
231                    if Instant::now() < batch_deadline && !self.rx.is_empty() {
232                        continue;
233                    }
234                    tracing::trace!(
235                        pending_items_weight = self.pending_items_weight,
236                        batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
237                        running_batches = self.concurrent_batches.len(),
238                        "batch timer expired",
239                    );
240
241                    // TODO: use a batch-specific span to instrument this future.
242                    self.flush_service().await;
243                },
244
245                maybe_msg = self.rx.recv(), if self.can_spawn_new_batches() => match maybe_msg {
246                    Some(msg) => {
247                        tracing::trace!(
248                            pending_items_weight = self.pending_items_weight,
249                            batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
250                            running_batches = self.concurrent_batches.len(),
251                            "batch message received",
252                        );
253
254                        let span = msg.span;
255                        let is_new_batch = self.pending_items_weight == 0;
256
257                        self.process_req(msg.request, msg.tx)
258                            // Apply the provided span to request processing.
259                            .instrument(span)
260                            .await;
261
262                        // Check whether we have too many pending items.
263                        if self.pending_items_weight >= self.max_items_weight_in_batch {
264                            tracing::trace!(
265                                pending_items_weight = self.pending_items_weight,
266                                batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
267                                running_batches = self.concurrent_batches.len(),
268                                "batch is full",
269                            );
270
271                            // TODO: use a batch-specific span to instrument this future.
272                            self.flush_service().await;
273                        } else if is_new_batch {
274                            tracing::trace!(
275                                pending_items_weight = self.pending_items_weight,
276                                batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
277                                running_batches = self.concurrent_batches.len(),
278                                "batch is new, starting timer",
279                            );
280
281                            // The first message in a new batch.
282                            let now = Instant::now();
283                            batch_deadline = now
284                                .checked_add(self.max_latency)
285                                .unwrap_or_else(|| sleep(self.max_latency).deadline());
286                            let idle_deadline = now.checked_add(self.max_idle).unwrap_or(batch_deadline);
287                            self.pending_batch_timer = Some(Box::pin(sleep_until(
288                                batch_deadline.min(idle_deadline),
289                            )));
290                        } else {
291                            tracing::trace!(
292                                pending_items_weight = self.pending_items_weight,
293                                batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
294                                running_batches = self.concurrent_batches.len(),
295                                "waiting for full batch or batch timer",
296                            );
297                            if let Some(timer) = self.pending_batch_timer.as_mut() {
298                                let idle_deadline = Instant::now()
299                                    .checked_add(self.max_idle)
300                                    .unwrap_or(batch_deadline);
301                                timer.as_mut().reset(batch_deadline.min(idle_deadline));
302                            }
303                        }
304                    }
305                    None => {
306                        tracing::trace!("batch channel closed and emptied, exiting worker task");
307
308                        return;
309                    }
310                },
311            }
312        }
313    }
314
315    /// Register an inner service failure.
316    ///
317    /// The underlying service failed with the given `error` when we called `poll_ready` or `call` on it. We
318    /// need to communicate this to all the `Batch` handles. To do so, we wrap up the error in
319    /// an `Arc`, send that `Arc<E>` to all pending requests, and store it so that subsequent
320    /// requests will also fail with the same error.
321    fn failed(&mut self, error: crate::BoxError) {
322        tracing::debug!(?error, "batch worker error");
323
324        // Note that we need to handle the case where some error_handle is concurrently trying to send us
325        // a request. We need to make sure that *either* the send of the request fails *or* it
326        // receives an error on the `oneshot` it constructed. Specifically, we want to avoid the
327        // case where we send errors to all outstanding requests, and *then* the caller sends its
328        // request. We do this by *first* exposing the error, *then* closing the channel used to
329        // send more requests (so the client will see the error when the send fails), and *then*
330        // sending the error to all outstanding requests.
331        let error = ServiceError::new(error);
332
333        let mut inner = self.error_handle.inner.lock().unwrap();
334
335        // Ignore duplicate failures
336        if inner.is_some() {
337            return;
338        }
339
340        *inner = Some(error.clone());
341        drop(inner);
342
343        tracing::trace!(
344            ?error,
345            "worker failure: waking pending requests so they can be failed",
346        );
347        self.rx.close();
348        self.close.close();
349
350        // We don't schedule any batches on an errored service
351        self.pending_batch_timer = None;
352
353        // By closing the mpsc::Receiver, we know that the run() loop will
354        // drain all pending requests. We just need to make sure that any
355        // requests that we receive before we've exhausted the receiver receive
356        // the error:
357        self.failed = Some(error);
358    }
359}
360
361impl ErrorHandle {
362    pub(crate) fn get_error_on_closed(&self) -> crate::BoxError {
363        self.inner
364            .lock()
365            .expect("previous task panicked while holding the error handle mutex")
366            .as_ref()
367            .map(|svc_err| svc_err.clone().into())
368            .unwrap_or_else(|| Closed::new().into())
369    }
370}
371
372impl Clone for ErrorHandle {
373    fn clone(&self) -> ErrorHandle {
374        ErrorHandle {
375            inner: self.inner.clone(),
376        }
377    }
378}
379
380#[pin_project::pinned_drop]
381impl<T, Request: RequestWeight> PinnedDrop for Worker<T, Request>
382where
383    T: Service<BatchControl<Request>>,
384    T::Future: Send + 'static,
385    T::Error: Into<crate::BoxError>,
386{
387    fn drop(mut self: Pin<&mut Self>) {
388        tracing::trace!(
389            pending_items_weight = self.pending_items_weight,
390            batch_deadline = ?self.pending_batch_timer.as_ref().map(|sleep| sleep.deadline()),
391            running_batches = self.concurrent_batches.len(),
392            error = ?self.failed,
393            "dropping batch worker",
394        );
395
396        // Fail pending tasks
397        self.failed(Closed::new().into());
398
399        // Fail queued requests
400        while let Ok(msg) = self.rx.try_recv() {
401            let _ = msg
402                .tx
403                .send(Err(self.failed.as_ref().expect("just set failed").clone()));
404        }
405
406        // Clear any finished batches, ignoring any errors.
407        // Ignore any batches that are still executing, because we can't cancel them.
408        //
409        // now_or_never() can stop futures waking up, but that's ok here,
410        // because we're manually polling, then dropping the stream.
411        while let Some(Some(_)) = self
412            .as_mut()
413            .project()
414            .concurrent_batches
415            .next()
416            .now_or_never()
417        {}
418    }
419}