1use super::*;
2
3impl Hasher for FnvHasher {
5 #[inline(always)]
11 fn finish(&self) -> u64 {
12 let Self { state } = *self;
13 state
14 }
15
16 #[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 #[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 #[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
54impl Display for MqError {
56 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
76impl Error for MqError {}
78
79impl Default for MqConfig {
81 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
92impl MqConfig {
94 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 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 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 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
154impl MqMessage {
156 #[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 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 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 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 pub fn with_max_retries(mut self, max_retries: u32) -> Self {
246 self.set_max_retries(max_retries);
247 self
248 }
249}
250
251impl QueuedMessage {
253 #[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 #[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
288impl TopicBrokerState {
290 #[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 #[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 #[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 #[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 #[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
395impl InMemoryBroker {
397 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 #[inline(always)]
433 pub fn get_config(&self) -> &MqConfig {
434 let Self { inner } = self;
435 &inner.config
436 }
437
438 #[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 #[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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 pub fn dlq_name(&self, topic: &str) -> String {
1090 dlq_topic_name(topic, self.get_config())
1091 }
1092}
1093
1094impl Default for InMemoryBroker {
1096 fn default() -> Self {
1098 Self::new(MqConfig::default())
1099 }
1100}
1101
1102impl MessageBroker for InMemoryBroker {
1104 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 fn publish(&self, message: MqMessage) -> BrokerFuture<'_, u64> {
1129 Box::pin(ready(self.publish_sync(message)))
1130 }
1131
1132 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 fn ack(&self, receipt_id: u64) -> BrokerFuture<'_, ()> {
1161 Box::pin(ready(self.ack_sync(receipt_id)))
1162 }
1163
1164 fn nack(&self, receipt_id: u64, requeue: bool) -> BrokerFuture<'_, ()> {
1175 Box::pin(ready(self.nack_sync(receipt_id, requeue)))
1176 }
1177
1178 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
1194impl MqPlugin {
1196 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 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 #[inline(always)]
1237 pub fn get() -> Option<&'static Self> {
1238 MQ_PLUGIN.get()
1239 }
1240
1241 #[inline(always)]
1247 pub fn get_config(&self) -> &MqConfig {
1248 let Self { config, .. } = self;
1249 config
1250 }
1251
1252 #[inline(always)]
1258 pub fn get_broker(&self) -> &InMemoryBroker {
1259 let Self { broker, .. } = self;
1260 broker
1261 }
1262
1263 #[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}