Promote service modules to services/ directory; add AmqpConnection + async IPL
- Flat src/amqp.rs, src/mongo.rs, src/mariadb.rs promoted to src/services/{amqp,mongo,mariadb}/
- services/amqp/connection.rs: AmqpConnection struct with connect() and declare_exchange()
- services/amqp/error.rs: AmqpError type (thiserror, wraps lapin::Error)
- ipl() made async; #[tokio::main] added to main()
- IPL step 3b: authenticate to RabbitMQ + declare beds.events topic exchange (durable)
- Added lapin = "2" and tokio = { version = "1", features = ["full"] } to Cargo.toml
- 12 unit tests pass
- Docs: README, CLAUDE.md, wiki/04-ipl.md, wiki/06-queue-topology.md updated
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
//! # services/amqp/connection.rs — AMQP Connection
|
||||
//!
|
||||
//! Defines the `AmqpConnection` struct — the authenticated, channel-holding
|
||||
//! connection to a RabbitMQ broker. Responsible for establishing the AMQP
|
||||
//! session and declaring the `beds.events` topic exchange at IPL.
|
||||
//!
|
||||
//! ## Calling Agents
|
||||
//! - `ipl()` in main.rs — calls `AmqpConnection::connect()` then `declare_exchange()`
|
||||
//! - Broker tasks (future) — hold an `AmqpConnection` for publish/consume operations
|
||||
//!
|
||||
//! ## Inputs
|
||||
//! - `BrokerServicesConfig` — host, port, vhost, credentials, queue_tag from config
|
||||
//!
|
||||
//! ## Outputs
|
||||
//! - `AmqpConnection` — authenticated connection + open channel, ready for use
|
||||
//! - `AmqpError` on authentication failure or broker unavailability
|
||||
//!
|
||||
//! **Author:** mks
|
||||
//! **Version:** 1.0
|
||||
//!
|
||||
//! ## History
|
||||
//! * `2026-04-04` - mks - original coding
|
||||
|
||||
use lapin::{Channel, Connection, ConnectionProperties, ExchangeKind};
|
||||
use lapin::options::ExchangeDeclareOptions;
|
||||
use lapin::types::FieldTable;
|
||||
|
||||
use crate::config::BrokerServicesConfig;
|
||||
use super::error::AmqpError;
|
||||
|
||||
/// The name of the BEDS topic exchange. All events in the cluster are
|
||||
/// published to this exchange and routed by key to their consumers.
|
||||
pub const EXCHANGE_NAME: &str = "beds.events";
|
||||
|
||||
/// An authenticated AMQP connection with an open channel.
|
||||
///
|
||||
/// Created during IPL by `AmqpConnection::connect()`. Holds both the
|
||||
/// underlying `lapin::Connection` (to prevent premature drop) and the
|
||||
/// `lapin::Channel` used for all subsequent operations.
|
||||
///
|
||||
/// The `queue_tag` field carries the configured queue name prefix
|
||||
/// (e.g. `"prod_"`) so that any queue declarations made through this
|
||||
/// connection are automatically namespaced to the correct environment.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub struct AmqpConnection {
|
||||
/// Held to keep the underlying TCP connection alive.
|
||||
/// lapin::Channel holds an internal Arc reference to the connection,
|
||||
/// but we store it explicitly for clarity and to prevent accidental drop.
|
||||
_connection: Connection,
|
||||
|
||||
/// The open channel used for all AMQP operations on this connection.
|
||||
pub channel: Channel,
|
||||
|
||||
/// Queue name prefix from config — prepended to every queue name to
|
||||
/// isolate environments on a shared broker. Example: "prod_", "dev_"
|
||||
pub queue_tag: String,
|
||||
}
|
||||
|
||||
impl AmqpConnection {
|
||||
|
||||
/// Connects to the configured RabbitMQ broker and opens a channel.
|
||||
///
|
||||
/// Authenticates using the credentials in `cfg.app_server` and connects
|
||||
/// to the configured vhost. Returns an `AmqpConnection` with an open
|
||||
/// channel ready for exchange declaration and queue binding.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `cfg` — broker services configuration block from `BedsConfig`
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(AmqpConnection)` on successful authentication and channel open.
|
||||
/// `Err(AmqpError)` if the broker rejects the connection or credentials.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub async fn connect(cfg: &BrokerServicesConfig) -> Result<Self, AmqpError> {
|
||||
let uri = format!(
|
||||
"amqp://{}:{}@{}:{}/{}",
|
||||
cfg.app_server.user,
|
||||
cfg.app_server.pass,
|
||||
cfg.app_server.host,
|
||||
cfg.app_server.port,
|
||||
cfg.vhost,
|
||||
);
|
||||
|
||||
let connection = Connection::connect(&uri, ConnectionProperties::default()).await?;
|
||||
let channel = connection.create_channel().await?;
|
||||
|
||||
Ok(Self {
|
||||
_connection: connection,
|
||||
channel,
|
||||
queue_tag: cfg.queue_tag.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Declares the `beds.events` topic exchange on the broker.
|
||||
///
|
||||
/// The exchange is declared durable — it survives broker restarts.
|
||||
/// If the exchange already exists with identical parameters, this is
|
||||
/// a no-op. If it exists with different parameters, the broker returns
|
||||
/// an error.
|
||||
///
|
||||
/// This must be called once at IPL before any broker tasks attempt to
|
||||
/// bind queues or publish events.
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(())` if the exchange is declared or already exists.
|
||||
/// `Err(AmqpError)` if the broker rejects the declaration.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub async fn declare_exchange(&self) -> Result<(), AmqpError> {
|
||||
self.channel
|
||||
.exchange_declare(
|
||||
EXCHANGE_NAME,
|
||||
ExchangeKind::Topic,
|
||||
ExchangeDeclareOptions {
|
||||
durable: true,
|
||||
..Default::default()
|
||||
},
|
||||
FieldTable::default(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! # services/amqp/error.rs — AMQP Error Types
|
||||
//!
|
||||
//! Defines the error type for all AMQP operations in the BEDS transport layer.
|
||||
//!
|
||||
//! ## Calling Agents
|
||||
//! - `services::amqp::connection` — returned from connect() and declare_exchange()
|
||||
//! - `ipl()` in main.rs — maps AmqpError to String for the IPL error chain
|
||||
//!
|
||||
//! **Author:** mks
|
||||
//! **Version:** 1.0
|
||||
//!
|
||||
//! ## History
|
||||
//! * `2026-04-04` - mks - original coding
|
||||
|
||||
/// Errors that can occur in the AMQP transport layer.
|
||||
///
|
||||
/// All lapin protocol errors are wrapped transparently via the `From` impl.
|
||||
/// Additional variants cover BEDS-specific failure modes.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum AmqpError {
|
||||
#[error("AMQP protocol error: {0}")]
|
||||
Protocol(#[from] lapin::Error),
|
||||
|
||||
#[error("Invalid broker address '{0}': {1}")]
|
||||
InvalidAddress(String, String),
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! # services/amqp/mod.rs — AMQP Transport Module
|
||||
//!
|
||||
//! RabbitMQ transport layer. Provides IPL reachability validation and the
|
||||
//! `AmqpConnection` struct for authenticated broker sessions.
|
||||
//!
|
||||
//! ## Public Surface
|
||||
//! - `validate()` — TCP reachability check (IPL step 3)
|
||||
//! - `AmqpConnection` — authenticated connection + channel (IPL step 3b)
|
||||
//! - `EXCHANGE_NAME` — the canonical `beds.events` exchange name constant
|
||||
//!
|
||||
//! **Author:** mks
|
||||
//! **Version:** 1.0
|
||||
//!
|
||||
//! ## History
|
||||
//! * `2026-04-02` - mks - original coding (flat amqp.rs)
|
||||
//! * `2026-04-04` - mks - promoted to services/amqp/, added AmqpConnection struct
|
||||
|
||||
pub mod connection;
|
||||
pub mod error;
|
||||
|
||||
pub use connection::{AmqpConnection, EXCHANGE_NAME};
|
||||
pub use error::AmqpError; // will be used by broker pool error handling
|
||||
|
||||
use std::net::TcpStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::BrokerServicesConfig;
|
||||
|
||||
/// Validates that the RabbitMQ broker is reachable via TCP.
|
||||
///
|
||||
/// Opens a TCP connection to the configured broker host and port. Does not
|
||||
/// authenticate or open an AMQP channel — reachability only. The connection
|
||||
/// is closed immediately after a successful connect.
|
||||
///
|
||||
/// Called at IPL step 3 as a fast pre-flight check before the more expensive
|
||||
/// `AmqpConnection::connect()` authentication step.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `cfg` — broker services configuration block from `BedsConfig`
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(())` if the TCP handshake succeeds within 5 seconds.
|
||||
/// `Err(String)` with a descriptive message if the broker cannot be reached.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-02` - mks - original coding
|
||||
pub fn validate(cfg: &BrokerServicesConfig) -> Result<(), String> {
|
||||
let addr_str = format!("{}:{}", cfg.app_server.host, cfg.app_server.port);
|
||||
|
||||
let addr: std::net::SocketAddr = addr_str
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid broker address {}: {}", addr_str, e))?;
|
||||
|
||||
TcpStream::connect_timeout(&addr, Duration::from_secs(5))
|
||||
.map_err(|e| format!("RabbitMQ unreachable at {}: {}", addr_str, e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::load_from;
|
||||
|
||||
fn test_cfg() -> crate::config::BedsConfig {
|
||||
load_from("tests/fixtures/beds_test.toml", "")
|
||||
.expect("test fixture beds_test.toml failed to load")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_err_on_closed_port() {
|
||||
let mut cfg = test_cfg();
|
||||
cfg.broker_services.app_server.port = 1;
|
||||
assert!(validate(&cfg.broker_services).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_err_on_bad_address() {
|
||||
let mut cfg = test_cfg();
|
||||
cfg.broker_services.app_server.host = "not_a_valid_host!!!".to_string();
|
||||
assert!(validate(&cfg.broker_services).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! # services/mariadb/mod.rs — MariaDB (REL) Transport Module
|
||||
//!
|
||||
//! MariaDB transport layer. Provides IPL reachability validation for all
|
||||
//! configured REL service nodes. Master failure is fatal; secondary failure
|
||||
//! is always non-fatal. Future phases will add the MariaDbConnection struct
|
||||
//! for authenticated sessions and query dispatch.
|
||||
//!
|
||||
//! ## Calling Agents
|
||||
//! - `ipl()` in main.rs — calls `validate_all()` during the IPL sequence
|
||||
//!
|
||||
//! ## Inputs
|
||||
//! - `HashMap<String, RelNodeConfig>` from the loaded BEDS configuration
|
||||
//!
|
||||
//! ## Outputs
|
||||
//! - `Ok(())` if all configured REL master nodes are reachable
|
||||
//! - `Err(String)` with node name, host:port, and OS error on first master failure
|
||||
//!
|
||||
//! **Author:** mks
|
||||
//! **Version:** 1.0
|
||||
//!
|
||||
//! ## History
|
||||
//! * `2026-04-04` - mks - original coding (flat mariadb.rs)
|
||||
//! * `2026-04-04` - mks - promoted to services/mariadb/
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::TcpStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::{RelInstanceConfig, RelNodeConfig};
|
||||
|
||||
/// Validates that all configured MariaDB master nodes are reachable.
|
||||
///
|
||||
/// Iterates every entry in the `rel_services` config block and validates the
|
||||
/// master instance. Secondary instances are checked but their failure is
|
||||
/// non-fatal — a missing or unreachable secondary is logged as a warning.
|
||||
/// Fails on the first unreachable master.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `nodes` — map of service name → `RelNodeConfig` from `BedsConfig`
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(())` if every master node responds to a TCP connect within the timeout.
|
||||
/// `Err(String)` with the service name and address of the first master failure.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub fn validate_all(nodes: &HashMap<String, RelNodeConfig>) -> Result<(), String> {
|
||||
for (name, node) in nodes {
|
||||
validate(&format!("{}.master", name), &node.master)?;
|
||||
|
||||
if let Some(secondary) = &node.secondary {
|
||||
if let Err(e) = validate(&format!("{}.secondary", name), secondary) {
|
||||
tracing::warn!("MariaDB secondary unreachable (non-fatal): {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates that a single MariaDB instance is reachable.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `label` — descriptive label for error messages (e.g. "app_server.master")
|
||||
/// * `instance` — `RelInstanceConfig` for this instance
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(())` if the TCP handshake succeeds within 5 seconds.
|
||||
/// `Err(String)` with a descriptive message on failure.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub fn validate(label: &str, instance: &RelInstanceConfig) -> Result<(), String> {
|
||||
let addr_str = format!("{}:{}", instance.host, instance.port);
|
||||
|
||||
let addr: std::net::SocketAddr = addr_str
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid MariaDB address for rel_services.{} ({}): {}", label, addr_str, e))?;
|
||||
|
||||
TcpStream::connect_timeout(&addr, Duration::from_secs(5))
|
||||
.map_err(|e| format!("MariaDB unreachable at rel_services.{} ({}): {}", label, addr_str, e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::load_from;
|
||||
|
||||
fn test_cfg() -> crate::config::BedsConfig {
|
||||
load_from("tests/fixtures/beds_test.toml", "")
|
||||
.expect("test fixture beds_test.toml failed to load")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_err_on_closed_port() {
|
||||
let cfg = test_cfg();
|
||||
let node = cfg.rel_services.get("app_server").unwrap();
|
||||
let mut bad = node.master.clone();
|
||||
bad.port = 1;
|
||||
assert!(validate("app_server.master", &bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_err_on_bad_address() {
|
||||
let cfg = test_cfg();
|
||||
let node = cfg.rel_services.get("app_server").unwrap();
|
||||
let mut bad = node.master.clone();
|
||||
bad.host = "not_a_valid_host!!!".to_string();
|
||||
assert!(validate("app_server.master", &bad).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//! # services/mod.rs — External Service Transports
|
||||
//!
|
||||
//! Groups all external service transport modules. Each submodule owns the
|
||||
//! TCP/protocol-level connection lifecycle for one service type — from IPL
|
||||
//! reachability validation through to authenticated connection pooling.
|
||||
//!
|
||||
//! ## Submodules
|
||||
//! - `amqp` — RabbitMQ transport (AMQP 0-9-1 via lapin)
|
||||
//! - `mongo` — MongoDB transport (REC document store)
|
||||
//! - `mariadb` — MariaDB transport (REL relational store)
|
||||
//!
|
||||
//! **Author:** mks
|
||||
//! **Version:** 1.0
|
||||
//!
|
||||
//! ## History
|
||||
//! * `2026-04-04` - mks - original coding — promoted from flat src/ files
|
||||
|
||||
pub mod amqp;
|
||||
pub mod mariadb;
|
||||
pub mod mongo;
|
||||
@@ -0,0 +1,109 @@
|
||||
//! # services/mongo/mod.rs — MongoDB (REC) Transport Module
|
||||
//!
|
||||
//! MongoDB transport layer. Provides IPL reachability validation for all
|
||||
//! configured REC service nodes. Future phases will add the MongoConnection
|
||||
//! struct for authenticated sessions and collection access.
|
||||
//!
|
||||
//! ## Calling Agents
|
||||
//! - `ipl()` in main.rs — calls `validate_all()` during the IPL sequence
|
||||
//!
|
||||
//! ## Inputs
|
||||
//! - `HashMap<String, RecNodeConfig>` from the loaded BEDS configuration
|
||||
//!
|
||||
//! ## Outputs
|
||||
//! - `Ok(())` if all configured REC nodes are reachable
|
||||
//! - `Err(String)` with node name, host:port, and OS error on first failure
|
||||
//!
|
||||
//! **Author:** mks
|
||||
//! **Version:** 1.0
|
||||
//!
|
||||
//! ## History
|
||||
//! * `2026-04-04` - mks - original coding (flat mongo.rs)
|
||||
//! * `2026-04-04` - mks - promoted to services/mongo/
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::TcpStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::RecNodeConfig;
|
||||
|
||||
/// Validates that all configured MongoDB nodes are reachable.
|
||||
///
|
||||
/// Iterates every entry in the `rec_services` config block and opens a TCP
|
||||
/// connection to each declared host:port. Does not authenticate or issue any
|
||||
/// MongoDB wire protocol — reachability only. Fails on the first unreachable
|
||||
/// node.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `nodes` — map of service name → `RecNodeConfig` from `BedsConfig`
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(())` if every node responds to a TCP connect within the timeout.
|
||||
/// `Err(String)` with the service name and address of the first failure.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub fn validate_all(nodes: &HashMap<String, RecNodeConfig>) -> Result<(), String> {
|
||||
for (name, node) in nodes {
|
||||
validate(name, node)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Validates that a single MongoDB node is reachable.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `name` — service name from config (e.g. "app_server") — used in error messages
|
||||
/// * `node` — `RecNodeConfig` for this node
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// `Ok(())` if the TCP handshake succeeds within 5 seconds.
|
||||
/// `Err(String)` with a descriptive message on failure.
|
||||
///
|
||||
/// # History
|
||||
///
|
||||
/// * `2026-04-04` - mks - original coding
|
||||
pub fn validate(name: &str, node: &RecNodeConfig) -> Result<(), String> {
|
||||
let addr_str = format!("{}:{}", node.host, node.port);
|
||||
|
||||
let addr: std::net::SocketAddr = addr_str
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid MongoDB address for rec_services.{} ({}): {}", name, addr_str, e))?;
|
||||
|
||||
TcpStream::connect_timeout(&addr, Duration::from_secs(5))
|
||||
.map_err(|e| format!("MongoDB unreachable at rec_services.{} ({}): {}", name, addr_str, e))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::load_from;
|
||||
|
||||
fn test_cfg() -> crate::config::BedsConfig {
|
||||
load_from("tests/fixtures/beds_test.toml", "")
|
||||
.expect("test fixture beds_test.toml failed to load")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_err_on_closed_port() {
|
||||
let mut cfg = test_cfg();
|
||||
let node = cfg.rec_services.get_mut("app_server").unwrap();
|
||||
node.port = 1;
|
||||
assert!(validate("app_server", node).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_err_on_bad_address() {
|
||||
let mut cfg = test_cfg();
|
||||
let node = cfg.rec_services.get_mut("app_server").unwrap();
|
||||
node.host = "not_a_valid_host!!!".to_string();
|
||||
assert!(validate("app_server", node).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user