hyperlane-plugin-mq 23.3.2

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::*;

/// Returns the current Unix timestamp in milliseconds.
///
/// # Returns
///
/// - `u64` - Milliseconds since Unix epoch (`0` if the system clock precedes the epoch).
#[inline]
pub(crate) fn now_epoch_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_millis() as u64)
        .unwrap_or(0)
}

/// Computes a deterministic shard slot for `topic` using 8-byte word multiplicative hashing.
///
/// # Arguments
///
/// - `&str` - Topic name to hash.
///
/// # Returns
///
/// - `usize` - Shard index in `0..MQ_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn mq_topic_shard_index(topic: &str) -> usize {
    let mut hasher: FnvHasher = FnvHasher::default();
    hasher.write(topic.as_bytes());
    let h: u64 = hasher.finish();
    (((h >> 32) ^ h) as usize) & (MQ_SHARD_COUNT - 1)
}

/// Encodes `topic_id` and monotonic `seq` into one globally unique `receipt_id`.
///
/// # Arguments
///
/// - `u32` - Dense owning topic identifier.
/// - `u64` - Monotonic delivery sequence number.
///
/// # Returns
///
/// - `u64` - Packed receipt identifier carrying `topic_id` in its upper 24 bits.
#[inline(always)]
pub(crate) fn encode_receipt_id(topic_id: u32, seq: u64) -> u64 {
    ((topic_id as u64) << MQ_RECEIPT_SEQ_BITS) | (seq & MQ_RECEIPT_SEQ_MASK)
}

/// Decodes the owning `topic_id` embedded in `receipt_id`.
///
/// # Arguments
///
/// - `u64` - Packed delivery receipt identifier.
///
/// # Returns
///
/// - `usize` - Dense topic table index.
#[inline(always)]
pub(crate) fn decode_receipt_topic_id(receipt_id: u64) -> usize {
    (receipt_id >> MQ_RECEIPT_SEQ_BITS) as usize
}

/// Returns whether a message has passed its optional TTL deadline.
///
/// # Arguments
///
/// - `&MqMessage` - Message to inspect.
/// - `u64` - Current Unix timestamp in milliseconds.
///
/// # Returns
///
/// - `bool` - `true` when `expires_at_ms` is set and `<= now_ms`.
#[inline(always)]
pub(crate) fn is_message_expired(message: &MqMessage, now_ms: u64) -> bool {
    message
        .get_expires_at_ms()
        .is_some_and(|deadline: u64| now_ms >= deadline)
}

/// Formats the dead-letter queue key for `topic` using `config`.
///
/// # Arguments
///
/// - `&str` - Base topic name.
/// - `&MqConfig` - Broker configuration holding `dlq_suffix`.
///
/// # Returns
///
/// - `String` - Dead-letter queue key.
#[inline]
pub(crate) fn dlq_topic_name(topic: &str, config: &MqConfig) -> String {
    let suffix: &str = config.get_dlq_suffix();
    let mut out: String = String::with_capacity(topic.len() + suffix.len());
    out.push_str(topic);
    out.push_str(suffix);
    out
}