Skip to main content

hyperlane_plugin_mq/
struct.rs

1use super::*;
2
3/// Fast zero-dependency word-at-a-time 64-bit hasher for internal broker tables.
4#[derive(Clone, Copy, Default)]
5pub(crate) struct FnvHasher {
6    /// Running 64-bit hash state.
7    pub(crate) state: u64,
8}
9
10/// Cache-line-aligned topic registry shard preventing cross-thread false sharing.
11#[repr(align(64))]
12pub(crate) struct TopicShard {
13    /// Per-shard read-write lock guarding topic brokers.
14    pub(crate) map: RwLock<FnvHashMap<String, Arc<TopicBroker>>>,
15}
16
17/// Configuration controlling queue bounds, visibility timeouts, retries, and DLQ naming.
18#[derive(Clone, Data, Debug, Eq, PartialEq)]
19pub struct MqConfig {
20    /// Maximum pending messages allowed per `(topic, group)` queue.
21    #[get(type(copy))]
22    pub(crate) max_queue_len: usize,
23    /// Visibility timeout in milliseconds before unacked in-flight messages redeliver.
24    #[get(type(copy))]
25    pub(crate) visibility_timeout_ms: u64,
26    /// Default retry budget per message before dead-lettering.
27    #[get(type(copy))]
28    pub(crate) default_max_retries: u32,
29    /// Suffix appended to a topic name when moving messages to its dead-letter queue.
30    pub(crate) dlq_suffix: String,
31}
32
33/// A message published to and consumed from a [`MessageBroker`].
34#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
35pub struct MqMessage {
36    /// Monotonic broker-assigned identifier (`0` before publish).
37    #[get(type(copy))]
38    pub(crate) id: u64,
39    /// Target topic name.
40    pub(crate) topic: String,
41    /// Optional routing or partitioning key.
42    #[get(type(clone))]
43    pub(crate) key: Option<String>,
44    /// Raw payload bytes.
45    pub(crate) payload: Vec<u8>,
46    /// Optional string metadata headers.
47    pub(crate) headers: HashMap<String, String>,
48    /// Delivery attempt counter incremented on each dispatch.
49    #[get(type(copy))]
50    pub(crate) attempts: u32,
51    /// Maximum attempts permitted before moving to DLQ (`0` inherits broker default).
52    #[get(type(copy))]
53    pub(crate) max_retries: u32,
54    /// Creation timestamp in Unix epoch milliseconds.
55    #[get(type(copy))]
56    pub(crate) created_at_ms: u64,
57    /// Optional expiration timestamp in Unix epoch milliseconds.
58    #[get(type(copy))]
59    pub(crate) expires_at_ms: Option<u64>,
60}
61
62/// Active delivery leased to a consumer until acknowledged, negatively acknowledged, or timed out.
63#[derive(Clone, Data, Debug, Eq, PartialEq)]
64pub struct MqDelivery {
65    /// Delivered message snapshot.
66    pub(crate) message: MqMessage,
67    /// Unique lease identifier required for [`MessageBroker::ack`] or [`MessageBroker::nack`].
68    #[get(type(copy))]
69    pub(crate) receipt_id: u64,
70    /// Consumer group that owns this lease.
71    pub(crate) group: String,
72}
73
74/// Point-in-time counters for one `(topic, group)` queue.
75#[derive(Clone, Copy, Data, Debug, Default, Eq, PartialEq)]
76pub struct MqStats {
77    /// Messages currently waiting in the ready queue.
78    #[get(type(copy))]
79    pub(crate) queued: usize,
80    /// Messages currently leased to consumers awaiting ack/nack.
81    #[get(type(copy))]
82    pub(crate) in_flight: usize,
83    /// Messages currently stored in the topic's dead-letter queue.
84    #[get(type(copy))]
85    pub(crate) dead_lettered: usize,
86    /// Cumulative messages published to the topic.
87    #[get(type(copy))]
88    pub(crate) published_total: u64,
89    /// Cumulative messages acknowledged across this group.
90    #[get(type(copy))]
91    pub(crate) acked_total: u64,
92}
93
94/// Per-consumer-group queue and counters indexed directly in [`TopicBrokerState::groups`].
95pub(crate) struct GroupState {
96    /// Consumer group name for fast small-group linear lookup without hashing.
97    pub(crate) name: String,
98    /// Ready FIFO message queue for this group.
99    pub(crate) queue: VecDeque<QueuedMessage>,
100    /// Number of currently leased in-flight messages for this group.
101    pub(crate) in_flight_count: usize,
102    /// Cumulative acknowledged messages for this group.
103    pub(crate) acked_total: u64,
104}
105
106/// One leased message waiting for ack or visibility timeout expiry.
107pub(crate) struct InFlightEntry {
108    /// Dense slot index into [`TopicBrokerState::groups`] (zero string allocation).
109    pub(crate) group_idx: usize,
110    /// Delivery attempt count recorded for this lease.
111    pub(crate) attempts: u32,
112    /// Leased message handle (zero-clone [`Arc`] when fanned out across multiple groups).
113    pub(crate) message: QueuedMessage,
114}
115
116/// Per-topic mutable state independently locked inside a [`TopicBroker`].
117pub(crate) struct TopicBrokerState {
118    /// Group name to dense slot index in `groups`.
119    pub(crate) group_index: FnvHashMap<String, usize>,
120    /// Dense per-group queue and counters for cache-friendly zero-alloc publish/ack/nack.
121    pub(crate) groups: Vec<GroupState>,
122    /// Dense slot indices of explicitly subscribed consumer groups.
123    pub(crate) explicit_groups: Vec<usize>,
124    /// Dense slot index of [`DEFAULT_MQ_GROUP`] used when `explicit_groups` is empty, or [`MQ_GROUP_UNSET`].
125    pub(crate) default_group_idx: usize,
126    /// Inline single-entry in-flight slot bypassing `in_flight` map probes when concurrency is one.
127    pub(crate) fast_in_flight: Option<(u64, InFlightEntry)>,
128    /// Active leased deliveries keyed by `receipt_id`.
129    pub(crate) in_flight: FnvHashMap<u64, InFlightEntry>,
130    /// Monotonic FIFO queue of `(visible_after_mono_ms, receipt_id)` for `O(1)` lease expiry and front-pruning.
131    pub(crate) deadlines: VecDeque<(u64, u64)>,
132    /// Dead-letter queue for this topic.
133    pub(crate) dlq: VecDeque<MqMessage>,
134}
135
136/// Independently locked broker slice owning one topic.
137pub(crate) struct TopicBroker {
138    /// Owned topic name enabling lock-free primary-topic matching without shard lookup.
139    pub(crate) topic: String,
140    /// Unique dense identifier encoded into the upper bits of every `receipt_id`.
141    pub(crate) topic_id: u32,
142    /// Cumulative messages published to this topic (lock-free).
143    pub(crate) published_total: AtomicU64,
144    /// Per-topic queues, in-flight leases, deadline queue, and DLQ.
145    pub(crate) state: Mutex<TopicBrokerState>,
146}
147
148/// Shared sharded interior state of [`InMemoryBroker`].
149pub(crate) struct InMemoryBrokerInner {
150    /// Broker configuration.
151    pub(crate) config: MqConfig,
152    /// Monotonic clock anchor for visibility-timeout calculations.
153    pub(crate) start_instant: Instant,
154    /// Monotonic message id counter.
155    pub(crate) next_msg_id: AtomicU64,
156    /// Monotonic per-receipt sequence counter.
157    pub(crate) next_receipt_seq: AtomicU64,
158    /// Monotonic dense topic identifier allocator.
159    pub(crate) next_topic_id: AtomicU32,
160    /// 64-way sharded topic table isolating contention per topic.
161    pub(crate) topic_shards: Box<[TopicShard; MQ_SHARD_COUNT]>,
162    /// Lock-free O(1) topic lookup table indexed by `topic_id` for `ack`/`nack`.
163    pub(crate) fast_topics: Box<[OnceLock<Arc<TopicBroker>>; MQ_FAST_TOPIC_SLOTS]>,
164    /// Overflow topic lookup vector for brokers exceeding [`MQ_FAST_TOPIC_SLOTS`] topics.
165    pub(crate) overflow_topics: RwLock<Vec<Arc<TopicBroker>>>,
166}
167
168/// Production-ready sharded high-concurrency in-memory [`MessageBroker`] implementation.
169#[derive(Clone)]
170pub struct InMemoryBroker {
171    /// Shared sharded broker state.
172    pub(crate) inner: Arc<InMemoryBrokerInner>,
173}
174
175/// Process-wide [`MqPlugin`] registry storing [`MqConfig`], an [`InMemoryBroker`], and an optional custom [`MessageBroker`].
176#[derive(Clone)]
177pub struct MqPlugin {
178    /// Active plugin configuration.
179    pub(crate) config: MqConfig,
180    /// Shared process-wide in-memory broker.
181    pub(crate) broker: InMemoryBroker,
182    /// Optional custom pluggable broker backend installed via [`MqPlugin::init_with_broker`].
183    pub(crate) custom_broker: Option<Arc<dyn MessageBroker>>,
184}