shove 0.11.2

Async tasks via pubsub on steroids. Comes with built-in support for complex queue configurations, audit logs, autoscaling consumer groups and more.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! Consumer supervisor harness and its outcome type.

use std::time::Duration;

use tokio::task::{JoinError, JoinSet};
use tokio_util::sync::CancellationToken;

use crate::backend::{Backend, ConsumerImpl};
use crate::consumer::ConsumerOptions;
use crate::error::{Result, ShoveError};
use crate::handler::MessageHandler;
use crate::topic::{SequencedTopic, Topic};

/// Result of draining a supervisor or consumer group.
#[must_use]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SupervisorOutcome {
    pub errors: usize,
    pub panics: usize,
    pub timed_out: bool,
}

impl SupervisorOutcome {
    /// Canonical process exit code: `0` clean, `1` any error, `2` any panic,
    /// `3` drain timeout. Highest non-zero condition wins.
    pub fn exit_code(&self) -> i32 {
        if self.timed_out {
            3
        } else if self.panics > 0 {
            2
        } else if self.errors > 0 {
            1
        } else {
            0
        }
    }

    /// True when no errors, panics, or drain timeouts were recorded.
    pub fn is_clean(&self) -> bool {
        self.exit_code() == 0
    }
}

/// Internal tally of errors and panics captured while draining a consumer
/// group. Each backend's `ConsumerGroup::shutdown_with_tally` and
/// `ConsumerGroupRegistry::shutdown_all_with_tally` fill this out so
/// `RegistryImpl::run_until_timeout` can return a truthful
/// [`SupervisorOutcome`].
///
/// Only coordinated-group backends (RabbitMQ / Kafka / NATS / InMemory) use
/// this; a supervisor-only build such as `aws-sns-sqs` doesn't.
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct ShutdownTally {
    pub errors: usize,
    pub panics: usize,
}

#[allow(dead_code)]
impl ShutdownTally {
    pub(crate) fn add(&mut self, other: ShutdownTally) {
        self.errors += other.errors;
        self.panics += other.panics;
    }
}

// ---------------------------------------------------------------------------
// Shared drain helper
// ---------------------------------------------------------------------------

/// RAII guard that calls `AbortHandle::abort` on drop. Used to ensure that
/// when a wrapper task around a FIFO shard `JoinHandle` is itself aborted
/// (e.g. by `JoinSet::abort_all`), the inner shard task is aborted too —
/// not merely detached, which is what dropping a bare `JoinHandle` does.
pub(crate) struct AbortOnDrop(pub(crate) tokio::task::AbortHandle);

impl Drop for AbortOnDrop {
    fn drop(&mut self) {
        self.0.abort();
    }
}

/// Map a `JoinSet::join_next` result onto running `errors` / `panics`
/// counters. Shared by `ConsumerSupervisor::run_until_timeout` and each
/// backend's `run_fifo_until_timeout`.
///
/// `Ok(Ok(()))` → success, ignored
/// `Ok(Err(ShoveError))` → `errors += 1`
/// Cancellation (`JoinError::is_cancelled`) → ignored
/// Other `JoinError` → `panics += 1`
pub(crate) fn tally_join_result(
    res: std::result::Result<Result<()>, JoinError>,
    errors: &mut usize,
    panics: &mut usize,
) {
    match res {
        Ok(Ok(())) => {}
        Ok(Err(e)) => {
            tracing::error!(error = %e, "consumer task failed");
            *errors += 1;
        }
        Err(e) if e.is_cancelled() => {}
        Err(e) => {
            tracing::error!(error = %e, "consumer task panicked");
            *panics += 1;
        }
    }
}

/// Drive an already-spawned set of FIFO shard task handles to completion or
/// timeout, mirroring [`ConsumerSupervisor::run_until_timeout`] for
/// sequenced topics.
///
/// Each handle is wrapped in a [`JoinSet`] entry that maps
/// abort-cancellation to `Ok(())` and re-panics on real panics, so the
/// outer drain can use [`tally_join_result`] uniformly.
///
/// - Races `signal` against shards finishing on their own. `biased` puts
///   `signal` first so a shutdown trigger that's already ready wins ties
///   with a shard that has just completed — `shards_done` then runs as the
///   post-cancel drain instead.
/// - On signal, cancels `shutdown` and waits up to `drain_timeout` for
///   shards to finish.
/// - On timeout, calls `JoinSet::abort_all` and sets
///   [`SupervisorOutcome::timed_out`] = `true`. The wrapper holds an
///   [`AbortOnDrop`] guard around the inner shard `JoinHandle`, so aborting
///   the wrapper task aborts the inner shard task too — without it,
///   `JoinHandle::drop` would just *detach* the inner task, leaking it.
/// - `drain_timeout = Duration::ZERO` means "abort immediately after
///   `signal` fires" (no grace period); this is honored verbatim.
#[allow(dead_code)] // every caller is feature-gated; unused under --no-default-features
pub(crate) async fn drive_fifo_until_timeout<S>(
    handles: Vec<tokio::task::JoinHandle<Result<()>>>,
    shutdown: CancellationToken,
    signal: S,
    drain_timeout: Duration,
) -> SupervisorOutcome
where
    S: Future<Output = ()> + Send + 'static,
{
    let mut joinset: JoinSet<Result<()>> = JoinSet::new();
    for handle in handles {
        let abort_guard = AbortOnDrop(handle.abort_handle());
        joinset.spawn(async move {
            // Bind the guard to the wrapper task's stack so it drops with
            // the wrapper future — including when the wrapper is itself
            // aborted by `JoinSet::abort_all`. Calling `abort()` on an
            // already-finished inner task is a no-op.
            let _abort_guard = abort_guard;
            match handle.await {
                Ok(r) => r,
                Err(e) if e.is_cancelled() => Ok(()),
                Err(e) => std::panic::resume_unwind(e.into_panic()),
            }
        });
    }

    let mut errors = 0usize;
    let mut panics = 0usize;

    let shards_done = {
        let errors = &mut errors;
        let panics = &mut panics;
        let joinset = &mut joinset;
        async move {
            while let Some(res) = joinset.join_next().await {
                tally_join_result(res, errors, panics);
            }
        }
    };

    let signal_won = tokio::select! {
        biased;
        _ = signal => true,
        _ = shards_done => false,
    };

    if !signal_won {
        return SupervisorOutcome {
            errors,
            panics,
            timed_out: false,
        };
    }

    shutdown.cancel();
    let drain = async {
        while let Some(res) = joinset.join_next().await {
            tally_join_result(res, &mut errors, &mut panics);
        }
    };
    match tokio::time::timeout(drain_timeout, drain).await {
        Ok(()) => SupervisorOutcome {
            errors,
            panics,
            timed_out: false,
        },
        Err(_) => {
            tracing::warn!(
                timeout_ms = drain_timeout.as_millis() as u64,
                "run_fifo_until_timeout: drain timed out; aborting surviving shards"
            );
            joinset.abort_all();
            while let Some(res) = joinset.join_next().await {
                tally_join_result(res, &mut errors, &mut panics);
            }
            SupervisorOutcome {
                errors,
                panics,
                timed_out: true,
            }
        }
    }
}

// ---------------------------------------------------------------------------
// ConsumerSupervisor<B, Ctx>
// ---------------------------------------------------------------------------

pub struct ConsumerSupervisor<B: Backend, Ctx: Clone + Send + Sync + 'static = ()> {
    consumer: B::ConsumerImpl,
    ctx: Ctx,
    shutdown: CancellationToken,
    tasks: JoinSet<Result<()>>,
    /// Queue names of every topic registered through `register` /
    /// `register_fifo`, used to reject duplicate registrations on the same
    /// supervisor (which would silently double-spawn consumer or shard
    /// tasks on the same broker queue).
    registered: std::collections::HashSet<&'static str>,
}

impl<B: Backend> ConsumerSupervisor<B, ()> {
    pub(crate) fn new(client: &B::Client) -> Self {
        Self {
            consumer: B::make_consumer(client),
            ctx: (),
            shutdown: CancellationToken::new(),
            tasks: JoinSet::new(),
            registered: std::collections::HashSet::new(),
        }
    }

    pub fn with_context<Ctx: Clone + Send + Sync + 'static>(
        self,
        ctx: Ctx,
    ) -> ConsumerSupervisor<B, Ctx> {
        ConsumerSupervisor {
            consumer: self.consumer,
            ctx,
            shutdown: self.shutdown,
            tasks: self.tasks,
            registered: self.registered,
        }
    }
}

impl<B: Backend, Ctx: Clone + Send + Sync + 'static> ConsumerSupervisor<B, Ctx> {
    pub fn cancellation_token(&self) -> CancellationToken {
        self.shutdown.clone()
    }

    pub fn register<T, H>(&mut self, handler: H, options: ConsumerOptions<B>) -> Result<()>
    where
        T: Topic,
        H: MessageHandler<T, Context = Ctx>,
    {
        let queue = T::topology().queue();
        if T::topology().sequencing().is_some() {
            return Err(ShoveError::Topology(format!(
                "topic '{queue}' has a sequencing config; `ConsumerSupervisor::register` \
                 would silently drop FIFO ordering. Use `register_fifo` instead."
            )));
        }
        if !self.registered.insert(queue) {
            return Err(ShoveError::Topology(format!(
                "topic '{queue}' is already registered on this supervisor"
            )));
        }
        let consumer = self.consumer.clone();
        let ctx = self.ctx.clone();
        let inner = options.with_shutdown(self.shutdown.clone()).into_inner();
        self.tasks
            .spawn(async move { consumer.run::<T, H>(handler, ctx, inner).await });
        Ok(())
    }

    pub async fn register_fifo<T, H>(
        &mut self,
        handler: H,
        options: ConsumerOptions<B>,
    ) -> Result<()>
    where
        T: SequencedTopic,
        H: MessageHandler<T, Context = Ctx>,
    {
        let queue = T::topology().queue();
        if T::topology().sequencing().is_none() {
            return Err(ShoveError::Topology(format!(
                "topic '{queue}' implements `SequencedTopic` but its topology has no \
                 sequencing config; `ConsumerSupervisor::register_fifo` would attach to \
                 FIFO shard queues that were never declared. Use `register` for \
                 unsequenced topics, or add `.sequenced(...)` to the topology."
            )));
        }
        if !self.registered.insert(queue) {
            return Err(ShoveError::Topology(format!(
                "topic '{queue}' is already registered on this supervisor"
            )));
        }
        let ctx = self.ctx.clone();
        let inner = options.with_shutdown(self.shutdown.clone()).into_inner();
        let handles = self
            .consumer
            .spawn_fifo_shards::<T, H>(handler, ctx, inner)
            .await?;
        for handle in handles {
            // Hold an AbortOnDrop guard on the inner shard handle so that
            // when the supervisor's JoinSet aborts this wrapper (e.g. on
            // drain timeout escalation in `run_until_timeout`), the inner
            // shard task is aborted instead of detached.
            let abort_guard = AbortOnDrop(handle.abort_handle());
            self.tasks.spawn(async move {
                let _abort_guard = abort_guard;
                match handle.await {
                    Ok(r) => r,
                    Err(e) if e.is_cancelled() => Ok(()),
                    Err(e) => std::panic::resume_unwind(e.into_panic()),
                }
            });
        }
        Ok(())
    }

    pub async fn run_until_timeout<S>(
        mut self,
        signal: S,
        drain_timeout: Duration,
    ) -> SupervisorOutcome
    where
        S: Future<Output = ()> + Send + 'static,
    {
        tokio::select! {
            _ = signal => { self.shutdown.cancel(); }
            _ = self.shutdown.cancelled() => {}
        }

        let mut errors = 0usize;
        let mut panics = 0usize;

        let drain = {
            let tasks = &mut self.tasks;
            let errors = &mut errors;
            let panics = &mut panics;
            async move {
                while let Some(res) = tasks.join_next().await {
                    tally_join_result(res, errors, panics);
                }
            }
        };

        match tokio::time::timeout(drain_timeout, drain).await {
            Ok(()) => SupervisorOutcome {
                errors,
                panics,
                timed_out: false,
            },
            Err(_) => {
                tracing::warn!(
                    timeout_ms = drain_timeout.as_millis() as u64,
                    "drain timeout elapsed; aborting surviving tasks"
                );
                self.tasks.abort_all();
                while let Some(res) = self.tasks.join_next().await {
                    tally_join_result(res, &mut errors, &mut panics);
                }
                SupervisorOutcome {
                    errors,
                    panics,
                    timed_out: true,
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn clean_outcome_has_exit_code_zero() {
        assert_eq!(SupervisorOutcome::default().exit_code(), 0);
        assert!(SupervisorOutcome::default().is_clean());
    }

    #[test]
    fn errors_produce_exit_code_one() {
        let o = SupervisorOutcome {
            errors: 3,
            panics: 0,
            timed_out: false,
        };
        assert_eq!(o.exit_code(), 1);
    }

    #[test]
    fn panics_outrank_errors() {
        let o = SupervisorOutcome {
            errors: 3,
            panics: 1,
            timed_out: false,
        };
        assert_eq!(o.exit_code(), 2);
    }

    #[test]
    fn timeout_outranks_everything() {
        let o = SupervisorOutcome {
            errors: 3,
            panics: 1,
            timed_out: true,
        };
        assert_eq!(o.exit_code(), 3);
    }

    use crate::error::ShoveError;

    #[tokio::test]
    async fn tally_increments_errors_on_task_failure() {
        let mut errors = 0usize;
        let mut panics = 0usize;
        tally_join_result(
            Ok(Err(ShoveError::Topology("test".into()))),
            &mut errors,
            &mut panics,
        );
        assert_eq!(errors, 1);
        assert_eq!(panics, 0);
    }

    #[tokio::test]
    async fn tally_increments_panics_on_join_panic() {
        let handle = tokio::spawn(async { panic!("boom") });
        let join_err = handle.await.unwrap_err();
        assert!(join_err.is_panic());
        let mut errors = 0usize;
        let mut panics = 0usize;
        tally_join_result(Err(join_err), &mut errors, &mut panics);
        assert_eq!(panics, 1);
        assert_eq!(errors, 0);
    }

    #[tokio::test]
    async fn tally_ignores_cancellation() {
        let handle: tokio::task::JoinHandle<Result<()>> = tokio::spawn(async {
            tokio::time::sleep(Duration::from_secs(60)).await;
            Ok(())
        });
        handle.abort();
        let join_err = handle.await.unwrap_err();
        assert!(join_err.is_cancelled());
        let mut errors = 0usize;
        let mut panics = 0usize;
        tally_join_result(Err(join_err), &mut errors, &mut panics);
        assert_eq!(errors, 0);
        assert_eq!(panics, 0);
    }

    #[test]
    fn tally_does_not_count_success() {
        let mut errors = 0usize;
        let mut panics = 0usize;
        tally_join_result(Ok(Ok(())), &mut errors, &mut panics);
        assert_eq!(errors, 0);
        assert_eq!(panics, 0);
    }

    // -----------------------------------------------------------------------
    // drive_fifo_until_timeout — synthetic JoinHandle tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn drive_fifo_until_timeout_clean_completion_no_signal() {
        // All shards finish on their own before the signal fires. The
        // `shards_done` arm of the biased select wins, so the function
        // returns a clean outcome without ever cancelling the shutdown token.
        let handles: Vec<tokio::task::JoinHandle<Result<()>>> = vec![
            tokio::spawn(async { Ok(()) }),
            tokio::spawn(async { Ok(()) }),
        ];
        let shutdown = CancellationToken::new();
        let outcome = drive_fifo_until_timeout(
            handles,
            shutdown.clone(),
            std::future::pending::<()>(),
            Duration::from_secs(1),
        )
        .await;
        assert!(outcome.is_clean(), "unexpected outcome: {outcome:?}");
        assert!(
            !shutdown.is_cancelled(),
            "shutdown must not be cancelled when shards complete on their own"
        );
    }

    #[tokio::test]
    async fn drive_fifo_until_timeout_signal_then_clean_drain() {
        // Signal fires while shards are sleeping; they complete inside the
        // drain window so timed_out stays false.
        let handles: Vec<tokio::task::JoinHandle<Result<()>>> = vec![
            tokio::spawn(async {
                tokio::time::sleep(Duration::from_millis(20)).await;
                Ok(())
            }),
            tokio::spawn(async {
                tokio::time::sleep(Duration::from_millis(20)).await;
                Ok(())
            }),
        ];
        let shutdown = CancellationToken::new();
        let outcome = drive_fifo_until_timeout(
            handles,
            shutdown.clone(),
            async { /* signal ready immediately */ },
            Duration::from_secs(1),
        )
        .await;
        assert!(outcome.is_clean(), "unexpected outcome: {outcome:?}");
        assert!(
            shutdown.is_cancelled(),
            "shutdown must be cancelled once the signal fires"
        );
    }

    #[tokio::test]
    async fn drive_fifo_until_timeout_drain_timeout_aborts_surviving_shards() {
        // Shards never finish on their own; after signal fires the drain
        // window elapses and `abort_all` short-circuits them. Cancellation
        // surfaces as `is_cancelled()` join errors that the wrapper maps to
        // Ok(()), so the outcome is timed_out without false errors/panics.
        let handles: Vec<tokio::task::JoinHandle<Result<()>>> = (0..3)
            .map(|_| {
                tokio::spawn(async {
                    tokio::time::sleep(Duration::from_secs(60)).await;
                    Ok(())
                })
            })
            .collect();
        let shutdown = CancellationToken::new();
        let outcome = drive_fifo_until_timeout(
            handles,
            shutdown.clone(),
            async {},
            Duration::from_millis(20),
        )
        .await;
        assert!(outcome.timed_out, "expected timed_out: {outcome:?}");
        assert_eq!(outcome.errors, 0);
        assert_eq!(outcome.panics, 0);
        assert!(shutdown.is_cancelled());
    }

    #[tokio::test]
    async fn drive_fifo_until_timeout_propagates_shard_panic() {
        // A panicking shard surfaces through the wrapper's
        // `resume_unwind(into_panic())` path. The outer JoinSet catches the
        // resumed panic and tally_join_result counts it as a panic.
        let handles: Vec<tokio::task::JoinHandle<Result<()>>> =
            vec![tokio::spawn(async { panic!("synthetic shard panic") })];
        let shutdown = CancellationToken::new();
        let outcome = drive_fifo_until_timeout(
            handles,
            shutdown,
            std::future::pending::<()>(),
            Duration::from_secs(1),
        )
        .await;
        assert_eq!(
            outcome.panics, 1,
            "shard panic must be tallied: {outcome:?}"
        );
        assert_eq!(outcome.errors, 0);
        assert!(!outcome.timed_out);
    }

    #[tokio::test]
    async fn drive_fifo_until_timeout_tallies_shard_error() {
        // A shard that returns `Err(_)` increments the error counter and
        // does not panic.
        let handles: Vec<tokio::task::JoinHandle<Result<()>>> = vec![tokio::spawn(async {
            Err(ShoveError::Topology("synthetic shard error".into()))
        })];
        let shutdown = CancellationToken::new();
        let outcome = drive_fifo_until_timeout(
            handles,
            shutdown,
            std::future::pending::<()>(),
            Duration::from_secs(1),
        )
        .await;
        assert_eq!(
            outcome.errors, 1,
            "shard error must be tallied: {outcome:?}"
        );
        assert_eq!(outcome.panics, 0);
        assert!(!outcome.timed_out);
    }
}

#[cfg(all(test, feature = "inmemory"))]
mod inmemory_tests {
    use std::time::Duration;

    use serde::{Deserialize, Serialize};

    use crate::consumer::ConsumerOptions;
    use crate::error::ShoveError;
    use crate::inmemory::InMemoryConfig;
    use crate::markers::InMemory;
    use crate::topic::SequencedTopic;
    use crate::topology::{SequenceFailure, TopologyBuilder};
    use crate::{
        Broker, MessageHandler, MessageMetadata, Outcome, define_sequenced_topic, define_topic,
    };

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct LedgerEntry {
        account_id: String,
    }

    define_sequenced_topic!(
        Ledger,
        LedgerEntry,
        |msg| msg.account_id.clone(),
        TopologyBuilder::new("supervisor-ledger-test")
            .sequenced(SequenceFailure::FailAll)
            .hold_queue(Duration::from_millis(50))
            .dlq()
            .build()
    );

    struct NoopHandler;
    impl MessageHandler<Ledger> for NoopHandler {
        type Context = ();
        async fn handle(&self, _: LedgerEntry, _: MessageMetadata, _: &()) -> Outcome {
            Outcome::Ack
        }
    }

    #[tokio::test]
    async fn register_fifo_runs_cleanly() {
        let broker = Broker::<InMemory>::new(InMemoryConfig::default())
            .await
            .expect("broker");
        broker
            .topology()
            .declare::<Ledger>()
            .await
            .expect("declare");

        let mut sup = broker.consumer_supervisor();
        sup.register_fifo::<Ledger, _>(NoopHandler, ConsumerOptions::<InMemory>::new())
            .await
            .expect("register_fifo");

        let token = sup.cancellation_token();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            token.cancel();
        });

        let outcome = sup
            .run_until_timeout(std::future::pending::<()>(), Duration::from_secs(1))
            .await;
        assert!(outcome.is_clean(), "unexpected outcome: {outcome:?}");
    }

    #[tokio::test]
    async fn register_rejection_points_at_register_fifo() {
        let broker = Broker::<InMemory>::new(InMemoryConfig::default())
            .await
            .expect("broker");
        broker
            .topology()
            .declare::<Ledger>()
            .await
            .expect("declare");

        let mut sup = broker.consumer_supervisor();
        let result = sup.register::<Ledger, _>(NoopHandler, ConsumerOptions::<InMemory>::new());
        match result {
            Err(ShoveError::Topology(msg)) => {
                assert!(msg.contains("register_fifo"), "unexpected msg: {msg}");
            }
            other => panic!("expected Topology error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn register_fifo_rejects_duplicate_topic() {
        let broker = Broker::<InMemory>::new(InMemoryConfig::default())
            .await
            .expect("broker");
        broker
            .topology()
            .declare::<Ledger>()
            .await
            .expect("declare");

        let mut sup = broker.consumer_supervisor();
        sup.register_fifo::<Ledger, _>(NoopHandler, ConsumerOptions::<InMemory>::new())
            .await
            .expect("first register_fifo should succeed");

        let result = sup
            .register_fifo::<Ledger, _>(NoopHandler, ConsumerOptions::<InMemory>::new())
            .await;
        match result {
            Err(ShoveError::Topology(msg)) => {
                assert!(msg.contains("already registered"), "unexpected msg: {msg}");
            }
            other => panic!("expected Topology error, got {other:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // register / register_fifo additional rejection paths and drain timeout
    // -----------------------------------------------------------------------

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct Note {
        body: String,
    }

    define_topic!(
        Notes,
        Note,
        TopologyBuilder::new("supervisor-notes-test").build()
    );

    struct NoteHandler;
    impl MessageHandler<Notes> for NoteHandler {
        type Context = ();
        async fn handle(&self, _: Note, _: MessageMetadata, _: &()) -> Outcome {
            Outcome::Ack
        }
    }

    // A SequencedTopic intentionally paired with a non-sequenced topology so
    // we can exercise the runtime check in `register_fifo` that the topology
    // actually has `.sequenced(...)`.
    define_sequenced_topic!(
        UnsequencedBySchema,
        LedgerEntry,
        |msg| msg.account_id.clone(),
        TopologyBuilder::new("supervisor-no-seq-test").build()
    );

    struct UnsequencedHandler;
    impl MessageHandler<UnsequencedBySchema> for UnsequencedHandler {
        type Context = ();
        async fn handle(&self, _: LedgerEntry, _: MessageMetadata, _: &()) -> Outcome {
            Outcome::Ack
        }
    }

    #[tokio::test]
    async fn register_rejects_duplicate_non_sequenced_topic() {
        let broker = Broker::<InMemory>::new(InMemoryConfig::default())
            .await
            .expect("broker");
        broker.topology().declare::<Notes>().await.expect("declare");

        let mut sup = broker.consumer_supervisor();
        sup.register::<Notes, _>(NoteHandler, ConsumerOptions::<InMemory>::new())
            .expect("first register should succeed");

        let result = sup.register::<Notes, _>(NoteHandler, ConsumerOptions::<InMemory>::new());
        match result {
            Err(ShoveError::Topology(msg)) => {
                assert!(msg.contains("already registered"), "unexpected msg: {msg}");
            }
            other => panic!("expected Topology error, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn register_fifo_rejects_topic_without_sequencing_config() {
        // The macro-generated `UnsequencedBySchema` implements `SequencedTopic`
        // but its topology has no `.sequenced(...)`. `register_fifo` must
        // reject it rather than silently attaching to shard queues that were
        // never declared.
        let broker = Broker::<InMemory>::new(InMemoryConfig::default())
            .await
            .expect("broker");
        // Skip declaring the topology — declaration would also fail (or be
        // no-op) and isn't what we're testing.

        let mut sup = broker.consumer_supervisor();
        let result = sup
            .register_fifo::<UnsequencedBySchema, _>(
                UnsequencedHandler,
                ConsumerOptions::<InMemory>::new(),
            )
            .await;
        match result {
            Err(ShoveError::Topology(msg)) => {
                assert!(
                    msg.contains("no \nsequencing config") || msg.contains("sequencing config"),
                    "unexpected msg: {msg}"
                );
            }
            other => panic!("expected Topology error, got {other:?}"),
        }
    }

    /// Handler that ignores cancellation and never returns within the test
    /// window, forcing the supervisor's drain timeout to elapse.
    struct StuckHandler;
    impl MessageHandler<Notes> for StuckHandler {
        type Context = ();
        async fn handle(&self, _: Note, _: MessageMetadata, _: &()) -> Outcome {
            std::future::pending::<()>().await;
            Outcome::Ack
        }
    }

    #[tokio::test]
    async fn run_until_timeout_drain_timeout_aborts_surviving_tasks() {
        // Publish one message, register a handler that blocks forever, fire
        // the signal immediately. The consumer task is still inside the
        // handler when shutdown is cancelled, so the drain window elapses
        // and `abort_all` triggers the timed_out branch.
        let broker = Broker::<InMemory>::new(InMemoryConfig::default())
            .await
            .expect("broker");
        broker.topology().declare::<Notes>().await.expect("declare");

        // Disable the handler timeout so the handler stays inside `.handle()`
        // long enough for the drain timeout to fire instead of the handler
        // timeout returning Retry.
        let opts = ConsumerOptions::<InMemory>::new().without_handler_timeout();

        let mut sup = broker.consumer_supervisor();
        sup.register::<Notes, _>(StuckHandler, opts)
            .expect("register");

        let publisher = broker.publisher().await.expect("publisher");
        publisher
            .publish::<Notes>(&Note {
                body: "stuck".into(),
            })
            .await
            .expect("publish");

        // Give the consumer a moment to pick up the message and enter the
        // handler before we signal shutdown.
        tokio::time::sleep(Duration::from_millis(50)).await;

        let outcome = sup
            .run_until_timeout(
                async { /* signal immediately */ },
                Duration::from_millis(50),
            )
            .await;

        assert!(
            outcome.timed_out,
            "expected drain timeout, got: {outcome:?}"
        );
        assert_eq!(outcome.exit_code(), 3);
    }
}