hyperlane-plugin-mq 23.1.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
use super::*;

/// Fast zero-dependency word-at-a-time 64-bit hasher for internal broker tables.
#[derive(Clone, Copy, Default)]
pub(crate) struct FnvHasher {
    /// Running 64-bit hash state.
    pub(crate) state: u64,
}

/// Cache-line-aligned topic registry shard preventing cross-thread false sharing.
#[repr(align(64))]
pub(crate) struct TopicShard {
    /// Per-shard read-write lock guarding topic brokers.
    pub(crate) map: RwLock<FnvHashMap<String, Arc<TopicBroker>>>,
}

/// Configuration controlling queue bounds, visibility timeouts, retries, and DLQ naming.
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct MqConfig {
    /// Maximum pending messages allowed per `(topic, group)` queue.
    #[get(type(copy))]
    pub(crate) max_queue_len: usize,
    /// Visibility timeout in milliseconds before unacked in-flight messages redeliver.
    #[get(type(copy))]
    pub(crate) visibility_timeout_ms: u64,
    /// Default retry budget per message before dead-lettering.
    #[get(type(copy))]
    pub(crate) default_max_retries: u32,
    /// Suffix appended to a topic name when moving messages to its dead-letter queue.
    pub(crate) dlq_suffix: String,
}

/// A message published to and consumed from a [`MessageBroker`].
#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
pub struct MqMessage {
    /// Monotonic broker-assigned identifier (`0` before publish).
    #[get(type(copy))]
    pub(crate) id: u64,
    /// Target topic name.
    pub(crate) topic: String,
    /// Optional routing or partitioning key.
    #[get(type(clone))]
    pub(crate) key: Option<String>,
    /// Raw payload bytes.
    pub(crate) payload: Vec<u8>,
    /// Optional string metadata headers.
    pub(crate) headers: HashMap<String, String>,
    /// Delivery attempt counter incremented on each dispatch.
    #[get(type(copy))]
    pub(crate) attempts: u32,
    /// Maximum attempts permitted before moving to DLQ (`0` inherits broker default).
    #[get(type(copy))]
    pub(crate) max_retries: u32,
    /// Creation timestamp in Unix epoch milliseconds.
    #[get(type(copy))]
    pub(crate) created_at_ms: u64,
    /// Optional expiration timestamp in Unix epoch milliseconds.
    #[get(type(copy))]
    pub(crate) expires_at_ms: Option<u64>,
}

/// Active delivery leased to a consumer until acknowledged, negatively acknowledged, or timed out.
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct MqDelivery {
    /// Delivered message snapshot.
    pub(crate) message: MqMessage,
    /// Unique lease identifier required for [`MessageBroker::ack`] or [`MessageBroker::nack`].
    #[get(type(copy))]
    pub(crate) receipt_id: u64,
    /// Consumer group that owns this lease.
    pub(crate) group: String,
}

/// Point-in-time counters for one `(topic, group)` queue.
#[derive(Clone, Copy, Data, Debug, Default, Eq, PartialEq)]
pub struct MqStats {
    /// Messages currently waiting in the ready queue.
    #[get(type(copy))]
    pub(crate) queued: usize,
    /// Messages currently leased to consumers awaiting ack/nack.
    #[get(type(copy))]
    pub(crate) in_flight: usize,
    /// Messages currently stored in the topic's dead-letter queue.
    #[get(type(copy))]
    pub(crate) dead_lettered: usize,
    /// Cumulative messages published to the topic.
    #[get(type(copy))]
    pub(crate) published_total: u64,
    /// Cumulative messages acknowledged across this group.
    #[get(type(copy))]
    pub(crate) acked_total: u64,
}

/// Per-consumer-group queue and counters indexed directly in [`TopicBrokerState::groups`].
pub(crate) struct GroupState {
    /// Consumer group name for fast small-group linear lookup without hashing.
    pub(crate) name: String,
    /// Ready FIFO message queue for this group.
    pub(crate) queue: VecDeque<QueuedMessage>,
    /// Number of currently leased in-flight messages for this group.
    pub(crate) in_flight_count: usize,
    /// Cumulative acknowledged messages for this group.
    pub(crate) acked_total: u64,
}

/// One leased message waiting for ack or visibility timeout expiry.
pub(crate) struct InFlightEntry {
    /// Dense slot index into [`TopicBrokerState::groups`] (zero string allocation).
    pub(crate) group_idx: usize,
    /// Delivery attempt count recorded for this lease.
    pub(crate) attempts: u32,
    /// Leased message handle (zero-clone [`Arc`] when fanned out across multiple groups).
    pub(crate) message: QueuedMessage,
}

/// Per-topic mutable state independently locked inside a [`TopicBroker`].
pub(crate) struct TopicBrokerState {
    /// Group name to dense slot index in `groups`.
    pub(crate) group_index: FnvHashMap<String, usize>,
    /// Dense per-group queue and counters for cache-friendly zero-alloc publish/ack/nack.
    pub(crate) groups: Vec<GroupState>,
    /// Dense slot indices of explicitly subscribed consumer groups.
    pub(crate) explicit_groups: Vec<usize>,
    /// Dense slot index of [`DEFAULT_MQ_GROUP`] used when `explicit_groups` is empty, or [`MQ_GROUP_UNSET`].
    pub(crate) default_group_idx: usize,
    /// Inline single-entry in-flight slot bypassing `in_flight` map probes when concurrency is one.
    pub(crate) fast_in_flight: Option<(u64, InFlightEntry)>,
    /// Active leased deliveries keyed by `receipt_id`.
    pub(crate) in_flight: FnvHashMap<u64, InFlightEntry>,
    /// Monotonic FIFO queue of `(visible_after_mono_ms, receipt_id)` for `O(1)` lease expiry and front-pruning.
    pub(crate) deadlines: VecDeque<(u64, u64)>,
    /// Dead-letter queue for this topic.
    pub(crate) dlq: VecDeque<MqMessage>,
}

/// Independently locked broker slice owning one topic.
pub(crate) struct TopicBroker {
    /// Owned topic name enabling lock-free primary-topic matching without shard lookup.
    pub(crate) topic: String,
    /// Unique dense identifier encoded into the upper bits of every `receipt_id`.
    pub(crate) topic_id: u32,
    /// Cumulative messages published to this topic (lock-free).
    pub(crate) published_total: AtomicU64,
    /// Per-topic queues, in-flight leases, deadline queue, and DLQ.
    pub(crate) state: Mutex<TopicBrokerState>,
}

/// Shared sharded interior state of [`InMemoryBroker`].
pub(crate) struct InMemoryBrokerInner {
    /// Broker configuration.
    pub(crate) config: MqConfig,
    /// Monotonic clock anchor for visibility-timeout calculations.
    pub(crate) start_instant: Instant,
    /// Monotonic message id counter.
    pub(crate) next_msg_id: AtomicU64,
    /// Monotonic per-receipt sequence counter.
    pub(crate) next_receipt_seq: AtomicU64,
    /// Monotonic dense topic identifier allocator.
    pub(crate) next_topic_id: AtomicU32,
    /// 64-way sharded topic table isolating contention per topic.
    pub(crate) topic_shards: Box<[TopicShard; MQ_SHARD_COUNT]>,
    /// Lock-free O(1) topic lookup table indexed by `topic_id` for `ack`/`nack`.
    pub(crate) fast_topics: Box<[OnceLock<Arc<TopicBroker>>; MQ_FAST_TOPIC_SLOTS]>,
    /// Overflow topic lookup vector for brokers exceeding [`MQ_FAST_TOPIC_SLOTS`] topics.
    pub(crate) overflow_topics: RwLock<Vec<Arc<TopicBroker>>>,
}

/// Production-ready sharded high-concurrency in-memory [`MessageBroker`] implementation.
#[derive(Clone)]
pub struct InMemoryBroker {
    /// Shared sharded broker state.
    pub(crate) inner: Arc<InMemoryBrokerInner>,
}

/// Process-wide [`MqPlugin`] registry storing [`MqConfig`], an [`InMemoryBroker`], and an optional custom [`MessageBroker`].
#[derive(Clone)]
pub struct MqPlugin {
    /// Active plugin configuration.
    pub(crate) config: MqConfig,
    /// Shared process-wide in-memory broker.
    pub(crate) broker: InMemoryBroker,
    /// Optional custom pluggable broker backend installed via [`MqPlugin::init_with_broker`].
    pub(crate) custom_broker: Option<Arc<dyn MessageBroker>>,
}