Files
mytheclipse/crates/mytheclipse-event/src/amqp.rs
T
asepharyana 4d851c5a58
CI / Rustfmt (push) Canceled after 0s
CI / Clippy (push) Canceled after 0s
CI / Test (workspace all features) (push) Canceled after 0s
CI / Test (workspace default features) (push) Canceled after 0s
CI / Test (mytheclipse / bg only) (push) Canceled after 0s
CI / Test (mytheclipse / compute only) (push) Canceled after 0s
CI / Test (mytheclipse / io only) (push) Canceled after 0s
CI / Test (mytheclipse / lifecycle only) (push) Canceled after 0s
CI / Test (mytheclipse / observability only) (push) Canceled after 0s
CI / Test (mytheclipse / resiliency only) (push) Canceled after 0s
CI / Test (mytheclipse / traffic only) (push) Canceled after 0s
CI / Test (mytheclipse-cache / l2-redis) (push) Canceled after 0s
CI / Test (mytheclipse-cache / l1-moka) (push) Canceled after 0s
CI / Test (mytheclipse-cache / default) (push) Canceled after 0s
CI / Test (mytheclipse-config / default) (push) Canceled after 0s
CI / Test (mytheclipse-crypto / default) (push) Canceled after 0s
CI / Test (mytheclipse-event / amqp) (push) Canceled after 0s
CI / Test (mytheclipse-event / nats) (push) Canceled after 0s
CI / Test (mytheclipse-event / default (mem)) (push) Canceled after 0s
CI / Test (mytheclipse-storage / gcs) (push) Canceled after 0s
CI / Test (mytheclipse-storage / s3) (push) Canceled after 0s
CI / Test (mytheclipse-storage / default (local)) (push) Canceled after 0s
CI / Run mytheclipse example (push) Canceled after 0s
CI / Docs check (push) Canceled after 0s
CI / Cargo package dry-run (mytheclipse) (push) Canceled after 0s
CI / Cargo package dry-run (mytheclipse-cache) (push) Canceled after 0s
CI / Cargo package dry-run (mytheclipse-config) (push) Canceled after 0s
CI / Cargo package dry-run (mytheclipse-crypto) (push) Canceled after 0s
CI / Cargo package dry-run (mytheclipse-event) (push) Canceled after 0s
CI / Cargo package dry-run (mytheclipse-storage) (push) Canceled after 0s
Release / Semantic Release (push) Canceled after 0s
chore: rename corex-* crates to mytheclipse-* namespace
Rename all `corex-cache`, `corex-storage`, `corex-event`, `corex-config`,
and `corex-crypto` crates to `mytheclipse-cache`, `mytheclipse-storage`,
`mytheclipse-event`, `mytheclipse-config`, and `mytheclipse-crypto`
respectively, aligning with the `mytheclipse` root crate naming convention.

- Convert root `Cargo.toml` from a package manifest to a workspace
  manifest with explicit member paths
- Update crate names in each `Cargo.toml` and docs.rs URLs
- Update all import paths, module doc comments, and error/panic messages
  from `corex-*` to `mytheclipse-*` across source and README files
- Update CI workflow and publish script to reference the new crate names<tool_call></think>chore: rename corex-* crates to mytheclipse-* namespace

Rename all `corex-cache`, `corex-storage`, `corex-event`, `corex-config`,
and `corex-crypto` crates to `mytheclipse-cache`, `mytheclipse-storage`,
`mytheclipse-event`, `mytheclipse-config`, and `mytheclipse-crypto`
respectively, aligning with the `mytheclipse` root crate naming convention.

- Convert root `Cargo.toml` from a package manifest to a workspace
  manifest with explicit member paths
- Update crate names in each `Cargo.toml` and docs.rs URLs
- Update all import paths, module doc comments, and error/panic messages
  from `corex-*` to `mytheclipse-*` across source and README files
- Update CI workflow and publish script to reference the new crate names
2026-08-28 22:29:49 +07:00

164 lines
5.1 KiB
Rust

//! A RabbitMQ-backed [`EventBus`] (feature `amqp`), via the pure-Rust `lapin`
//! AMQP 0.9.1 client.
//!
//! Topics map to routing keys on a single topic [`lapin::ExchangeKind::Topic`]
//! exchange (default name `mytheclipse.events`); each subscription declares its own
//! exclusive, auto-delete queue bound to that routing key, matching the
//! common "fanout via topic exchange" pattern.
use async_trait::async_trait;
use futures_lite::StreamExt;
use lapin::options::{
BasicAckOptions, BasicConsumeOptions, BasicPublishOptions, ExchangeDeclareOptions,
QueueBindOptions, QueueDeclareOptions,
};
use lapin::types::FieldTable;
use lapin::{BasicProperties, Channel, Connection, ConnectionProperties, ExchangeKind};
use crate::traits::{EventBus, EventError, Subscription, SubscriptionInner};
fn map_err(e: lapin::Error) -> EventError {
EventError::Io(e.to_string())
}
/// An [`EventBus`] backed by a RabbitMQ topic exchange.
#[derive(Clone)]
pub struct AmqpEventBus {
channel: Channel,
exchange: String,
}
impl AmqpEventBus {
/// Connects to `addr` (an AMQP URL, e.g. `amqp://guest:guest@localhost:5672/%2f`)
/// and declares the topic exchange `exchange`.
pub async fn connect(addr: &str, exchange: &str) -> Result<Self, EventError> {
let conn = Connection::connect(addr, ConnectionProperties::default())
.await
.map_err(map_err)?;
let channel = conn.create_channel().await.map_err(map_err)?;
channel
.exchange_declare(
exchange,
ExchangeKind::Topic,
ExchangeDeclareOptions {
durable: true,
..Default::default()
},
FieldTable::default(),
)
.await
.map_err(map_err)?;
Ok(Self {
channel,
exchange: exchange.to_string(),
})
}
/// Wraps an already-open channel with a pre-declared exchange (advanced
/// use: sharing a channel/connection across multiple buses).
pub fn from_channel(channel: Channel, exchange: String) -> Self {
Self { channel, exchange }
}
}
#[async_trait]
impl EventBus for AmqpEventBus {
async fn publish(&self, topic: &str, payload: Vec<u8>) -> Result<(), EventError> {
self.channel
.basic_publish(
&self.exchange,
topic,
BasicPublishOptions::default(),
&payload,
BasicProperties::default(),
)
.await
.map_err(map_err)?
.await
.map_err(map_err)?;
Ok(())
}
async fn subscribe(&self, topic: &str) -> Result<Subscription, EventError> {
let queue = self
.channel
.queue_declare(
"", // server-generated name
QueueDeclareOptions {
exclusive: true,
auto_delete: true,
..Default::default()
},
FieldTable::default(),
)
.await
.map_err(map_err)?;
self.channel
.queue_bind(
queue.name().as_str(),
&self.exchange,
topic,
QueueBindOptions::default(),
FieldTable::default(),
)
.await
.map_err(map_err)?;
let consumer = self
.channel
.basic_consume(
queue.name().as_str(),
"mytheclipse-event-consumer",
BasicConsumeOptions::default(),
FieldTable::default(),
)
.await
.map_err(map_err)?;
Ok(Subscription::new(Box::new(AmqpSubscription { consumer })))
}
}
struct AmqpSubscription {
consumer: lapin::Consumer,
}
#[async_trait]
impl SubscriptionInner for AmqpSubscription {
async fn recv(&mut self) -> Result<Vec<u8>, EventError> {
match self.consumer.next().await {
Some(Ok(delivery)) => {
let data = delivery.data.clone();
delivery
.ack(BasicAckOptions::default())
.await
.map_err(map_err)?;
Ok(data)
}
Some(Err(e)) => Err(map_err(e)),
None => Err(EventError::Closed),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Requires a live RabbitMQ at `AMQP_URL` (e.g.
/// `amqp://guest:guest@127.0.0.1:5672/%2f`). Run with:
/// `AMQP_URL=... cargo test -p mytheclipse-event --features amqp -- --ignored`.
#[tokio::test]
#[ignore = "requires a live RabbitMQ instance (AMQP_URL)"]
async fn publish_subscribe_roundtrip_live() {
let url = std::env::var("AMQP_URL").expect("set AMQP_URL");
let bus = AmqpEventBus::connect(&url, "mytheclipse_event_test")
.await
.unwrap();
let mut sub = bus.subscribe("orders.created").await.unwrap();
bus.publish("orders.created", b"hello".to_vec())
.await
.unwrap();
let msg = sub.recv().await.unwrap();
assert_eq!(msg, b"hello");
}
}