Skip to main content

hyperlane_plugin_mq/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`FnvHasher`] using 8-byte word multiplicative mixing.
4impl Hasher for FnvHasher {
5    /// Returns the finalized 64-bit hash value.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Computed 64-bit hash.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Mixes `bytes` 8 bytes at a time into the hash state without heap allocation.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        let mut h: u64 = *state;
25        for &b in bytes {
26            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
27        }
28        *state = h;
29    }
30
31    /// Mixes a single `u8` byte into the hash state.
32    ///
33    /// # Arguments
34    ///
35    /// - `u8` - Input byte.
36    #[inline(always)]
37    fn write_u8(&mut self, i: u8) {
38        let Self { state } = self;
39        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
40    }
41
42    /// Fast Fibonacci mixing for `u64` receipt keys.
43    ///
44    /// # Arguments
45    ///
46    /// - `u64` - Integer key.
47    #[inline(always)]
48    fn write_u64(&mut self, i: u64) {
49        let Self { state } = self;
50        *state = i.wrapping_mul(FIB_HASH_K);
51    }
52}
53
54/// Formatting / debug-printing for [`MqError`].
55impl Display for MqError {
56    /// Formats the [`MqError`] via the supplied formatter.
57    ///
58    /// # Arguments
59    ///
60    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
61    ///
62    /// # Returns
63    ///
64    /// - `fmt::Result` - A `fmt::Result` value.
65    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
66        match self {
67            Self::QueueFull => f.write_str(ERR_MQ_QUEUE_FULL),
68            Self::UnknownDelivery => f.write_str(ERR_MQ_UNKNOWN_DELIVERY),
69            Self::BrokerClosed => f.write_str(ERR_MQ_BROKER_CLOSED),
70            Self::MessageExpired => f.write_str(ERR_MQ_EXPIRED),
71            Self::Backend(msg) => f.write_str(msg),
72        }
73    }
74}
75
76/// Implements [`Error`] for [`MqError`].
77impl Error for MqError {}
78
79/// Default construction for [`MqConfig`].
80impl Default for MqConfig {
81    /// Constructs a default [`MqConfig`] value.
82    fn default() -> Self {
83        Self {
84            max_queue_len: DEFAULT_MQ_MAX_QUEUE_LEN,
85            visibility_timeout_ms: DEFAULT_MQ_VISIBILITY_TIMEOUT_MS,
86            default_max_retries: DEFAULT_MQ_MAX_RETRIES,
87            dlq_suffix: DEFAULT_MQ_DLQ_SUFFIX.to_owned(),
88        }
89    }
90}
91
92/// Inherent implementation of [`MqConfig`].
93impl MqConfig {
94    /// Sets the maximum pending queue length per `(topic, group)`.
95    ///
96    /// # Arguments
97    ///
98    /// - `usize` - Maximum pending messages.
99    ///
100    /// # Returns
101    ///
102    /// - `Self` - Updated configuration.
103    pub fn with_max_queue_len(mut self, max_queue_len: usize) -> Self {
104        self.set_max_queue_len(max_queue_len);
105        self
106    }
107
108    /// Sets the visibility timeout in milliseconds.
109    ///
110    /// # Arguments
111    ///
112    /// - `u64` - Visibility timeout in milliseconds.
113    ///
114    /// # Returns
115    ///
116    /// - `Self` - Updated configuration.
117    pub fn with_visibility_timeout_ms(mut self, visibility_timeout_ms: u64) -> Self {
118        self.set_visibility_timeout_ms(visibility_timeout_ms);
119        self
120    }
121
122    /// Sets the default retry count before routing to the dead-letter queue.
123    ///
124    /// # Arguments
125    ///
126    /// - `u32` - Default maximum attempts.
127    ///
128    /// # Returns
129    ///
130    /// - `Self` - Updated configuration.
131    pub fn with_default_max_retries(mut self, default_max_retries: u32) -> Self {
132        self.set_default_max_retries(default_max_retries);
133        self
134    }
135
136    /// Sets the dead-letter queue topic suffix.
137    ///
138    /// # Arguments
139    ///
140    /// - `S` - Suffix convertible into `String`.
141    ///
142    /// # Returns
143    ///
144    /// - `Self` - Updated configuration.
145    pub fn with_dlq_suffix<S>(mut self, dlq_suffix: S) -> Self
146    where
147        S: Into<String>,
148    {
149        self.set_dlq_suffix(dlq_suffix.into());
150        self
151    }
152}
153
154/// Inherent implementation of [`MqMessage`].
155impl MqMessage {
156    /// Creates a new message targeting `topic` with raw `payload` bytes.
157    ///
158    /// # Arguments
159    ///
160    /// - `T` - Topic name convertible into `String`.
161    /// - `P` - Payload bytes convertible into `Vec<u8>`.
162    ///
163    /// # Returns
164    ///
165    /// - `Self` - Newly constructed message stamped with the current epoch millisecond.
166    #[inline]
167    pub fn new<T, P>(topic: T, payload: P) -> Self
168    where
169        T: Into<String>,
170        P: Into<Vec<u8>>,
171    {
172        Self {
173            id: 0,
174            topic: topic.into(),
175            key: None,
176            payload: payload.into(),
177            headers: HashMap::new(),
178            attempts: 0,
179            max_retries: 0,
180            created_at_ms: now_epoch_ms(),
181            expires_at_ms: None,
182        }
183    }
184
185    /// Sets an optional routing or partitioning key.
186    ///
187    /// # Arguments
188    ///
189    /// - `K` - Routing key convertible into `String`.
190    ///
191    /// # Returns
192    ///
193    /// - `Self` - Updated message.
194    pub fn with_key<K>(mut self, key: K) -> Self
195    where
196        K: Into<String>,
197    {
198        self.set_key(Some(key.into()));
199        self
200    }
201
202    /// Inserts a metadata header key-value pair on this message.
203    ///
204    /// # Arguments
205    ///
206    /// - `K` - Header key convertible into `String`.
207    /// - `V` - Header value convertible into `String`.
208    ///
209    /// # Returns
210    ///
211    /// - `Self` - Updated message.
212    pub fn with_header<K, V>(mut self, key: K, value: V) -> Self
213    where
214        K: Into<String>,
215        V: Into<String>,
216    {
217        self.get_mut_headers().insert(key.into(), value.into());
218        self
219    }
220
221    /// Configures a relative time-to-live in milliseconds from creation time.
222    ///
223    /// # Arguments
224    ///
225    /// - `u64` - TTL in milliseconds.
226    ///
227    /// # Returns
228    ///
229    /// - `Self` - Updated message with `expires_at_ms` set.
230    pub fn with_ttl_ms(mut self, ttl_ms: u64) -> Self {
231        let base: u64 = self.get_created_at_ms();
232        self.set_expires_at_ms(Some(base.saturating_add(ttl_ms)));
233        self
234    }
235
236    /// Overrides the maximum delivery attempts before dead-lettering.
237    ///
238    /// # Arguments
239    ///
240    /// - `u32` - Maximum attempts allowed for this message.
241    ///
242    /// # Returns
243    ///
244    /// - `Self` - Updated message.
245    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
246        self.set_max_retries(max_retries);
247        self
248    }
249}
250
251/// Inherent helpers for [`QueuedMessage`].
252impl QueuedMessage {
253    /// Borrows the underlying [`MqMessage`] regardless of ownership mode.
254    ///
255    /// # Returns
256    ///
257    /// - `&MqMessage` - Borrowed message reference.
258    #[inline(always)]
259    pub(crate) fn as_msg(&self) -> &MqMessage {
260        match self {
261            Self::Owned(msg) => msg,
262            Self::Shared(arc) => arc.as_ref(),
263        }
264    }
265
266    /// Consumes this handle into an owned [`MqMessage`] stamped with `attempts`.
267    ///
268    /// # Arguments
269    ///
270    /// - `u32` - Delivery attempt count to stamp on the returned message.
271    ///
272    /// # Returns
273    ///
274    /// - `MqMessage` - Owned message with updated attempt counter.
275    #[inline]
276    pub(crate) fn into_owned_with_attempts(self, attempts: u32) -> MqMessage {
277        let mut msg: MqMessage = match self {
278            Self::Owned(owned) => owned,
279            Self::Shared(arc) => {
280                Arc::try_unwrap(arc).unwrap_or_else(|shared: Arc<MqMessage>| (*shared).clone())
281            }
282        };
283        msg.set_attempts(attempts);
284        msg
285    }
286}
287
288/// Inherent helpers for [`TopicBrokerState`].
289impl TopicBrokerState {
290    /// Returns the dense slot index for `group`, creating a new [`GroupState`] if absent.
291    ///
292    /// # Arguments
293    ///
294    /// - `&str` - Consumer group name.
295    ///
296    /// # Returns
297    ///
298    /// - `usize` - Dense slot index in `self.groups`.
299    #[inline]
300    pub(crate) fn ensure_group_slot(&mut self, group: &str) -> usize {
301        let Self {
302            group_index,
303            groups,
304            ..
305        } = self;
306        if let Some(&idx) = group_index.get(group) {
307            return idx;
308        }
309        let idx: usize = groups.len();
310        groups.push(GroupState {
311            name: group.to_owned(),
312            queue: VecDeque::new(),
313            in_flight_count: 0,
314            acked_total: 0,
315        });
316        group_index.insert(group.to_owned(), idx);
317        idx
318    }
319
320    /// Reports whether zero deliveries are currently in flight for this topic.
321    ///
322    /// # Returns
323    ///
324    /// - `bool` - `true` when both the inline slot and overflow map are empty.
325    #[inline(always)]
326    pub(crate) fn is_in_flight_empty(&self) -> bool {
327        let Self {
328            fast_in_flight,
329            in_flight,
330            ..
331        } = self;
332        fast_in_flight.is_none() && in_flight.is_empty()
333    }
334
335    /// Returns the total number of active in-flight deliveries for this topic.
336    ///
337    /// # Returns
338    ///
339    /// - `usize` - Active in-flight delivery count.
340    #[inline(always)]
341    pub(crate) fn total_in_flight(&self) -> usize {
342        let Self {
343            fast_in_flight,
344            in_flight,
345            ..
346        } = self;
347        in_flight.len() + usize::from(fast_in_flight.is_some())
348    }
349
350    /// Inserts an active in-flight delivery, using the inline slot when no other leases exist.
351    ///
352    /// # Arguments
353    ///
354    /// - `u64` - Unique receipt identifier.
355    /// - `InFlightEntry` - Leased message state.
356    #[inline(always)]
357    pub(crate) fn insert_in_flight(&mut self, receipt_id: u64, entry: InFlightEntry) {
358        let Self {
359            fast_in_flight,
360            in_flight,
361            ..
362        } = self;
363        if fast_in_flight.is_none() && in_flight.is_empty() {
364            *fast_in_flight = Some((receipt_id, entry));
365        } else {
366            in_flight.insert(receipt_id, entry);
367        }
368    }
369
370    /// Removes and returns the in-flight delivery matching `receipt_id`, checking the inline slot first.
371    ///
372    /// # Arguments
373    ///
374    /// - `u64` - Receipt identifier to remove.
375    ///
376    /// # Returns
377    ///
378    /// - `Option<InFlightEntry>` - Removed entry if present.
379    #[inline(always)]
380    pub(crate) fn remove_in_flight(&mut self, receipt_id: u64) -> Option<InFlightEntry> {
381        let Self {
382            fast_in_flight,
383            in_flight,
384            ..
385        } = self;
386        if let Some((rid, _)) = fast_in_flight
387            && *rid == receipt_id
388        {
389            return fast_in_flight.take().map(|(_, e): (u64, InFlightEntry)| e);
390        }
391        in_flight.remove(&receipt_id)
392    }
393}
394
395/// Inherent implementation of [`InMemoryBroker`].
396impl InMemoryBroker {
397    /// Creates a new 64-shard [`InMemoryBroker`] governed by `config`.
398    ///
399    /// # Arguments
400    ///
401    /// - `MqConfig` - Queue capacity, retry, and visibility timeout settings.
402    ///
403    /// # Returns
404    ///
405    /// - `Self` - Ready in-memory message broker.
406    pub fn new(config: MqConfig) -> Self {
407        let topic_shards: Box<[TopicShard; MQ_SHARD_COUNT]> =
408            Box::new(from_fn(|_: usize| TopicShard {
409                map: RwLock::new(FnvHashMap::with_hasher(BuildHasherDefault::default())),
410            }));
411        let fast_topics: Box<[OnceLock<Arc<TopicBroker>>; MQ_FAST_TOPIC_SLOTS]> =
412            Box::new(from_fn(|_: usize| OnceLock::new()));
413        Self {
414            inner: Arc::new(InMemoryBrokerInner {
415                config,
416                start_instant: Instant::now(),
417                next_msg_id: AtomicU64::new(1),
418                next_receipt_seq: AtomicU64::new(1),
419                next_topic_id: AtomicU32::new(0),
420                topic_shards,
421                fast_topics,
422                overflow_topics: RwLock::new(Vec::new()),
423            }),
424        }
425    }
426
427    /// Returns a reference to this broker's [`MqConfig`].
428    ///
429    /// # Returns
430    ///
431    /// - `&MqConfig` - Active broker configuration.
432    #[inline(always)]
433    pub fn get_config(&self) -> &MqConfig {
434        let Self { inner } = self;
435        &inner.config
436    }
437
438    /// Returns monotonic elapsed milliseconds since broker creation for visibility timeouts.
439    ///
440    /// # Returns
441    ///
442    /// - `u64` - Monotonic elapsed milliseconds.
443    #[inline(always)]
444    fn monotonic_now_ms(&self) -> u64 {
445        let Self { inner } = self;
446        inner.start_instant.elapsed().as_millis() as u64
447    }
448
449    /// Looks up an existing [`TopicBroker`] for `topic` via read-fast sharding.
450    ///
451    /// # Arguments
452    ///
453    /// - `&str` - Topic name.
454    ///
455    /// # Returns
456    ///
457    /// - `Option<Arc<TopicBroker>>` - Shared topic broker, if present.
458    #[inline]
459    fn get_topic(&self, topic: &str) -> Option<Arc<TopicBroker>> {
460        let Self { inner } = self;
461        let idx: usize = mq_topic_shard_index(topic);
462        inner.topic_shards[idx].map.read().ok().and_then(
463            |map: RwLockReadGuard<'_, FnvHashMap<String, Arc<TopicBroker>>>| {
464                map.get(topic).cloned()
465            },
466        )
467    }
468
469    /// Borrows the owning [`TopicBroker`] from `fast_topics` without cloning `Arc`.
470    ///
471    /// # Arguments
472    ///
473    /// - `u64` - Packed delivery receipt identifier.
474    ///
475    /// # Returns
476    ///
477    /// - `Option<&TopicBroker>` - Borrowed owning topic broker when in the fast table.
478    #[inline(always)]
479    fn get_fast_topic_ref(&self, receipt_id: u64) -> Option<&TopicBroker> {
480        let Self { inner } = self;
481        let topic_id: usize = decode_receipt_topic_id(receipt_id);
482        if topic_id < MQ_FAST_TOPIC_SLOTS {
483            return inner.fast_topics[topic_id].get().map(Arc::as_ref);
484        }
485        None
486    }
487
488    /// Looks up an overflow [`TopicBroker`] for `receipt_id` when `topic_id >= MQ_FAST_TOPIC_SLOTS`.
489    ///
490    /// # Arguments
491    ///
492    /// - `u64` - Packed delivery receipt identifier.
493    ///
494    /// # Returns
495    ///
496    /// - `Option<Arc<TopicBroker>>` - Owning overflow topic broker, if present.
497    #[cold]
498    fn get_overflow_topic_by_receipt(&self, receipt_id: u64) -> Option<Arc<TopicBroker>> {
499        let Self { inner } = self;
500        let topic_id: usize = decode_receipt_topic_id(receipt_id);
501        if topic_id < MQ_FAST_TOPIC_SLOTS {
502            return None;
503        }
504        let overflow_idx: usize = topic_id - MQ_FAST_TOPIC_SLOTS;
505        inner.overflow_topics.read().ok().and_then(
506            |vec: RwLockReadGuard<'_, Vec<Arc<TopicBroker>>>| vec.get(overflow_idx).cloned(),
507        )
508    }
509
510    /// Looks up or inserts the [`TopicBroker`] for `topic` via read-fast sharding.
511    ///
512    /// # Arguments
513    ///
514    /// - `&str` - Topic name.
515    ///
516    /// # Returns
517    ///
518    /// - `Result<Arc<TopicBroker>, MqError>` - Shared topic broker or [`MqError::BrokerClosed`].
519    fn get_or_create_topic(&self, topic: &str) -> Result<Arc<TopicBroker>, MqError> {
520        if let Some(existing) = self.get_topic(topic) {
521            return Ok(existing);
522        }
523        let Self { inner } = self;
524        let idx: usize = mq_topic_shard_index(topic);
525        let Ok(mut write_map) = inner.topic_shards[idx].map.write() else {
526            return Err(MqError::BrokerClosed);
527        };
528        if let Some(existing) = write_map.get(topic) {
529            return Ok(Arc::clone(existing));
530        }
531        let topic_id: u32 = inner.next_topic_id.fetch_add(1, Ordering::Relaxed);
532        let created: Arc<TopicBroker> = Arc::new(TopicBroker {
533            topic: topic.to_owned(),
534            topic_id,
535            published_total: AtomicU64::new(0),
536            state: Mutex::new(TopicBrokerState {
537                group_index: FnvHashMap::with_hasher(BuildHasherDefault::default()),
538                groups: Vec::new(),
539                explicit_groups: Vec::new(),
540                default_group_idx: MQ_GROUP_UNSET,
541                fast_in_flight: None,
542                in_flight: FnvHashMap::with_hasher(BuildHasherDefault::default()),
543                deadlines: VecDeque::new(),
544                dlq: VecDeque::new(),
545            }),
546        });
547        let slot: usize = topic_id as usize;
548        if slot < MQ_FAST_TOPIC_SLOTS {
549            let _: Result<(), Arc<TopicBroker>> = inner.fast_topics[slot].set(Arc::clone(&created));
550        } else if let Ok(mut overflow) = inner.overflow_topics.write() {
551            let overflow_idx: usize = slot - MQ_FAST_TOPIC_SLOTS;
552            if overflow.len() <= overflow_idx {
553                overflow.resize(overflow_idx + 1, Arc::clone(&created));
554            } else {
555                overflow[overflow_idx] = Arc::clone(&created);
556            }
557        }
558        write_map.insert(topic.to_owned(), Arc::clone(&created));
559        Ok(created)
560    }
561
562    /// Prunes settled entries from the front of the monotonic deadline queue with zero map probes on FIFO acks.
563    ///
564    /// # Arguments
565    ///
566    /// - `&mut TopicBrokerState` - Locked per-topic broker state.
567    /// - `u64` - Receipt identifier that was just acknowledged or nacked.
568    #[inline(always)]
569    fn prune_settled_deadlines(state: &mut TopicBrokerState, settled_receipt_id: u64) {
570        if state.is_in_flight_empty() {
571            if !state.deadlines.is_empty() {
572                state.deadlines.clear();
573            }
574            return;
575        }
576        if let Some(&(_, front_rid)) = state.deadlines.front()
577            && front_rid == settled_receipt_id
578        {
579            let _: Option<(u64, u64)> = state.deadlines.pop_front();
580        }
581        let max_slack: usize = state.total_in_flight().saturating_mul(2).saturating_add(64);
582        if state.deadlines.len() > max_slack {
583            let TopicBrokerState {
584                fast_in_flight,
585                in_flight,
586                deadlines,
587                ..
588            } = state;
589            let fast_rid: Option<u64> = fast_in_flight
590                .as_ref()
591                .map(|&(rid, _): &(u64, InFlightEntry)| rid);
592            deadlines.retain(|&(_, rid): &(u64, u64)| {
593                fast_rid == Some(rid) || in_flight.contains_key(&rid)
594            });
595        }
596    }
597
598    /// Reclaims expired in-flight leases for one topic in `O(k)` via its monotonic FIFO deadline queue.
599    ///
600    /// # Arguments
601    ///
602    /// - `&mut TopicBrokerState` - Locked per-topic broker state.
603    /// - `&MqConfig` - Broker configuration.
604    /// - `u64` - Current monotonic timestamp in milliseconds.
605    #[inline]
606    fn reclaim_expired_topic_leases(
607        state: &mut TopicBrokerState,
608        config: &MqConfig,
609        now_mono_ms: u64,
610    ) {
611        if state.is_in_flight_empty() {
612            if !state.deadlines.is_empty() {
613                state.deadlines.clear();
614            }
615            return;
616        }
617        let mut epoch_cache: Option<u64> = None;
618        while let Some(&(deadline, receipt_id)) = state.deadlines.front() {
619            if deadline > now_mono_ms {
620                break;
621            }
622            let _: Option<(u64, u64)> = state.deadlines.pop_front();
623            let Some(entry) = state.remove_in_flight(receipt_id) else {
624                continue;
625            };
626            let group_state: &mut GroupState = &mut state.groups[entry.group_idx];
627            group_state.in_flight_count = group_state.in_flight_count.saturating_sub(1);
628            let msg_ref: &MqMessage = entry.message.as_msg();
629            if msg_ref.get_expires_at_ms().is_some() {
630                let now_epoch: u64 = *epoch_cache.get_or_insert_with(now_epoch_ms);
631                if is_message_expired(msg_ref, now_epoch) {
632                    continue;
633                }
634            }
635            let max_attempts: u32 = if msg_ref.get_max_retries() > 0 {
636                msg_ref.get_max_retries()
637            } else {
638                config.get_default_max_retries().max(1)
639            };
640            let owned_msg: MqMessage = entry.message.into_owned_with_attempts(entry.attempts);
641            if entry.attempts >= max_attempts {
642                state.dlq.push_back(owned_msg);
643            } else {
644                group_state
645                    .queue
646                    .push_front(QueuedMessage::Owned(owned_msg));
647            }
648        }
649    }
650
651    /// Resolves `group`'s dense slot index with zero-hash fast paths for [`DEFAULT_MQ_GROUP`] and small group sets.
652    ///
653    /// # Arguments
654    ///
655    /// - `&TopicBrokerState` - Locked topic state.
656    /// - `&str` - Consumer group name.
657    ///
658    /// # Returns
659    ///
660    /// - `Option<usize>` - Dense group slot index if registered.
661    #[inline(always)]
662    fn lookup_group_slot(state: &TopicBrokerState, group: &str) -> Option<usize> {
663        if group == DEFAULT_MQ_GROUP && state.default_group_idx != MQ_GROUP_UNSET {
664            return Some(state.default_group_idx);
665        }
666        if state.groups.len() <= 8 {
667            return state
668                .groups
669                .iter()
670                .position(|gs: &GroupState| gs.name == group);
671        }
672        state.group_index.get(group).copied()
673    }
674
675    /// Executes synchronous subscribe-group registration.
676    ///
677    /// # Arguments
678    ///
679    /// - `&str` - Topic name.
680    /// - `&str` - Consumer group name.
681    ///
682    /// # Returns
683    ///
684    /// - `Result<(), MqError>` - Registration result.
685    #[inline]
686    fn subscribe_group_sync(&self, topic: &str, group: &str) -> Result<(), MqError> {
687        let topic_broker: Arc<TopicBroker> = self.get_or_create_topic(topic)?;
688        let Ok(mut state) = topic_broker.state.lock() else {
689            return Err(MqError::BrokerClosed);
690        };
691        let slot: usize = state.ensure_group_slot(group);
692        if !state.explicit_groups.contains(&slot) {
693            state.explicit_groups.push(slot);
694        }
695        Ok(())
696    }
697
698    /// Enqueues `message` into an already-resolved [`TopicBroker`] under its per-topic lock.
699    ///
700    /// # Arguments
701    ///
702    /// - `&TopicBroker` - Target topic broker.
703    /// - `MqMessage` - Message stamped with id and retry budget.
704    /// - `usize` - Maximum queue length per consumer group.
705    ///
706    /// # Returns
707    ///
708    /// - `Result<(), MqError>` - `Ok(())` or backpressure/lock error.
709    #[inline]
710    fn enqueue_on_topic(
711        topic_broker: &TopicBroker,
712        message: MqMessage,
713        max_len: usize,
714    ) -> Result<(), MqError> {
715        let Ok(mut state) = topic_broker.state.lock() else {
716            return Err(MqError::BrokerClosed);
717        };
718        if state.explicit_groups.is_empty() {
719            let slot: usize = if state.default_group_idx != MQ_GROUP_UNSET {
720                state.default_group_idx
721            } else {
722                let created: usize = state.ensure_group_slot(DEFAULT_MQ_GROUP);
723                state.default_group_idx = created;
724                created
725            };
726            let queue: &mut VecDeque<QueuedMessage> = &mut state.groups[slot].queue;
727            if queue.len() >= max_len {
728                return Err(MqError::QueueFull);
729            }
730            queue.push_back(QueuedMessage::Owned(message));
731        } else {
732            let group_count: usize = state.explicit_groups.len();
733            for &slot in &state.explicit_groups {
734                if state.groups[slot].queue.len() >= max_len {
735                    return Err(MqError::QueueFull);
736                }
737            }
738            if group_count == 1 {
739                let slot: usize = state.explicit_groups[0];
740                state.groups[slot]
741                    .queue
742                    .push_back(QueuedMessage::Owned(message));
743            } else {
744                let shared: Arc<MqMessage> = Arc::new(message);
745                let last_idx: usize = group_count - 1;
746                for i in 0..last_idx {
747                    let slot: usize = state.explicit_groups[i];
748                    state.groups[slot]
749                        .queue
750                        .push_back(QueuedMessage::Shared(Arc::clone(&shared)));
751                }
752                let last_slot: usize = state.explicit_groups[last_idx];
753                state.groups[last_slot]
754                    .queue
755                    .push_back(QueuedMessage::Shared(shared));
756            }
757        }
758        topic_broker.published_total.fetch_add(1, Ordering::Relaxed);
759        Ok(())
760    }
761
762    /// Executes synchronous message publish with zero-`Arc`-clone fast path on existing topics.
763    ///
764    /// # Arguments
765    ///
766    /// - `MqMessage` - Message to publish.
767    ///
768    /// # Returns
769    ///
770    /// - `Result<u64, MqError>` - Assigned message identifier or error.
771    #[inline]
772    fn publish_sync(&self, mut message: MqMessage) -> Result<u64, MqError> {
773        let Self { inner } = self;
774        if let Some(deadline) = message.get_expires_at_ms()
775            && now_epoch_ms() >= deadline
776        {
777            return Err(MqError::MessageExpired);
778        }
779        let id: u64 = inner.next_msg_id.fetch_add(1, Ordering::Relaxed);
780        message.set_id(id);
781        if message.get_max_retries() == 0 {
782            message.set_max_retries(inner.config.get_default_max_retries().max(1));
783        }
784        let max_len: usize = inner.config.get_max_queue_len();
785        if let Some(primary) = inner.fast_topics[0].get()
786            && primary.topic == *message.get_topic()
787        {
788            Self::enqueue_on_topic(primary, message, max_len)?;
789            return Ok(id);
790        }
791        let shard_idx: usize = mq_topic_shard_index(message.get_topic());
792        if let Ok(read_map) = inner.topic_shards[shard_idx].map.read()
793            && let Some(topic_broker) = read_map.get(message.get_topic())
794        {
795            Self::enqueue_on_topic(topic_broker, message, max_len)?;
796            return Ok(id);
797        }
798        let topic_broker: Arc<TopicBroker> = self.get_or_create_topic(message.get_topic())?;
799        Self::enqueue_on_topic(&topic_broker, message, max_len)?;
800        Ok(id)
801    }
802
803    /// Leases the next ready message from an already-resolved [`TopicBroker`].
804    ///
805    /// # Arguments
806    ///
807    /// - `&TopicBroker` - Owning topic broker.
808    /// - `&str` - Consumer group name.
809    ///
810    /// # Returns
811    ///
812    /// - `Result<Option<MqDelivery>, MqError>` - Leased delivery or `None` when empty.
813    #[inline]
814    fn consume_from_topic(
815        &self,
816        topic_broker: &TopicBroker,
817        group: &str,
818    ) -> Result<Option<MqDelivery>, MqError> {
819        let Self { inner } = self;
820        let Ok(mut state) = topic_broker.state.lock() else {
821            return Err(MqError::BrokerClosed);
822        };
823        let mut mono_cache: Option<u64> = None;
824        if !state.deadlines.is_empty() {
825            let now_mono: u64 = *mono_cache.get_or_insert_with(|| self.monotonic_now_ms());
826            Self::reclaim_expired_topic_leases(&mut state, &inner.config, now_mono);
827        }
828        let Some(group_idx) = Self::lookup_group_slot(&state, group) else {
829            return Ok(None);
830        };
831        let mut epoch_cache: Option<u64> = None;
832        let mut next_msg: Option<QueuedMessage> = None;
833        let queue: &mut VecDeque<QueuedMessage> = &mut state.groups[group_idx].queue;
834        while let Some(candidate) = queue.pop_front() {
835            if let Some(deadline) = candidate.as_msg().get_expires_at_ms() {
836                let now_epoch: u64 = *epoch_cache.get_or_insert_with(now_epoch_ms);
837                if now_epoch >= deadline {
838                    continue;
839                }
840            }
841            next_msg = Some(candidate);
842            break;
843        }
844        let Some(queued) = next_msg else {
845            return Ok(None);
846        };
847        let next_attempts: u32 = queued.as_msg().get_attempts().saturating_add(1);
848        let (delivery_msg, stored_msg): (MqMessage, QueuedMessage) = match queued {
849            QueuedMessage::Owned(mut owned) => {
850                owned.set_attempts(next_attempts);
851                let delivery_copy: MqMessage = owned.clone();
852                (delivery_copy, QueuedMessage::Owned(owned))
853            }
854            QueuedMessage::Shared(arc) => {
855                let mut delivery_copy: MqMessage = (*arc).clone();
856                delivery_copy.set_attempts(next_attempts);
857                (delivery_copy, QueuedMessage::Shared(arc))
858            }
859        };
860        let now_mono: u64 = *mono_cache.get_or_insert_with(|| self.monotonic_now_ms());
861        let seq: u64 = inner.next_receipt_seq.fetch_add(1, Ordering::Relaxed);
862        let receipt_id: u64 = encode_receipt_id(topic_broker.topic_id, seq);
863        let visible_after_ms: u64 =
864            now_mono.saturating_add(inner.config.get_visibility_timeout_ms());
865        state.groups[group_idx].in_flight_count += 1;
866        state.insert_in_flight(
867            receipt_id,
868            InFlightEntry {
869                group_idx,
870                attempts: next_attempts,
871                message: stored_msg,
872            },
873        );
874        state.deadlines.push_back((visible_after_ms, receipt_id));
875        Ok(Some(MqDelivery {
876            message: delivery_msg,
877            receipt_id,
878            group: group.to_owned(),
879        }))
880    }
881
882    /// Executes synchronous message lease without `Arc::clone` or secondary receipt shard locking.
883    ///
884    /// # Arguments
885    ///
886    /// - `&str` - Topic name.
887    /// - `&str` - Consumer group name.
888    ///
889    /// # Returns
890    ///
891    /// - `Result<Option<MqDelivery>, MqError>` - Leased delivery or `None` when empty.
892    #[inline]
893    fn consume_sync(&self, topic: &str, group: &str) -> Result<Option<MqDelivery>, MqError> {
894        let Self { inner } = self;
895        if let Some(primary) = inner.fast_topics[0].get()
896            && primary.topic == topic
897        {
898            return self.consume_from_topic(primary, group);
899        }
900        let shard_idx: usize = mq_topic_shard_index(topic);
901        let Ok(read_map) = inner.topic_shards[shard_idx].map.read() else {
902            return Err(MqError::BrokerClosed);
903        };
904        let Some(topic_broker) = read_map.get(topic) else {
905            return Ok(None);
906        };
907        self.consume_from_topic(topic_broker, group)
908    }
909
910    /// Executes synchronous delivery acknowledgement with zero-`Arc`-clone lock-free topic routing.
911    ///
912    /// # Arguments
913    ///
914    /// - `u64` - Delivery receipt identifier.
915    ///
916    /// # Returns
917    ///
918    /// - `Result<(), MqError>` - `Ok(())` or [`MqError::UnknownDelivery`].
919    #[inline]
920    fn ack_sync(&self, receipt_id: u64) -> Result<(), MqError> {
921        let overflow_holder: Option<Arc<TopicBroker>>;
922        let topic_broker: &TopicBroker = if let Some(fast) = self.get_fast_topic_ref(receipt_id) {
923            fast
924        } else {
925            overflow_holder = self.get_overflow_topic_by_receipt(receipt_id);
926            let Some(ref owned) = overflow_holder else {
927                return Err(MqError::UnknownDelivery);
928            };
929            owned.as_ref()
930        };
931        let Ok(mut state) = topic_broker.state.lock() else {
932            return Err(MqError::BrokerClosed);
933        };
934        let Some(entry) = state.remove_in_flight(receipt_id) else {
935            return Err(MqError::UnknownDelivery);
936        };
937        let group_state: &mut GroupState = &mut state.groups[entry.group_idx];
938        group_state.in_flight_count = group_state.in_flight_count.saturating_sub(1);
939        group_state.acked_total = group_state.acked_total.saturating_add(1);
940        Self::prune_settled_deadlines(&mut state, receipt_id);
941        Ok(())
942    }
943
944    /// Executes synchronous negative acknowledgement with zero-`Arc`-clone O(1) requeue or DLQ routing.
945    ///
946    /// # Arguments
947    ///
948    /// - `u64` - Delivery receipt identifier.
949    /// - `bool` - `true` to requeue when retries remain, `false` to dead-letter immediately.
950    ///
951    /// # Returns
952    ///
953    /// - `Result<(), MqError>` - `Ok(())` or [`MqError::UnknownDelivery`].
954    #[inline]
955    fn nack_sync(&self, receipt_id: u64, requeue: bool) -> Result<(), MqError> {
956        let Self { inner } = self;
957        let overflow_holder: Option<Arc<TopicBroker>>;
958        let topic_broker: &TopicBroker = if let Some(fast) = self.get_fast_topic_ref(receipt_id) {
959            fast
960        } else {
961            overflow_holder = self.get_overflow_topic_by_receipt(receipt_id);
962            let Some(ref owned) = overflow_holder else {
963                return Err(MqError::UnknownDelivery);
964            };
965            owned.as_ref()
966        };
967        let Ok(mut state) = topic_broker.state.lock() else {
968            return Err(MqError::BrokerClosed);
969        };
970        let Some(entry) = state.remove_in_flight(receipt_id) else {
971            return Err(MqError::UnknownDelivery);
972        };
973        state.groups[entry.group_idx].in_flight_count = state.groups[entry.group_idx]
974            .in_flight_count
975            .saturating_sub(1);
976        Self::prune_settled_deadlines(&mut state, receipt_id);
977        let msg_ref: &MqMessage = entry.message.as_msg();
978        if let Some(deadline) = msg_ref.get_expires_at_ms()
979            && now_epoch_ms() >= deadline
980        {
981            return Ok(());
982        }
983        let max_attempts: u32 = if msg_ref.get_max_retries() > 0 {
984            msg_ref.get_max_retries()
985        } else {
986            inner.config.get_default_max_retries().max(1)
987        };
988        let owned_msg: MqMessage = entry.message.into_owned_with_attempts(entry.attempts);
989        if requeue && entry.attempts < max_attempts {
990            state.groups[entry.group_idx]
991                .queue
992                .push_back(QueuedMessage::Owned(owned_msg));
993        } else {
994            state.dlq.push_back(owned_msg);
995        }
996        Ok(())
997    }
998
999    /// Executes synchronous point-in-time queue statistics collection in `O(1)`.
1000    ///
1001    /// # Arguments
1002    ///
1003    /// - `&str` - Topic name.
1004    /// - `&str` - Consumer group name.
1005    ///
1006    /// # Returns
1007    ///
1008    /// - `Result<MqStats, MqError>` - Current queue counters.
1009    #[inline]
1010    fn stats_sync(&self, topic: &str, group: &str) -> Result<MqStats, MqError> {
1011        let Self { inner } = self;
1012        let Some(topic_broker) = self.get_topic(topic) else {
1013            return Ok(MqStats::default());
1014        };
1015        let Ok(mut state) = topic_broker.state.lock() else {
1016            return Err(MqError::BrokerClosed);
1017        };
1018        if !state.deadlines.is_empty() {
1019            let now_mono: u64 = self.monotonic_now_ms();
1020            Self::reclaim_expired_topic_leases(&mut state, &inner.config, now_mono);
1021        }
1022        let (queued, in_flight, acked_total): (usize, usize, u64) =
1023            match Self::lookup_group_slot(&state, group) {
1024                Some(slot) => {
1025                    let gs: &GroupState = &state.groups[slot];
1026                    (gs.queue.len(), gs.in_flight_count, gs.acked_total)
1027                }
1028                None => (0, 0, 0),
1029            };
1030        let dead_lettered: usize = state.dlq.len();
1031        let published_total: u64 = topic_broker.published_total.load(Ordering::Relaxed);
1032        Ok(MqStats {
1033            queued,
1034            in_flight,
1035            dead_lettered,
1036            published_total,
1037            acked_total,
1038        })
1039    }
1040
1041    /// Drains and returns all dead-lettered messages currently buffered for `topic`.
1042    ///
1043    /// # Arguments
1044    ///
1045    /// - `&str` - Base topic name.
1046    ///
1047    /// # Returns
1048    ///
1049    /// - `Vec<MqMessage>` - All dead-lettered messages in FIFO order.
1050    pub fn drain_dlq(&self, topic: &str) -> Vec<MqMessage> {
1051        let Some(topic_broker) = self.get_topic(topic) else {
1052            return Vec::new();
1053        };
1054        let Ok(mut state) = topic_broker.state.lock() else {
1055            return Vec::new();
1056        };
1057        state.dlq.drain(..).collect()
1058    }
1059
1060    /// Returns the number of dead-lettered messages currently buffered for `topic`.
1061    ///
1062    /// # Arguments
1063    ///
1064    /// - `&str` - Base topic name.
1065    ///
1066    /// # Returns
1067    ///
1068    /// - `usize` - Count of messages waiting in the dead-letter queue.
1069    pub fn dlq_len(&self, topic: &str) -> usize {
1070        let Some(topic_broker) = self.get_topic(topic) else {
1071            return 0;
1072        };
1073        topic_broker
1074            .state
1075            .lock()
1076            .map(|state: MutexGuard<'_, TopicBrokerState>| state.dlq.len())
1077            .unwrap_or(0)
1078    }
1079
1080    /// Returns the canonical dead-letter topic name for `topic` using this broker's config.
1081    ///
1082    /// # Arguments
1083    ///
1084    /// - `&str` - Base topic name.
1085    ///
1086    /// # Returns
1087    ///
1088    /// - `String` - Configured dead-letter topic name.
1089    pub fn dlq_name(&self, topic: &str) -> String {
1090        dlq_topic_name(topic, self.get_config())
1091    }
1092}
1093
1094/// Default construction for [`InMemoryBroker`].
1095impl Default for InMemoryBroker {
1096    /// Constructs a default [`InMemoryBroker`] value.
1097    fn default() -> Self {
1098        Self::new(MqConfig::default())
1099    }
1100}
1101
1102/// Implements [`MessageBroker`] for [`InMemoryBroker`].
1103impl MessageBroker for InMemoryBroker {
1104    /// Implements the `subscribe_group` operation on [`InMemoryBroker`].
1105    ///
1106    /// # Arguments
1107    ///
1108    /// - `&'a self` - Shared reference to a `'a self`.
1109    /// - `&'a str` - Shared reference to a `'a str`.
1110    /// - `&'a str` - Shared reference to a `'a str`.
1111    ///
1112    /// # Returns
1113    ///
1114    /// - `BrokerFuture<'a, ()>` - A `BrokerFuture<'a, ()>` value.
1115    fn subscribe_group<'a>(&'a self, topic: &'a str, group: &'a str) -> BrokerFuture<'a, ()> {
1116        Box::pin(ready(self.subscribe_group_sync(topic, group)))
1117    }
1118
1119    /// Implements the `publish` operation on [`InMemoryBroker`].
1120    ///
1121    /// # Arguments
1122    ///
1123    /// - `MqMessage` - A `MqMessage` parameter.
1124    ///
1125    /// # Returns
1126    ///
1127    /// - `BrokerFuture<'_, u64>` - A `BrokerFuture<'_, u64>` value.
1128    fn publish(&self, message: MqMessage) -> BrokerFuture<'_, u64> {
1129        Box::pin(ready(self.publish_sync(message)))
1130    }
1131
1132    /// Implements the `consume` operation on [`InMemoryBroker`].
1133    ///
1134    /// # Arguments
1135    ///
1136    /// - `&'a self` - Shared reference to a `'a self`.
1137    /// - `&'a str` - Shared reference to a `'a str`.
1138    /// - `&'a str` - Shared reference to a `'a str`.
1139    ///
1140    /// # Returns
1141    ///
1142    /// - `BrokerFuture<'a, Option<MqDelivery>>` - A `BrokerFuture<'a, Option<MqDelivery>>` value.
1143    fn consume<'a>(
1144        &'a self,
1145        topic: &'a str,
1146        group: &'a str,
1147    ) -> BrokerFuture<'a, Option<MqDelivery>> {
1148        Box::pin(async move { self.consume_sync(topic, group) })
1149    }
1150
1151    /// Implements the `ack` operation on [`InMemoryBroker`].
1152    ///
1153    /// # Arguments
1154    ///
1155    /// - `u64` - A `u64` parameter.
1156    ///
1157    /// # Returns
1158    ///
1159    /// - `BrokerFuture<'_, ()>` - A `BrokerFuture<'_, ()>` value.
1160    fn ack(&self, receipt_id: u64) -> BrokerFuture<'_, ()> {
1161        Box::pin(ready(self.ack_sync(receipt_id)))
1162    }
1163
1164    /// Implements the `nack` operation on [`InMemoryBroker`].
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `u64` - A `u64` parameter.
1169    /// - `bool` - A boolean (`bool`).
1170    ///
1171    /// # Returns
1172    ///
1173    /// - `BrokerFuture<'_, ()>` - A `BrokerFuture<'_, ()>` value.
1174    fn nack(&self, receipt_id: u64, requeue: bool) -> BrokerFuture<'_, ()> {
1175        Box::pin(ready(self.nack_sync(receipt_id, requeue)))
1176    }
1177
1178    /// Implements the `stats` operation on [`InMemoryBroker`].
1179    ///
1180    /// # Arguments
1181    ///
1182    /// - `&'a self` - Shared reference to a `'a self`.
1183    /// - `&'a str` - Shared reference to a `'a str`.
1184    /// - `&'a str` - Shared reference to a `'a str`.
1185    ///
1186    /// # Returns
1187    ///
1188    /// - `BrokerFuture<'a, MqStats>` - A `BrokerFuture<'a, MqStats>` value.
1189    fn stats<'a>(&'a self, topic: &'a str, group: &'a str) -> BrokerFuture<'a, MqStats> {
1190        Box::pin(async move { self.stats_sync(topic, group) })
1191    }
1192}
1193
1194/// Inherent implementation of [`MqPlugin`].
1195impl MqPlugin {
1196    /// Initializes the global [`MqPlugin`] once with `config`.
1197    ///
1198    /// # Arguments
1199    ///
1200    /// - `MqConfig` - Message queue broker configuration.
1201    ///
1202    /// # Returns
1203    ///
1204    /// - `&'static Self` - Reference to the initialized global plugin instance.
1205    pub fn init(config: MqConfig) -> &'static Self {
1206        MQ_PLUGIN.get_or_init(|| Self {
1207            broker: InMemoryBroker::new(config.clone()),
1208            config,
1209            custom_broker: None,
1210        })
1211    }
1212
1213    /// Initializes the global [`MqPlugin`] once with a custom pluggable [`MessageBroker`] backend.
1214    ///
1215    /// # Arguments
1216    ///
1217    /// - `MqConfig` - Message queue broker configuration.
1218    /// - `Arc<dyn MessageBroker>` - Custom message broker implementation.
1219    ///
1220    /// # Returns
1221    ///
1222    /// - `&'static Self` - Reference to the initialized global plugin instance.
1223    pub fn init_with_broker(config: MqConfig, broker: Arc<dyn MessageBroker>) -> &'static Self {
1224        MQ_PLUGIN.get_or_init(|| Self {
1225            broker: InMemoryBroker::new(config.clone()),
1226            config,
1227            custom_broker: Some(broker),
1228        })
1229    }
1230
1231    /// Returns the initialized global [`MqPlugin`], if [`MqPlugin::init`] was called.
1232    ///
1233    /// # Returns
1234    ///
1235    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1236    #[inline(always)]
1237    pub fn get() -> Option<&'static Self> {
1238        MQ_PLUGIN.get()
1239    }
1240
1241    /// Returns the plugin's [`MqConfig`].
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `&MqConfig` - Active configuration.
1246    #[inline(always)]
1247    pub fn get_config(&self) -> &MqConfig {
1248        let Self { config, .. } = self;
1249        config
1250    }
1251
1252    /// Returns the plugin's shared [`InMemoryBroker`].
1253    ///
1254    /// # Returns
1255    ///
1256    /// - `&InMemoryBroker` - Process-wide in-memory broker.
1257    #[inline(always)]
1258    pub fn get_broker(&self) -> &InMemoryBroker {
1259        let Self { broker, .. } = self;
1260        broker
1261    }
1262
1263    /// Returns the custom pluggable [`Arc<dyn MessageBroker>`] backend when installed via [`MqPlugin::init_with_broker`].
1264    ///
1265    /// # Returns
1266    ///
1267    /// - `Option<&Arc<dyn MessageBroker>>` - Active custom broker backend, or `None`.
1268    #[inline(always)]
1269    pub fn get_custom_broker(&self) -> Option<&Arc<dyn MessageBroker>> {
1270        let Self { custom_broker, .. } = self;
1271        custom_broker.as_ref()
1272    }
1273}