Skip to main content

tower_batch_control/
service.rs

1//! Wrapper service for batching items to an underlying service.
2
3use std::{
4    cmp::max,
5    fmt,
6    future::Future,
7    pin::Pin,
8    sync::{Arc, Mutex},
9    task::{Context, Poll},
10};
11
12use futures_core::ready;
13use tokio::{
14    pin,
15    sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore},
16    task::JoinHandle,
17};
18use tokio_util::sync::PollSemaphore;
19use tower::Service;
20use tracing::{info_span, Instrument};
21
22use crate::RequestWeight;
23
24use super::{
25    future::ResponseFuture,
26    message::Message,
27    worker::{ErrorHandle, Worker},
28    BatchControl,
29};
30
31/// The maximum number of batches in the queue.
32///
33/// This avoids having very large queues on machines with hundreds or thousands of cores.
34pub const QUEUE_BATCH_LIMIT: usize = 64;
35
36/// Allows batch processing of requests.
37///
38/// See the crate documentation for more details.
39pub struct Batch<T, Request: RequestWeight>
40where
41    T: Service<BatchControl<Request>>,
42{
43    // Batch management
44    //
45    /// A custom-bounded channel for sending requests to the batch worker.
46    ///
47    /// Note: this actually _is_ bounded, but rather than using Tokio's unbounded
48    /// channel, we use tokio's semaphore separately to implement the bound.
49    tx: mpsc::UnboundedSender<Message<Request, T::Future>>,
50
51    /// A semaphore used to bound the channel.
52    ///
53    /// When the buffer's channel is full, we want to exert backpressure in
54    /// `poll_ready`, so that callers such as load balancers could choose to call
55    /// another service rather than waiting for buffer capacity.
56    ///
57    /// Unfortunately, this can't be done easily using Tokio's bounded MPSC
58    /// channel, because it doesn't wake pending tasks on close. Therefore, we implement our
59    /// own bounded MPSC on top of the unbounded channel, using a semaphore to
60    /// limit how many items are in the channel.
61    semaphore: PollSemaphore,
62
63    /// A semaphore permit that allows this service to send one message on `tx`.
64    permit: Option<OwnedSemaphorePermit>,
65
66    // Errors
67    //
68    /// An error handle shared between all service clones for the same worker.
69    error_handle: ErrorHandle,
70
71    /// A worker task handle shared between all service clones for the same worker.
72    ///
73    /// Only used when the worker is spawned on the tokio runtime.
74    worker_handle: Arc<Mutex<Option<JoinHandle<()>>>>,
75}
76
77impl<T, Request: RequestWeight> fmt::Debug for Batch<T, Request>
78where
79    T: Service<BatchControl<Request>>,
80{
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        let name = std::any::type_name::<Self>();
83        f.debug_struct(name)
84            .field("tx", &self.tx)
85            .field("semaphore", &self.semaphore)
86            .field("permit", &self.permit)
87            .field("error_handle", &self.error_handle)
88            .field("worker_handle", &self.worker_handle)
89            .finish()
90    }
91}
92
93impl<T, Request: RequestWeight> Batch<T, Request>
94where
95    T: Service<BatchControl<Request>>,
96    T::Future: Send + 'static,
97    T::Error: Into<crate::BoxError>,
98{
99    /// Creates a new `Batch` wrapping `service`.
100    ///
101    /// The wrapper is responsible for telling the inner service when to flush a
102    /// batch of requests. These parameters control this policy:
103    ///
104    /// * `max_items_weight_in_batch` gives the maximum item weight per batch.
105    /// * `max_batches` is an upper bound on the number of batches in the queue,
106    ///   and the number of concurrently executing batches.
107    ///   If this is `None`, we use the current number of [`rayon`] threads.
108    ///   The number of batches in the queue is also limited by [`QUEUE_BATCH_LIMIT`].
109    /// * `max_latency` gives the maximum latency for a batch item to start verifying.
110    /// * The `max_idle` duration bounds idle time after the most recent batch item.
111    ///   The batch flushes at the earlier of this idle deadline and `max_latency`.
112    ///
113    /// The default Tokio executor is used to run the given service, which means
114    /// that this method must be called while on the Tokio runtime.
115    pub fn new(
116        service: T,
117        max_items_weight_in_batch: usize,
118        max_batches: impl Into<Option<usize>>,
119        max_latency: std::time::Duration,
120        max_idle: std::time::Duration,
121    ) -> Self
122    where
123        T: Send + 'static,
124        T::Future: Send,
125        T::Response: Send,
126        T::Error: Send + Sync,
127        Request: Send + 'static,
128    {
129        let (mut batch, worker) = Self::pair(
130            service,
131            max_items_weight_in_batch,
132            max_batches,
133            max_latency,
134            max_idle,
135        );
136
137        let span = info_span!("batch worker", kind = std::any::type_name::<T>());
138
139        #[cfg(tokio_unstable)]
140        let worker_handle = {
141            let batch_kind = std::any::type_name::<T>();
142
143            // TODO: identify the unique part of the type name generically,
144            //       or make it an argument to this method
145            let batch_kind = batch_kind.trim_start_matches("zebra_consensus::primitives::");
146            let batch_kind = batch_kind.trim_end_matches("::Verifier");
147
148            tokio::task::Builder::new()
149                .name(&format!("{} batch", batch_kind))
150                .spawn(worker.run().instrument(span))
151                .expect("panic on error to match tokio::spawn")
152        };
153        #[cfg(not(tokio_unstable))]
154        let worker_handle = tokio::spawn(worker.run().instrument(span));
155
156        batch.register_worker(worker_handle);
157
158        batch
159    }
160
161    /// Creates a new `Batch` wrapping `service`, but returns the background worker.
162    ///
163    /// This is useful if you do not want to spawn directly onto the `tokio`
164    /// runtime but instead want to use your own executor. This will return the
165    /// `Batch` and the background `Worker` that you can then spawn.
166    ///
167    /// See [`Batch::new()`] for the batching policy parameters.
168    pub fn pair(
169        service: T,
170        max_items_weight_in_batch: usize,
171        max_batches: impl Into<Option<usize>>,
172        max_latency: std::time::Duration,
173        max_idle: std::time::Duration,
174    ) -> (Self, Worker<T, Request>)
175    where
176        T: Send + 'static,
177        T::Error: Send + Sync,
178        Request: Send + 'static,
179    {
180        let (tx, rx) = mpsc::unbounded_channel();
181
182        // Clamp config to sensible values.
183        let max_items_weight_in_batch = max(max_items_weight_in_batch, 1);
184        let max_batches = max_batches
185            .into()
186            .unwrap_or_else(rayon::current_num_threads);
187        let max_batches_in_queue = max_batches.clamp(1, QUEUE_BATCH_LIMIT);
188
189        // The semaphore bound limits the maximum number of concurrent requests
190        // (specifically, requests which got a `Ready` from `poll_ready`, but haven't
191        // used their semaphore reservation in a `call` yet).
192        //
193        // We choose a bound that allows callers to check readiness for one batch per rayon CPU thread.
194        // This helps keep all CPUs filled with work: there is one batch executing, and another ready to go.
195        // Often there is only one verifier running, when that happens we want it to take all the cores.
196        //
197        // Requests with a request weight greater than 1 won't typically exhaust the number of available
198        // permits, but will still be bounded to the maximum possible number of concurrent requests.
199        let semaphore = Semaphore::new(max_items_weight_in_batch * max_batches_in_queue);
200        let semaphore = PollSemaphore::new(Arc::new(semaphore));
201
202        let (error_handle, worker) = Worker::new(
203            service,
204            rx,
205            max_items_weight_in_batch,
206            max_batches,
207            max_latency,
208            max_idle,
209            semaphore.clone(),
210        );
211
212        let batch = Batch {
213            tx,
214            semaphore,
215            permit: None,
216            error_handle,
217            worker_handle: Arc::new(Mutex::new(None)),
218        };
219
220        (batch, worker)
221    }
222
223    /// Ask the `Batch` to monitor the spawned worker task's [`JoinHandle`].
224    ///
225    /// Only used when the task is spawned on the tokio runtime.
226    pub fn register_worker(&mut self, worker_handle: JoinHandle<()>) {
227        *self
228            .worker_handle
229            .lock()
230            .expect("previous task panicked while holding the worker handle mutex") =
231            Some(worker_handle);
232    }
233
234    /// Returns the error from the batch worker's `error_handle`.
235    fn get_worker_error(&self) -> crate::BoxError {
236        self.error_handle.get_error_on_closed()
237    }
238}
239
240impl<T, Request: RequestWeight> Service<Request> for Batch<T, Request>
241where
242    T: Service<BatchControl<Request>>,
243    T::Future: Send + 'static,
244    T::Error: Into<crate::BoxError>,
245{
246    type Response = T::Response;
247    type Error = crate::BoxError;
248    type Future = ResponseFuture<T::Future>;
249
250    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
251        // Check to see if the worker has returned or panicked.
252        //
253        // Correctness: Registers this task for wakeup when the worker finishes.
254        if let Some(worker_handle) = self
255            .worker_handle
256            .lock()
257            .expect("previous task panicked while holding the worker handle mutex")
258            .as_mut()
259        {
260            // # Correctness
261            //
262            // The inner service used with `Batch` MUST NOT return recoverable errors from its:
263            // - `poll_ready` method, or
264            // - `call` method when called with a `BatchControl::Flush` request.
265            //
266            // If the inner service returns an error in those cases, this `poll_ready` method will
267            // return an error the first time its called, and will panic the second time its called
268            // as it attempts to call `poll` on a `JoinHandle` that has already completed.
269            match Pin::new(worker_handle).poll(cx) {
270                Poll::Ready(Ok(())) => {
271                    let worker_error = self.get_worker_error();
272                    tracing::warn!(?worker_error, "batch worker finished unexpectedly");
273                    return Poll::Ready(Err(worker_error));
274                }
275                Poll::Ready(Err(task_cancelled)) if task_cancelled.is_cancelled() => {
276                    tracing::warn!(
277                        "batch task cancelled: {task_cancelled}\n\
278                         Is Zebra shutting down?"
279                    );
280
281                    return Poll::Ready(Err(task_cancelled.into()));
282                }
283                Poll::Ready(Err(task_panic)) => {
284                    std::panic::resume_unwind(task_panic.into_panic());
285                }
286                Poll::Pending => {}
287            }
288        }
289
290        // Check if the worker has set an error and closed its channels.
291        //
292        // Correctness: Registers this task for wakeup when the channel is closed.
293        let tx = self.tx.clone();
294        let closed = tx.closed();
295        pin!(closed);
296        if closed.poll(cx).is_ready() {
297            return Poll::Ready(Err(self.get_worker_error()));
298        }
299
300        // Poll to acquire a semaphore permit.
301        //
302        // CORRECTNESS
303        //
304        // If we acquire a permit, then there's enough buffer capacity to send a new request.
305        // Otherwise, we need to wait for capacity. When that happens, `poll_acquire()` registers
306        // this task for wakeup when the next permit is available, or when the semaphore is closed.
307        //
308        // When `poll_ready()` is called multiple times, and channel capacity is 1,
309        // avoid deadlocks by dropping any previous permit before acquiring another one.
310        // This also stops tasks holding a permit after an error.
311        //
312        // Calling `poll_ready()` multiple times can make tasks lose their previous permit
313        // to another concurrent task.
314        self.permit = None;
315
316        let permit = ready!(self.semaphore.poll_acquire(cx));
317        if let Some(permit) = permit {
318            // Calling poll_ready() more than once will drop any previous permit,
319            // releasing its capacity back to the semaphore.
320            self.permit = Some(permit);
321        } else {
322            // The semaphore has been closed.
323            return Poll::Ready(Err(self.get_worker_error()));
324        }
325
326        Poll::Ready(Ok(()))
327    }
328
329    fn call(&mut self, request: Request) -> Self::Future {
330        tracing::trace!("sending request to batch worker");
331        let _permit = self
332            .permit
333            .take()
334            .expect("poll_ready must be called before a batch request");
335
336        // get the current Span so that we can explicitly propagate it to the worker
337        // if we didn't do this, events on the worker related to this span wouldn't be counted
338        // towards that span since the worker would have no way of entering it.
339        let span = tracing::Span::current();
340
341        // If we've made it here, then a semaphore permit has already been
342        // acquired, so we can freely allocate a oneshot.
343        let (tx, rx) = oneshot::channel();
344
345        match self.tx.send(Message {
346            request,
347            tx,
348            span,
349            _permit,
350        }) {
351            Err(_) => ResponseFuture::failed(self.get_worker_error()),
352            Ok(_) => ResponseFuture::new(rx),
353        }
354    }
355}
356
357impl<T, Request: RequestWeight> Clone for Batch<T, Request>
358where
359    T: Service<BatchControl<Request>>,
360{
361    fn clone(&self) -> Self {
362        Self {
363            tx: self.tx.clone(),
364            semaphore: self.semaphore.clone(),
365            permit: None,
366            error_handle: self.error_handle.clone(),
367            worker_handle: self.worker_handle.clone(),
368        }
369    }
370}