hyperlane-plugin-mq 22.14.0

A message queue plugin for the Hyperlane framework providing a pluggable MessageBroker trait and an in-memory broker with consumer groups, visibility timeouts, retries, TTL expiration, and dead-letter queues.
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
use super::*;

/// Default construction for [`FnvHasher`].
impl Default for FnvHasher {
    /// Initializes [`FnvHasher`] with the 64-bit FNV-1a offset basis.
    #[inline(always)]
    fn default() -> Self {
        Self {
            state: FNV1A_OFFSET_BASIS,
        }
    }
}

/// Implements [`Hasher`] for [`FnvHasher`].
impl Hasher for FnvHasher {
    /// Returns the finalized 64-bit hash value.
    ///
    /// # Returns
    ///
    /// - `u64` - Computed FNV-1a hash.
    #[inline(always)]
    fn finish(&self) -> u64 {
        let Self { state } = *self;
        state
    }

    /// Mixes `bytes` into the FNV-1a state.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input byte slice.
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
        let Self { state } = self;
        let mut h: u64 = *state;
        for &b in bytes {
            h ^= u64::from(b);
            h = h.wrapping_mul(FNV1A_PRIME);
        }
        *state = h;
    }

    /// Fast Fibonacci mixing for `u64` receipt keys.
    ///
    /// # Arguments
    ///
    /// - `u64` - Integer key.
    #[inline(always)]
    fn write_u64(&mut self, i: u64) {
        let Self { state } = self;
        *state = i.wrapping_mul(0x9e37_79b9_7f4a_7c15);
    }
}

/// Formatting / debug-printing for [`MqError`].
impl Display for MqError {
    /// Formats the [`MqError`] via the supplied formatter.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - A `fmt::Result` value.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::QueueFull => f.write_str(ERR_MQ_QUEUE_FULL),
            Self::UnknownDelivery => f.write_str(ERR_MQ_UNKNOWN_DELIVERY),
            Self::BrokerClosed => f.write_str(ERR_MQ_BROKER_CLOSED),
            Self::MessageExpired => f.write_str(ERR_MQ_EXPIRED),
            Self::Backend(msg) => f.write_str(msg),
        }
    }
}

/// Implements [`Error`] for [`MqError`].
impl Error for MqError {}

/// Default construction for [`MqConfig`].
impl Default for MqConfig {
    /// Constructs a default [`MqConfig`] value.
    fn default() -> Self {
        Self {
            max_queue_len: DEFAULT_MQ_MAX_QUEUE_LEN,
            visibility_timeout_ms: DEFAULT_MQ_VISIBILITY_TIMEOUT_MS,
            default_max_retries: DEFAULT_MQ_MAX_RETRIES,
            dlq_suffix: DEFAULT_MQ_DLQ_SUFFIX.to_owned(),
        }
    }
}

/// Inherent implementation of [`MqConfig`].
impl MqConfig {
    /// Sets the maximum pending queue length per `(topic, group)`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum pending messages.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_max_queue_len(mut self, max_queue_len: usize) -> Self {
        self.set_max_queue_len(max_queue_len);
        self
    }

    /// Sets the visibility timeout in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Visibility timeout in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_visibility_timeout_ms(mut self, visibility_timeout_ms: u64) -> Self {
        self.set_visibility_timeout_ms(visibility_timeout_ms);
        self
    }

    /// Sets the default retry count before routing to the dead-letter queue.
    ///
    /// # Arguments
    ///
    /// - `u32` - Default maximum attempts.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_default_max_retries(mut self, default_max_retries: u32) -> Self {
        self.set_default_max_retries(default_max_retries);
        self
    }

    /// Sets the dead-letter queue topic suffix.
    ///
    /// # Arguments
    ///
    /// - `S` - Suffix convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_dlq_suffix<S>(mut self, dlq_suffix: S) -> Self
    where
        S: Into<String>,
    {
        self.set_dlq_suffix(dlq_suffix.into());
        self
    }
}

/// Inherent implementation of [`MqMessage`].
impl MqMessage {
    /// Creates a new message targeting `topic` with raw `payload` bytes.
    ///
    /// # Arguments
    ///
    /// - `T` - Topic name convertible into `String`.
    /// - `P` - Payload bytes convertible into `Vec<u8>`.
    ///
    /// # Returns
    ///
    /// - `Self` - Newly constructed message stamped with the current epoch millisecond.
    #[inline]
    pub fn new<T, P>(topic: T, payload: P) -> Self
    where
        T: Into<String>,
        P: Into<Vec<u8>>,
    {
        Self {
            id: 0,
            topic: topic.into(),
            key: None,
            payload: payload.into(),
            headers: HashMap::new(),
            attempts: 0,
            max_retries: 0,
            created_at_ms: now_epoch_ms(),
            expires_at_ms: None,
        }
    }

    /// Sets an optional routing or partitioning key.
    ///
    /// # Arguments
    ///
    /// - `K` - Routing key convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated message.
    pub fn with_key<K>(mut self, key: K) -> Self
    where
        K: Into<String>,
    {
        self.set_key(Some(key.into()));
        self
    }

    /// Inserts a metadata header key-value pair on this message.
    ///
    /// # Arguments
    ///
    /// - `K` - Header key convertible into `String`.
    /// - `V` - Header value convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated message.
    pub fn with_header<K, V>(mut self, key: K, value: V) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        self.get_mut_headers().insert(key.into(), value.into());
        self
    }

    /// Configures a relative time-to-live in milliseconds from creation time.
    ///
    /// # Arguments
    ///
    /// - `u64` - TTL in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated message with `expires_at_ms` set.
    pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
        let base: u64 = self.get_created_at_ms();
        self.set_expires_at_ms(Some(base.saturating_add(ttl_ms)));
        self
    }

    /// Overrides the maximum delivery attempts before dead-lettering.
    ///
    /// # Arguments
    ///
    /// - `u32` - Maximum attempts allowed for this message.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated message.
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.set_max_retries(max_retries);
        self
    }
}

/// Inherent helpers for [`QueuedMessage`].
impl QueuedMessage {
    /// Borrows the underlying [`MqMessage`] regardless of ownership mode.
    ///
    /// # Returns
    ///
    /// - `&MqMessage` - Borrowed message reference.
    #[inline(always)]
    pub(crate) fn as_msg(&self) -> &MqMessage {
        match self {
            Self::Owned(msg) => msg,
            Self::Shared(arc) => arc.as_ref(),
        }
    }

    /// Consumes this handle into an owned [`MqMessage`] stamped with `attempts`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Delivery attempt count to stamp on the returned message.
    ///
    /// # Returns
    ///
    /// - `MqMessage` - Owned message with updated attempt counter.
    #[inline]
    pub(crate) fn into_owned_with_attempts(self, attempts: u32) -> MqMessage {
        let mut msg: MqMessage = match self {
            Self::Owned(owned) => owned,
            Self::Shared(arc) => {
                Arc::try_unwrap(arc).unwrap_or_else(|shared: Arc<MqMessage>| (*shared).clone())
            }
        };
        msg.set_attempts(attempts);
        msg
    }
}

/// Inherent helpers for [`TopicBrokerState`].
impl TopicBrokerState {
    /// Returns the dense slot index for `group`, creating a new [`GroupState`] if absent.
    ///
    /// # Arguments
    ///
    /// - `&str` - Consumer group name.
    ///
    /// # Returns
    ///
    /// - `usize` - Dense slot index in `self.groups`.
    #[inline]
    pub(crate) fn ensure_group_slot(&mut self, group: &str) -> usize {
        let Self {
            group_index,
            groups,
            ..
        } = self;
        if let Some(&idx) = group_index.get(group) {
            return idx;
        }
        let idx: usize = groups.len();
        groups.push(GroupState {
            queue: VecDeque::new(),
            in_flight_count: 0,
            acked_total: 0,
        });
        group_index.insert(group.to_owned(), idx);
        idx
    }
}

/// Inherent implementation of [`InMemoryBroker`].
impl InMemoryBroker {
    /// Creates a new 64-shard [`InMemoryBroker`] governed by `config`.
    ///
    /// # Arguments
    ///
    /// - `MqConfig` - Queue capacity, retry, and visibility timeout settings.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready in-memory message broker.
    pub fn new(config: MqConfig) -> Self {
        let topic_shards: TopicShardArray = Box::new(from_fn(|_: usize| {
            RwLock::new(FnvHashMap::with_hasher(BuildHasherDefault::default()))
        }));
        let fast_topics: FastTopicTable = Box::new(from_fn(|_: usize| OnceLock::new()));
        Self {
            inner: Arc::new(InMemoryBrokerInner {
                config,
                next_msg_id: AtomicU64::new(1),
                next_receipt_seq: AtomicU64::new(1),
                next_topic_id: AtomicU32::new(0),
                topic_shards,
                fast_topics,
                overflow_topics: RwLock::new(Vec::new()),
            }),
        }
    }

    /// Returns a reference to this broker's [`MqConfig`].
    ///
    /// # Returns
    ///
    /// - `&MqConfig` - Active broker configuration.
    #[inline(always)]
    pub fn get_config(&self) -> &MqConfig {
        &self.inner.config
    }

    /// Looks up an existing [`TopicBroker`] for `topic` via read-fast sharding.
    ///
    /// # Arguments
    ///
    /// - `&str` - Topic name.
    ///
    /// # Returns
    ///
    /// - `Option<Arc<TopicBroker>>` - Shared topic broker, if present.
    #[inline]
    fn get_topic(&self, topic: &str) -> Option<Arc<TopicBroker>> {
        let Self { inner } = self;
        let idx: usize = mq_topic_shard_index(topic);
        inner.topic_shards[idx].read().ok().and_then(
            |map: RwLockReadGuard<'_, FnvHashMap<String, Arc<TopicBroker>>>| {
                map.get(topic).cloned()
            },
        )
    }

    /// Looks up the owning [`TopicBroker`] for `receipt_id` in lock-free `O(1)` time.
    ///
    /// # Arguments
    ///
    /// - `u64` - Packed delivery receipt identifier.
    ///
    /// # Returns
    ///
    /// - `Option<Arc<TopicBroker>>` - Owning topic broker, if valid.
    #[inline(always)]
    fn get_topic_by_receipt(&self, receipt_id: u64) -> Option<Arc<TopicBroker>> {
        let Self { inner } = self;
        let topic_id: usize = decode_receipt_topic_id(receipt_id);
        if topic_id < MQ_FAST_TOPIC_SLOTS {
            return inner.fast_topics[topic_id].get().cloned();
        }
        let overflow_idx: usize = topic_id - MQ_FAST_TOPIC_SLOTS;
        inner.overflow_topics.read().ok().and_then(
            |vec: RwLockReadGuard<'_, Vec<Arc<TopicBroker>>>| vec.get(overflow_idx).cloned(),
        )
    }

    /// Looks up or inserts the [`TopicBroker`] for `topic` via read-fast sharding.
    ///
    /// # Arguments
    ///
    /// - `&str` - Topic name.
    ///
    /// # Returns
    ///
    /// - `Result<Arc<TopicBroker>, MqError>` - Shared topic broker or [`MqError::BrokerClosed`].
    fn get_or_create_topic(&self, topic: &str) -> Result<Arc<TopicBroker>, MqError> {
        if let Some(existing) = self.get_topic(topic) {
            return Ok(existing);
        }
        let Self { inner } = self;
        let idx: usize = mq_topic_shard_index(topic);
        let Ok(mut write_map) = inner.topic_shards[idx].write() else {
            return Err(MqError::BrokerClosed);
        };
        if let Some(existing) = write_map.get(topic) {
            return Ok(Arc::clone(existing));
        }
        let topic_id: u32 = inner.next_topic_id.fetch_add(1, Ordering::Relaxed);
        let created: Arc<TopicBroker> = Arc::new(TopicBroker {
            topic_id,
            published_total: AtomicU64::new(0),
            state: Mutex::new(TopicBrokerState {
                group_index: FnvHashMap::with_hasher(BuildHasherDefault::default()),
                groups: Vec::new(),
                explicit_groups: Vec::new(),
                default_group_idx: MQ_GROUP_UNSET,
                in_flight: FnvHashMap::with_hasher(BuildHasherDefault::default()),
                deadlines: BinaryHeap::new(),
                dlq: VecDeque::new(),
            }),
        });
        let slot: usize = topic_id as usize;
        if slot < MQ_FAST_TOPIC_SLOTS {
            let _: Result<(), Arc<TopicBroker>> = inner.fast_topics[slot].set(Arc::clone(&created));
        } else if let Ok(mut overflow) = inner.overflow_topics.write() {
            let overflow_idx: usize = slot - MQ_FAST_TOPIC_SLOTS;
            if overflow.len() <= overflow_idx {
                overflow.resize(overflow_idx + 1, Arc::clone(&created));
            } else {
                overflow[overflow_idx] = Arc::clone(&created);
            }
        }
        write_map.insert(topic.to_owned(), Arc::clone(&created));
        Ok(created)
    }

    /// Reclaims expired in-flight leases for one topic in `O(k log N)` via its min-heap.
    ///
    /// # Arguments
    ///
    /// - `&mut TopicBrokerState` - Locked per-topic broker state.
    /// - `&MqConfig` - Broker configuration.
    /// - `u64` - Current Unix timestamp in milliseconds.
    #[inline]
    fn reclaim_expired_topic_leases(state: &mut TopicBrokerState, config: &MqConfig, now_ms: u64) {
        if state.in_flight.is_empty() {
            if !state.deadlines.is_empty() {
                state.deadlines.clear();
            }
            return;
        }
        while let Some(Reverse((deadline, receipt_id))) = state.deadlines.peek().copied() {
            if deadline > now_ms {
                break;
            }
            let _: Option<Reverse<(u64, u64)>> = state.deadlines.pop();
            let Some(entry) = state.in_flight.remove(&receipt_id) else {
                continue;
            };
            let group_state: &mut GroupState = &mut state.groups[entry.group_idx];
            group_state.in_flight_count = group_state.in_flight_count.saturating_sub(1);
            let msg_ref: &MqMessage = entry.message.as_msg();
            if is_message_expired(msg_ref, now_ms) {
                continue;
            }
            let max_attempts: u32 = if msg_ref.get_max_retries() > 0 {
                msg_ref.get_max_retries()
            } else {
                config.get_default_max_retries().max(1)
            };
            let owned_msg: MqMessage = entry.message.into_owned_with_attempts(entry.attempts);
            if entry.attempts >= max_attempts {
                state.dlq.push_back(owned_msg);
            } else {
                group_state
                    .queue
                    .push_front(QueuedMessage::Owned(owned_msg));
            }
        }
    }

    /// Executes synchronous subscribe-group registration.
    ///
    /// # Arguments
    ///
    /// - `&str` - Topic name.
    /// - `&str` - Consumer group name.
    ///
    /// # Returns
    ///
    /// - `Result<(), MqError>` - Registration result.
    #[inline]
    fn subscribe_group_sync(&self, topic: &str, group: &str) -> Result<(), MqError> {
        let topic_broker: Arc<TopicBroker> = self.get_or_create_topic(topic)?;
        let Ok(mut state) = topic_broker.state.lock() else {
            return Err(MqError::BrokerClosed);
        };
        let slot: usize = state.ensure_group_slot(group);
        if !state.explicit_groups.contains(&slot) {
            state.explicit_groups.push(slot);
        }
        Ok(())
    }

    /// Executes synchronous message publish with zero-clone single-group fast path.
    ///
    /// # Arguments
    ///
    /// - `MqMessage` - Message to publish.
    ///
    /// # Returns
    ///
    /// - `Result<u64, MqError>` - Assigned message identifier or error.
    #[inline]
    fn publish_sync(&self, mut message: MqMessage) -> Result<u64, MqError> {
        let Self { inner } = self;
        if let Some(deadline) = message.get_expires_at_ms()
            && now_epoch_ms() >= deadline
        {
            return Err(MqError::MessageExpired);
        }
        let id: u64 = inner.next_msg_id.fetch_add(1, Ordering::Relaxed);
        message.set_id(id);
        if message.get_max_retries() == 0 {
            message.set_max_retries(inner.config.get_default_max_retries().max(1));
        }
        let topic_broker: Arc<TopicBroker> = self.get_or_create_topic(message.get_topic())?;
        let max_len: usize = inner.config.get_max_queue_len();
        let Ok(mut state) = topic_broker.state.lock() else {
            return Err(MqError::BrokerClosed);
        };
        if state.explicit_groups.is_empty() {
            let slot: usize = if state.default_group_idx != MQ_GROUP_UNSET {
                state.default_group_idx
            } else {
                let created: usize = state.ensure_group_slot(DEFAULT_MQ_GROUP);
                state.default_group_idx = created;
                created
            };
            let queue: &mut VecDeque<QueuedMessage> = &mut state.groups[slot].queue;
            if queue.len() >= max_len {
                return Err(MqError::QueueFull);
            }
            queue.push_back(QueuedMessage::Owned(message));
        } else {
            let group_count: usize = state.explicit_groups.len();
            for &slot in &state.explicit_groups {
                if state.groups[slot].queue.len() >= max_len {
                    return Err(MqError::QueueFull);
                }
            }
            if group_count == 1 {
                let slot: usize = state.explicit_groups[0];
                state.groups[slot]
                    .queue
                    .push_back(QueuedMessage::Owned(message));
            } else {
                let shared: Arc<MqMessage> = Arc::new(message);
                let last_idx: usize = group_count - 1;
                for i in 0..last_idx {
                    let slot: usize = state.explicit_groups[i];
                    state.groups[slot]
                        .queue
                        .push_back(QueuedMessage::Shared(Arc::clone(&shared)));
                }
                let last_slot: usize = state.explicit_groups[last_idx];
                state.groups[last_slot]
                    .queue
                    .push_back(QueuedMessage::Shared(shared));
            }
        }
        topic_broker.published_total.fetch_add(1, Ordering::Relaxed);
        Ok(id)
    }

    /// Executes synchronous message lease without secondary receipt shard locking.
    ///
    /// # Arguments
    ///
    /// - `&str` - Topic name.
    /// - `&str` - Consumer group name.
    ///
    /// # Returns
    ///
    /// - `Result<Option<MqDelivery>, MqError>` - Leased delivery or `None` when empty.
    #[inline]
    fn consume_sync(&self, topic: &str, group: &str) -> Result<Option<MqDelivery>, MqError> {
        let Self { inner } = self;
        let Some(topic_broker) = self.get_topic(topic) else {
            return Ok(None);
        };
        let Ok(mut state) = topic_broker.state.lock() else {
            return Err(MqError::BrokerClosed);
        };
        let mut now_cache: Option<u64> = None;
        if !state.deadlines.is_empty() {
            let now_ms: u64 = *now_cache.get_or_insert_with(now_epoch_ms);
            Self::reclaim_expired_topic_leases(&mut state, &inner.config, now_ms);
        }
        let Some(&group_idx) = state.group_index.get(group) else {
            return Ok(None);
        };
        let mut next_msg: Option<QueuedMessage> = None;
        let queue: &mut VecDeque<QueuedMessage> = &mut state.groups[group_idx].queue;
        while let Some(candidate) = queue.pop_front() {
            if let Some(deadline) = candidate.as_msg().get_expires_at_ms() {
                let now_ms: u64 = *now_cache.get_or_insert_with(now_epoch_ms);
                if now_ms >= deadline {
                    continue;
                }
            }
            next_msg = Some(candidate);
            break;
        }
        let Some(queued) = next_msg else {
            return Ok(None);
        };
        let next_attempts: u32 = queued.as_msg().get_attempts().saturating_add(1);
        let (delivery_msg, stored_msg): (MqMessage, QueuedMessage) = match queued {
            QueuedMessage::Owned(mut owned) => {
                owned.set_attempts(next_attempts);
                let delivery_copy: MqMessage = owned.clone();
                (delivery_copy, QueuedMessage::Owned(owned))
            }
            QueuedMessage::Shared(arc) => {
                let mut delivery_copy: MqMessage = (*arc).clone();
                delivery_copy.set_attempts(next_attempts);
                (delivery_copy, QueuedMessage::Shared(arc))
            }
        };
        let now_ms: u64 = *now_cache.get_or_insert_with(now_epoch_ms);
        let seq: u64 = inner.next_receipt_seq.fetch_add(1, Ordering::Relaxed);
        let receipt_id: u64 = encode_receipt_id(topic_broker.topic_id, seq);
        let visible_after_ms: u64 = now_ms.saturating_add(inner.config.get_visibility_timeout_ms());
        state.groups[group_idx].in_flight_count += 1;
        state.in_flight.insert(
            receipt_id,
            InFlightEntry {
                group_idx,
                attempts: next_attempts,
                message: stored_msg,
            },
        );
        state
            .deadlines
            .push(Reverse((visible_after_ms, receipt_id)));
        Ok(Some(MqDelivery {
            message: delivery_msg,
            receipt_id,
            group: group.to_owned(),
        }))
    }

    /// Executes synchronous delivery acknowledgement with lock-free topic routing.
    ///
    /// # Arguments
    ///
    /// - `u64` - Delivery receipt identifier.
    ///
    /// # Returns
    ///
    /// - `Result<(), MqError>` - `Ok(())` or [`MqError::UnknownDelivery`].
    #[inline]
    fn ack_sync(&self, receipt_id: u64) -> Result<(), MqError> {
        let Some(topic_broker) = self.get_topic_by_receipt(receipt_id) else {
            return Err(MqError::UnknownDelivery);
        };
        let Ok(mut state) = topic_broker.state.lock() else {
            return Err(MqError::BrokerClosed);
        };
        let Some(entry) = state.in_flight.remove(&receipt_id) else {
            return Err(MqError::UnknownDelivery);
        };
        let group_state: &mut GroupState = &mut state.groups[entry.group_idx];
        group_state.in_flight_count = group_state.in_flight_count.saturating_sub(1);
        group_state.acked_total = group_state.acked_total.saturating_add(1);
        if state.in_flight.is_empty() && !state.deadlines.is_empty() {
            state.deadlines.clear();
        }
        Ok(())
    }

    /// Executes synchronous negative acknowledgement with O(1) requeue or DLQ routing.
    ///
    /// # Arguments
    ///
    /// - `u64` - Delivery receipt identifier.
    /// - `bool` - `true` to requeue when retries remain, `false` to dead-letter immediately.
    ///
    /// # Returns
    ///
    /// - `Result<(), MqError>` - `Ok(())` or [`MqError::UnknownDelivery`].
    #[inline]
    fn nack_sync(&self, receipt_id: u64, requeue: bool) -> Result<(), MqError> {
        let Self { inner } = self;
        let Some(topic_broker) = self.get_topic_by_receipt(receipt_id) else {
            return Err(MqError::UnknownDelivery);
        };
        let Ok(mut state) = topic_broker.state.lock() else {
            return Err(MqError::BrokerClosed);
        };
        let Some(entry) = state.in_flight.remove(&receipt_id) else {
            return Err(MqError::UnknownDelivery);
        };
        state.groups[entry.group_idx].in_flight_count = state.groups[entry.group_idx]
            .in_flight_count
            .saturating_sub(1);
        if state.in_flight.is_empty() && !state.deadlines.is_empty() {
            state.deadlines.clear();
        }
        let msg_ref: &MqMessage = entry.message.as_msg();
        if let Some(deadline) = msg_ref.get_expires_at_ms()
            && now_epoch_ms() >= deadline
        {
            return Ok(());
        }
        let max_attempts: u32 = if msg_ref.get_max_retries() > 0 {
            msg_ref.get_max_retries()
        } else {
            inner.config.get_default_max_retries().max(1)
        };
        let owned_msg: MqMessage = entry.message.into_owned_with_attempts(entry.attempts);
        if requeue && entry.attempts < max_attempts {
            state.groups[entry.group_idx]
                .queue
                .push_back(QueuedMessage::Owned(owned_msg));
        } else {
            state.dlq.push_back(owned_msg);
        }
        Ok(())
    }

    /// Executes synchronous point-in-time queue statistics collection in `O(1)`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Topic name.
    /// - `&str` - Consumer group name.
    ///
    /// # Returns
    ///
    /// - `Result<MqStats, MqError>` - Current queue counters.
    #[inline]
    fn stats_sync(&self, topic: &str, group: &str) -> Result<MqStats, MqError> {
        let Self { inner } = self;
        let Some(topic_broker) = self.get_topic(topic) else {
            return Ok(MqStats::default());
        };
        let Ok(mut state) = topic_broker.state.lock() else {
            return Err(MqError::BrokerClosed);
        };
        if !state.deadlines.is_empty() {
            let now_ms: u64 = now_epoch_ms();
            Self::reclaim_expired_topic_leases(&mut state, &inner.config, now_ms);
        }
        let (queued, in_flight, acked_total): (usize, usize, u64) =
            match state.group_index.get(group) {
                Some(&slot) => {
                    let gs: &GroupState = &state.groups[slot];
                    (gs.queue.len(), gs.in_flight_count, gs.acked_total)
                }
                None => (0, 0, 0),
            };
        let dead_lettered: usize = state.dlq.len();
        let published_total: u64 = topic_broker.published_total.load(Ordering::Relaxed);
        Ok(MqStats {
            queued,
            in_flight,
            dead_lettered,
            published_total,
            acked_total,
        })
    }

    /// Drains and returns all dead-lettered messages currently buffered for `topic`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Base topic name.
    ///
    /// # Returns
    ///
    /// - `Vec<MqMessage>` - All dead-lettered messages in FIFO order.
    pub fn drain_dlq(&self, topic: &str) -> Vec<MqMessage> {
        let Some(topic_broker) = self.get_topic(topic) else {
            return Vec::new();
        };
        let Ok(mut state) = topic_broker.state.lock() else {
            return Vec::new();
        };
        state.dlq.drain(..).collect()
    }

    /// Returns the number of dead-lettered messages currently buffered for `topic`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Base topic name.
    ///
    /// # Returns
    ///
    /// - `usize` - Count of messages waiting in the dead-letter queue.
    pub fn dlq_len(&self, topic: &str) -> usize {
        let Some(topic_broker) = self.get_topic(topic) else {
            return 0;
        };
        topic_broker
            .state
            .lock()
            .map(|state: MutexGuard<'_, TopicBrokerState>| state.dlq.len())
            .unwrap_or(0)
    }

    /// Returns the canonical dead-letter topic name for `topic` using this broker's config.
    ///
    /// # Arguments
    ///
    /// - `&str` - Base topic name.
    ///
    /// # Returns
    ///
    /// - `String` - Configured dead-letter topic name.
    pub fn dlq_name(&self, topic: &str) -> String {
        dlq_topic_name(topic, self.get_config())
    }
}

/// Default construction for [`InMemoryBroker`].
impl Default for InMemoryBroker {
    /// Constructs a default [`InMemoryBroker`] value.
    fn default() -> Self {
        Self::new(MqConfig::default())
    }
}

/// Implements [`MessageBroker`] for [`InMemoryBroker`].
impl MessageBroker for InMemoryBroker {
    /// Implements the `subscribe_group` operation on [`InMemoryBroker`].
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to a `'a self`.
    /// - `&'a str` - Shared reference to a `'a str`.
    /// - `&'a str` - Shared reference to a `'a str`.
    ///
    /// # Returns
    ///
    /// - `BrokerFuture<'a, ()>` - A `BrokerFuture<'a, ()>` value.
    fn subscribe_group<'a>(&'a self, topic: &'a str, group: &'a str) -> BrokerFuture<'a, ()> {
        Box::pin(async move { self.subscribe_group_sync(topic, group) })
    }

    /// Implements the `publish` operation on [`InMemoryBroker`].
    ///
    /// # Arguments
    ///
    /// - `MqMessage` - A `MqMessage` parameter.
    ///
    /// # Returns
    ///
    /// - `BrokerFuture<'_, u64>` - A `BrokerFuture<'_, u64>` value.
    fn publish(&self, message: MqMessage) -> BrokerFuture<'_, u64> {
        let res: Result<u64, MqError> = self.publish_sync(message);
        Box::pin(async move { res })
    }

    /// Implements the `consume` operation on [`InMemoryBroker`].
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to a `'a self`.
    /// - `&'a str` - Shared reference to a `'a str`.
    /// - `&'a str` - Shared reference to a `'a str`.
    ///
    /// # Returns
    ///
    /// - `BrokerFuture<'a, Option<MqDelivery>>` - A `BrokerFuture<'a, Option<MqDelivery>>` value.
    fn consume<'a>(
        &'a self,
        topic: &'a str,
        group: &'a str,
    ) -> BrokerFuture<'a, Option<MqDelivery>> {
        Box::pin(async move { self.consume_sync(topic, group) })
    }

    /// Implements the `ack` operation on [`InMemoryBroker`].
    ///
    /// # Arguments
    ///
    /// - `u64` - A `u64` parameter.
    ///
    /// # Returns
    ///
    /// - `BrokerFuture<'_, ()>` - A `BrokerFuture<'_, ()>` value.
    fn ack(&self, receipt_id: u64) -> BrokerFuture<'_, ()> {
        Box::pin(async move { self.ack_sync(receipt_id) })
    }

    /// Implements the `nack` operation on [`InMemoryBroker`].
    ///
    /// # Arguments
    ///
    /// - `u64` - A `u64` parameter.
    /// - `bool` - A boolean (`bool`).
    ///
    /// # Returns
    ///
    /// - `BrokerFuture<'_, ()>` - A `BrokerFuture<'_, ()>` value.
    fn nack(&self, receipt_id: u64, requeue: bool) -> BrokerFuture<'_, ()> {
        Box::pin(async move { self.nack_sync(receipt_id, requeue) })
    }

    /// Implements the `stats` operation on [`InMemoryBroker`].
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to a `'a self`.
    /// - `&'a str` - Shared reference to a `'a str`.
    /// - `&'a str` - Shared reference to a `'a str`.
    ///
    /// # Returns
    ///
    /// - `BrokerFuture<'a, MqStats>` - A `BrokerFuture<'a, MqStats>` value.
    fn stats<'a>(&'a self, topic: &'a str, group: &'a str) -> BrokerFuture<'a, MqStats> {
        Box::pin(async move { self.stats_sync(topic, group) })
    }
}

/// Inherent implementation of [`MqPlugin`].
impl MqPlugin {
    /// Initializes the global [`MqPlugin`] once with `config`.
    ///
    /// # Arguments
    ///
    /// - `MqConfig` - Message queue broker configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin instance.
    pub fn init(config: MqConfig) -> &'static Self {
        MQ_PLUGIN.get_or_init(|| Self {
            broker: InMemoryBroker::new(config.clone()),
            config,
            custom_broker: None,
        })
    }

    /// Initializes the global [`MqPlugin`] once with a custom pluggable [`MessageBroker`] backend.
    ///
    /// # Arguments
    ///
    /// - `MqConfig` - Message queue broker configuration.
    /// - `SharedBroker` - Custom message broker implementation.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin instance.
    pub fn init_with_broker(config: MqConfig, broker: SharedBroker) -> &'static Self {
        MQ_PLUGIN.get_or_init(|| Self {
            broker: InMemoryBroker::new(config.clone()),
            config,
            custom_broker: Some(broker),
        })
    }

    /// Returns the initialized global [`MqPlugin`], if [`MqPlugin::init`] was called.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        MQ_PLUGIN.get()
    }

    /// Returns the plugin's [`MqConfig`].
    ///
    /// # Returns
    ///
    /// - `&MqConfig` - Active configuration.
    #[inline(always)]
    pub fn get_config(&self) -> &MqConfig {
        &self.config
    }

    /// Returns the plugin's shared [`InMemoryBroker`].
    ///
    /// # Returns
    ///
    /// - `&InMemoryBroker` - Process-wide in-memory broker.
    #[inline(always)]
    pub fn get_broker(&self) -> &InMemoryBroker {
        &self.broker
    }

    /// Returns the custom pluggable [`SharedBroker`] backend when installed via [`MqPlugin::init_with_broker`].
    ///
    /// # Returns
    ///
    /// - `Option<&SharedBroker>` - Active custom broker backend, or `None`.
    #[inline(always)]
    pub fn get_custom_broker(&self) -> Option<&SharedBroker> {
        self.custom_broker.as_ref()
    }
}