Skip to main content

batch_aint_one/
worker.rs

1use std::{collections::HashMap, fmt::Debug, time::Duration};
2
3use tokio::{
4    sync::{mpsc, oneshot},
5    task::JoinHandle,
6};
7use tracing::{Span, debug, info};
8
9use crate::{
10    BatchError,
11    batch::BatchItem,
12    batch_inner::Generation,
13    batch_queue::BatchQueue,
14    limits::Limits,
15    metrics::{BatchStats, MetricsRecorder},
16    policies::{BatchingPolicy, OnAdd, OnFinish, OnGenerationEvent},
17    processor::Processor,
18};
19
20pub(crate) struct Worker<P: Processor> {
21    batcher_name: String,
22
23    /// Used to receive new batch items.
24    item_rx: mpsc::Receiver<BatchItem<P>>,
25    /// The callback to process a batch of inputs.
26    processor: P,
27
28    /// Used to signal that a batch for key `K` should be processed.
29    msg_tx: mpsc::Sender<Message<P>>,
30    /// Receives signals to process a batch for key `K`.
31    msg_rx: mpsc::Receiver<Message<P>>,
32
33    /// Used to send messages to the worker related to shutdown.
34    shutdown_notifier_rx: mpsc::Receiver<ShutdownMessage>,
35
36    /// Used to signal to listeners that the worker has shut down.
37    shutdown_notifiers: Vec<oneshot::Sender<()>>,
38
39    shutting_down: bool,
40
41    limits: Limits,
42    /// Controls when to start processing a batch.
43    batching_policy: BatchingPolicy,
44
45    /// Unprocessed batches, grouped by key `K`.
46    batch_queues: HashMap<P::Key, BatchQueue<P>>,
47
48    metrics_recorder: Box<dyn MetricsRecorder>,
49}
50
51/// Events which drive the worker.
52///
53/// Spawned tasks (resource acquisition, timeouts) report their outcomes to the worker by
54/// sending a message, and the worker performs the resulting batch state transitions when
55/// handling them, so it observes all events in message order.
56pub(crate) enum Message<P: Processor> {
57    TimedOut(P::Key, Generation),
58    ResourcesAcquired {
59        key: P::Key,
60        generation: Generation,
61        resources: P::Resources,
62        span: Span,
63        acquisition_duration: Duration,
64    },
65    ResourceAcquisitionFailed {
66        key: P::Key,
67        generation: Generation,
68        err: BatchError<P::Error>,
69        acquisition_duration: Duration,
70    },
71    Finished {
72        key: P::Key,
73        metrics: BatchStats,
74    },
75}
76
77impl<P: Processor> Debug for Message<P> {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Message::TimedOut(key, generation) => f
81                .debug_tuple("TimedOut")
82                .field(key)
83                .field(generation)
84                .finish(),
85            Message::ResourcesAcquired {
86                key,
87                generation,
88                resources: _,
89                span: _,
90                acquisition_duration: _,
91            } => f
92                .debug_tuple("ResourcesAcquired")
93                .field(key)
94                .field(generation)
95                .field(&"<Resources>")
96                .finish(),
97            Message::ResourceAcquisitionFailed {
98                key,
99                generation,
100                err,
101                acquisition_duration: _,
102            } => f
103                .debug_tuple("ResourceAcquisitionFailed")
104                .field(key)
105                .field(generation)
106                .field(err)
107                .finish(),
108            Message::Finished { key, metrics: _ } => f.debug_tuple("Finished").field(key).finish(),
109        }
110    }
111}
112
113pub(crate) enum ShutdownMessage {
114    Register(ShutdownNotifier),
115    ShutDown,
116}
117
118pub(crate) struct ShutdownNotifier(oneshot::Sender<()>);
119
120/// A handle to the worker task.
121///
122/// Used for shutting down the worker and waiting for it to finish.
123#[derive(Debug, Clone)]
124pub struct WorkerHandle {
125    shutdown_tx: mpsc::Sender<ShutdownMessage>,
126}
127
128/// Aborts the worker task when dropped.
129#[derive(Debug)]
130pub(crate) struct WorkerDropGuard {
131    handle: JoinHandle<()>,
132}
133
134impl<P: Processor> Worker<P> {
135    pub fn spawn(
136        batcher_name: String,
137        processor: P,
138        limits: Limits,
139        batching_policy: BatchingPolicy,
140        metrics_recorder: Box<dyn MetricsRecorder>,
141    ) -> (WorkerHandle, WorkerDropGuard, mpsc::Sender<BatchItem<P>>) {
142        // These channel sizes are somewhat arbitrary - they just need to be big enough to avoid
143        // backpressure in normal operation.
144        let (item_tx, item_rx) = mpsc::channel(limits.max_items_in_system_per_key());
145        let (msg_tx, msg_rx) = mpsc::channel(limits.max_items_in_system_per_key());
146
147        let (shutdown_tx, shutdown_rx) = mpsc::channel(1);
148
149        let mut worker = Worker {
150            batcher_name,
151
152            item_rx,
153            processor,
154
155            msg_tx,
156            msg_rx,
157
158            shutdown_notifier_rx: shutdown_rx,
159            shutdown_notifiers: Vec::new(),
160
161            shutting_down: false,
162
163            limits,
164            batching_policy,
165
166            batch_queues: HashMap::new(),
167
168            metrics_recorder,
169        };
170
171        let handle = tokio::spawn(async move {
172            worker.run().await;
173        });
174
175        (
176            WorkerHandle { shutdown_tx },
177            WorkerDropGuard { handle },
178            item_tx,
179        )
180    }
181
182    /// Add an item to the batch.
183    fn add(&mut self, mut item: BatchItem<P>) {
184        self.metrics_recorder
185            .item_received(item.submitted_at.elapsed());
186        item.received_at = Some(tokio::time::Instant::now());
187
188        let key = item.key.clone();
189
190        let batch_queue = self.batch_queues.entry(key.clone()).or_insert_with(|| {
191            BatchQueue::new(self.batcher_name.clone(), key.clone(), self.limits)
192        });
193
194        match self.batching_policy.on_add(batch_queue) {
195            OnAdd::AddAndProcess => {
196                batch_queue.push(item);
197
198                self.process_next_batch(&key);
199            }
200            OnAdd::AddAndAcquireResources => {
201                batch_queue.push(item);
202
203                batch_queue.pre_acquire_resources(self.processor.clone(), self.msg_tx.clone());
204            }
205            OnAdd::AddAndProcessAfter(duration) => {
206                batch_queue.push(item);
207
208                batch_queue.process_after(duration, self.msg_tx.clone());
209            }
210            OnAdd::Add => {
211                batch_queue.push(item);
212            }
213            OnAdd::Reject(reason) => {
214                self.metrics_recorder.item_rejected();
215
216                if item
217                    .tx
218                    .send((Err(BatchError::Rejected(reason)), None))
219                    .is_err()
220                {
221                    // Whatever was waiting for the output must have shut down. Presumably it
222                    // doesn't care anymore, but we log here anyway. There's not much else we can do.
223                    debug!(
224                        "Unable to send output over oneshot channel. Receiver deallocated. Batcher: {}",
225                        self.batcher_name
226                    );
227                }
228            }
229        }
230
231        self.report_gauges();
232    }
233
234    /// Get the batch queue for the given key, which should always exist when handling an event
235    /// for that key.
236    fn queue_mut<'q>(
237        batch_queues: &'q mut HashMap<P::Key, BatchQueue<P>>,
238        key: &P::Key,
239    ) -> &'q mut BatchQueue<P> {
240        batch_queues.get_mut(key).expect("batch queue should exist")
241    }
242
243    fn process_generation(&mut self, key: P::Key, generation: Generation) {
244        let batch_queue = Self::queue_mut(&mut self.batch_queues, &key);
245
246        batch_queue.process_generation(generation, self.processor.clone(), self.msg_tx.clone());
247    }
248
249    fn process_next_ready_batch(&mut self, key: &P::Key) {
250        let batch_queue = Self::queue_mut(&mut self.batch_queues, key);
251
252        batch_queue.process_next_ready_batch(self.processor.clone(), self.msg_tx.clone());
253    }
254
255    fn process_next_batch(&mut self, key: &P::Key) {
256        let batch_queue = Self::queue_mut(&mut self.batch_queues, key);
257
258        batch_queue.process_next_batch(self.processor.clone(), self.msg_tx.clone());
259    }
260
261    fn on_timeout(&mut self, key: P::Key, generation: Generation) {
262        // Unlike the other message handlers, the queue may have been removed: timers are not
263        // tracked by the in-flight counters, so a TimedOut message can outlive its queue.
264        let Some(batch_queue) = self.batch_queues.get_mut(&key) else {
265            debug!("Timeout for a batch queue which no longer exists. Ignoring.");
266            return;
267        };
268
269        match self.batching_policy.on_timeout(generation, batch_queue) {
270            OnGenerationEvent::Process => {
271                self.process_generation(key, generation);
272            }
273            OnGenerationEvent::DoNothing => {}
274        }
275    }
276
277    fn on_resource_acquired(
278        &mut self,
279        key: P::Key,
280        generation: Generation,
281        resources: P::Resources,
282        span: Span,
283        acquisition_duration: Duration,
284    ) {
285        self.metrics_recorder
286            .resource_acquisition_completed(acquisition_duration, true);
287
288        let batch_queue = Self::queue_mut(&mut self.batch_queues, &key);
289
290        batch_queue.resources_acquired(generation, resources, span);
291
292        match self
293            .batching_policy
294            .on_resources_acquired(generation, batch_queue)
295        {
296            OnGenerationEvent::Process => {
297                self.process_generation(key, generation);
298            }
299            OnGenerationEvent::DoNothing => {}
300        }
301    }
302
303    fn on_resource_acquisition_failed(
304        &mut self,
305        key: P::Key,
306        generation: Generation,
307        err: BatchError<P::Error>,
308        acquisition_duration: Duration,
309    ) {
310        self.metrics_recorder
311            .resource_acquisition_completed(acquisition_duration, false);
312
313        let batch_queue = Self::queue_mut(&mut self.batch_queues, &key);
314
315        batch_queue.fail_generation(generation, err);
316
317        self.process_next_and_clean_up(&key);
318        self.report_gauges();
319    }
320
321    fn on_batch_finished(&mut self, key: &P::Key, metrics: BatchStats) {
322        self.metrics_recorder.batch_completed(&metrics);
323
324        let batch_queue = Self::queue_mut(&mut self.batch_queues, key);
325
326        batch_queue.mark_processed();
327
328        self.process_next_and_clean_up(key);
329        self.report_gauges();
330    }
331
332    fn report_gauges(&self) {
333        self.metrics_recorder
334            .active_keys_changed(self.batch_queues.len());
335
336        let (total_processing, max_processing, total_queued, max_queued) = self
337            .batch_queues
338            .values()
339            .fold((0, 0, 0, 0), |(tp, mp, tq, mq), bq| {
340                let p = bq.processing();
341                let q = bq.queued();
342                (tp + p, mp.max(p), tq + q, mq.max(q))
343            });
344
345        self.metrics_recorder
346            .processing_concurrency_changed(total_processing, max_processing);
347        self.metrics_recorder
348            .queue_depth_changed(total_queued, max_queued);
349    }
350
351    /// After a batch has left the queue (either processed or having failed to acquire resources),
352    /// apply the batching policy's finish action and drop the queue if the key is now idle.
353    fn process_next_and_clean_up(&mut self, key: &P::Key) {
354        let batch_queue = Self::queue_mut(&mut self.batch_queues, key);
355
356        match self.batching_policy.on_finish(batch_queue) {
357            OnFinish::ProcessNextReady => {
358                self.process_next_ready_batch(key);
359            }
360            OnFinish::ProcessNext => {
361                self.process_next_batch(key);
362            }
363            OnFinish::DoNothing => {}
364        }
365
366        // Remove the queue for idle keys, otherwise the map grows unboundedly as new keys are
367        // seen. A key can only become idle once a batch leaves the queue, so these handlers are
368        // the only place we need to do this.
369        if Self::queue_mut(&mut self.batch_queues, key).is_idle() {
370            self.batch_queues.remove(key);
371        }
372    }
373
374    fn ready_to_shut_down(&self) -> bool {
375        self.shutting_down
376            && self.batch_queues.values().all(|q| q.is_empty())
377            && !self.batch_queues.values().any(|q| q.is_processing())
378    }
379
380    /// Start running the worker event loop.
381    async fn run(&mut self) {
382        loop {
383            tokio::select! {
384                Some(msg) = self.shutdown_notifier_rx.recv() => {
385                    match msg {
386                        ShutdownMessage::Register(notifier) => {
387                           self.shutdown_notifiers.push(notifier.0);
388                        }
389                        ShutdownMessage::ShutDown => {
390                            self.shutting_down = true;
391                        }
392                    }
393                }
394
395                Some(item) = self.item_rx.recv() => {
396                    self.add(item);
397                }
398
399                Some(msg) = self.msg_rx.recv() => {
400                    match msg {
401                        Message::ResourcesAcquired { key, generation, resources, span, acquisition_duration } => {
402                            self.on_resource_acquired(key, generation, resources, span, acquisition_duration);
403                        }
404                        Message::ResourceAcquisitionFailed { key, generation, err, acquisition_duration } => {
405                            self.on_resource_acquisition_failed(key, generation, err, acquisition_duration);
406                        }
407                        Message::TimedOut(key, generation) => {
408                            self.on_timeout(key, generation);
409                        }
410                        Message::Finished { key, metrics } => {
411                            self.on_batch_finished(&key, metrics);
412                        }
413                    }
414                }
415            }
416
417            if self.ready_to_shut_down() {
418                info!("Batch worker '{}' is shutting down", &self.batcher_name);
419                return;
420            }
421        }
422    }
423}
424
425impl WorkerHandle {
426    /// Signal the worker to shut down after processing any in-flight batches.
427    ///
428    /// New items are still accepted while shutting down, and the worker only shuts down once all
429    /// keys are idle. This means shutdown may never complete if:
430    ///
431    /// - new items keep being added, or
432    /// - a batch never meets its policy's processing condition, e.g. when using the
433    ///   [`Size`](crate::BatchingPolicy::Size) policy, a final partial batch may wait
434    ///   indefinitely for more items.
435    ///
436    /// Stopping the flow of new items is expected to be handled by the caller, e.g. by shutting
437    /// down the message handlers which add items before shutting down the batcher.
438    pub async fn shut_down(&self) {
439        info!("Sending shut down signal to batch worker");
440        // We ignore errors here - if the receiver has gone away, the worker is already shut down.
441        let _ = self.shutdown_tx.send(ShutdownMessage::ShutDown).await;
442    }
443
444    /// Wait for the worker to finish.
445    pub async fn wait_for_shutdown(&self) {
446        // We ignore errors here - if the receiver has gone away, the worker is already shut down.
447        let (notifier_tx, notifier_rx) = oneshot::channel();
448        let _ = self
449            .shutdown_tx
450            .send(ShutdownMessage::Register(ShutdownNotifier(notifier_tx)))
451            .await;
452        // Wait for the notifier to be dropped.
453        let _ = notifier_rx.await;
454    }
455}
456
457impl Drop for WorkerDropGuard {
458    fn drop(&mut self) {
459        info!("Aborting batch worker");
460        self.handle.abort();
461    }
462}
463
464#[cfg(test)]
465mod test {
466    use tokio::sync::oneshot;
467    use tracing::Span;
468
469    use super::*;
470
471    #[derive(Debug, Clone)]
472    struct SimpleBatchProcessor;
473
474    impl Processor for SimpleBatchProcessor {
475        type Key = String;
476        type Input = String;
477        type Output = String;
478        type Error = String;
479        type Resources = ();
480
481        async fn acquire_resources(&self, _key: String) -> Result<(), String> {
482            Ok(())
483        }
484
485        async fn process(
486            &self,
487            _key: String,
488            inputs: impl Iterator<Item = String> + Send,
489            _resources: (),
490        ) -> Result<Vec<String>, String> {
491            Ok(inputs.map(|s| s + " processed").collect())
492        }
493    }
494
495    /// Construct a worker directly, without spawning the run loop, so tests can drive it
496    /// manually and inspect its state.
497    fn new_worker() -> Worker<SimpleBatchProcessor> {
498        let (_item_tx, item_rx) = mpsc::channel(1);
499        let (msg_tx, msg_rx) = mpsc::channel(1);
500        let (_shutdown_tx, shutdown_rx) = mpsc::channel(1);
501
502        Worker {
503            batcher_name: "test".to_string(),
504            item_rx,
505            processor: SimpleBatchProcessor,
506            msg_tx,
507            msg_rx,
508            shutdown_notifier_rx: shutdown_rx,
509            shutdown_notifiers: Vec::new(),
510            shutting_down: false,
511            limits: Limits::builder().max_batch_size(1).build(),
512            batching_policy: BatchingPolicy::Size,
513            batch_queues: HashMap::new(),
514            metrics_recorder: Box::new(crate::metrics::NoopMetricsRecorder),
515        }
516    }
517
518    #[tokio::test]
519    async fn removes_batch_queue_when_key_becomes_idle() {
520        let mut worker = new_worker();
521
522        let (tx, rx) = oneshot::channel();
523        worker.add(BatchItem {
524            key: "K1".to_string(),
525            input: "I1".to_string(),
526            submitted_at: tokio::time::Instant::now(),
527            received_at: None,
528            tx,
529            requesting_span: Span::none(),
530        });
531
532        // max_batch_size is 1, so the batch processes immediately.
533        let output = rx.await.unwrap().0.unwrap();
534        assert_eq!(output, "I1 processed");
535
536        // Handle the Finished message, as the run loop would.
537        let msg = worker.msg_rx.recv().await.unwrap();
538        let Message::Finished { key, metrics } = msg else {
539            panic!("expected Finished message, got {:?}", msg);
540        };
541        worker.on_batch_finished(&key, metrics);
542
543        assert!(
544            worker.batch_queues.is_empty(),
545            "the batch queue for an idle key should be removed"
546        );
547    }
548
549    #[tokio::test]
550    async fn ignores_timeout_for_removed_batch_queue() {
551        // A timer can fire and enqueue a TimedOut message, after which the batch is processed
552        // anyway (e.g. it filled up) and the queue is removed once the key is idle. The stale
553        // TimedOut message must be ignored, not panic the worker.
554        let mut worker = new_worker();
555
556        worker.on_timeout("K1".to_string(), Generation::default());
557    }
558
559    #[tokio::test]
560    async fn simple_test_over_channel() {
561        let (_worker_handle, _worker_guard, item_tx) = Worker::<SimpleBatchProcessor>::spawn(
562            "test".to_string(),
563            SimpleBatchProcessor,
564            Limits::builder().max_batch_size(2).build(),
565            BatchingPolicy::Size,
566            Box::new(crate::metrics::NoopMetricsRecorder),
567        );
568
569        let rx1 = {
570            let (tx, rx) = oneshot::channel();
571            item_tx
572                .send(BatchItem {
573                    key: "K1".to_string(),
574                    input: "I1".to_string(),
575                    submitted_at: tokio::time::Instant::now(),
576            received_at: None,
577                    tx,
578                    requesting_span: Span::none(),
579                })
580                .await
581                .unwrap();
582
583            rx
584        };
585
586        let rx2 = {
587            let (tx, rx) = oneshot::channel();
588            item_tx
589                .send(BatchItem {
590                    key: "K1".to_string(),
591                    input: "I2".to_string(),
592                    submitted_at: tokio::time::Instant::now(),
593            received_at: None,
594                    tx,
595                    requesting_span: Span::none(),
596                })
597                .await
598                .unwrap();
599
600            rx
601        };
602
603        let o1 = rx1.await.unwrap().0.unwrap();
604        let o2 = rx2.await.unwrap().0.unwrap();
605
606        assert_eq!(o1, "I1 processed".to_string());
607        assert_eq!(o2, "I2 processed".to_string());
608    }
609}