Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(events): macro event broker crate (#4396)
Will Hutchinson481912015445
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 03325cbdc9..aef4c4ca6c 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -2594,6 +2594,15 @@"macro_env_var","workspace-hack"],+ "macro_event_broker": [+ "macro_event_broker",+ "macro_event_topics",+ "workspace-hack"+ ],+ "macro_event_topics": [+ "macro_event_topics",+ "workspace-hack"+ ],"macro_middleware": ["agent","ai_toolset",diff --git a/nix/cloud-storage.nix b/nix/cloud-storage.nixindex b1a462d321..6ae2400541 100644--- a/nix/cloud-storage.nix+++ b/nix/cloud-storage.nix@@ -28,6 +28,8 @@[opensslopenssl.dev+ rdkafka+ rdkafka.devglibglib.devlibclang@@ -763,22 +765,33 @@// deployLambdaPackages;devShells = {- default = pkgs.mkShell (- {- buildInputs = shellTools ++ libraries;- PKG_CONFIG_PATH = "${pkgs.openssl.dev}/lib/pkgconfig";- LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";- RUSTC_WRAPPER = "${pkgs.sccache}/bin/sccache";- # Keep local cargo-lambda builds on the same aws-lc-sys path as- # the Nix lambda derivations. The default cc builder rejects- # cargo-lambda/cargo-zigbuild's Zig cc wrapper.- AWS_LC_SYS_CMAKE_BUILDER = "1";- }- // pkgs.lib.optionalAttrs isLinux {- LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";- BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";- }- );+ default =+ let+ pkgConfigPath = pkgs.lib.makeSearchPath "lib/pkgconfig" [+ pkgs.openssl.dev+ pkgs.rdkafka.dev+ ];+ in+ pkgs.mkShell (+ {+ buildInputs = shellTools ++ libraries;+ PKG_CONFIG_PATH = pkgConfigPath;+ # Cargo build scripts use the Nix pkg-config wrapper, which prefers+ # the target-specific search path when PKG_CONFIG_PATH_FOR_TARGET is set.+ # Keep librdkafka visible there so rdkafka-sys can find rdkafka.pc.+ PKG_CONFIG_PATH_FOR_TARGET = pkgConfigPath;+ LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";+ RUSTC_WRAPPER = "${pkgs.sccache}/bin/sccache";+ # Keep local cargo-lambda builds on the same aws-lc-sys path as+ # the Nix lambda derivations. The default cc builder rejects+ # cargo-lambda/cargo-zigbuild's Zig cc wrapper.+ AWS_LC_SYS_CMAKE_BUILDER = "1";+ }+ // pkgs.lib.optionalAttrs isLinux {+ LD_LIBRARY_PATH = "${pkgs.lib.makeLibraryPath libraries}";+ BINDGEN_EXTRA_CLANG_ARGS = "-I${pkgs.glibc.dev}/include -I${pkgs.gcc.cc}/lib/gcc/${pkgs.stdenv.hostPlatform.config}/${pkgs.gcc.version}/include";+ }+ );};};}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 6404c2e045..4317ba39d5 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -7307,6 +7307,31 @@ dependencies = ["workspace-hack",]+[[package]]+name = "macro_event_broker"+version = "0.1.0"+dependencies = [+ "macro_event_topics",+ "rdkafka",+ "rootcause",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]++[[package]]+name = "macro_event_topics"+version = "0.1.0"+dependencies = [+ "sealed",+ "thiserror 2.0.18",+ "workspace-hack",+]+[[package]]name = "macro_middleware"version = "0.1.0"@@ -8701,6 +8726,28 @@ dependencies = ["libm",]+[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro-crate 3.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "oauth2"version = "5.0.0"@@ -10317,6 +10364,35 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "rdkafka"+version = "0.37.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14b52c81ac3cac39c9639b95c20452076e74b8d9a71bc6fc4d83407af2ea6fff"+dependencies = [+ "futures-channel",+ "futures-util",+ "libc",+ "log",+ "rdkafka-sys",+ "serde",+ "serde_derive",+ "serde_json",+ "slab",+ "tokio",+]++[[package]]+name = "rdkafka-sys"+version = "4.10.0+2.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e234cf318915c1059d4921ef7f75616b5219b10b46e9f3a511a15eb4b56a3f77"+dependencies = [+ "libc",+ "num_enum",+ "pkg-config",+]+[[package]]name = "readonly_pool"version = "0.1.0"@@ -11148,6 +11224,17 @@ version = "3.0.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca"+[[package]]+name = "sealed"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22f968c5ea23d555e670b449c1c5e7b2fc399fdaec1d304a17cd48e288abc107"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]+[[package]]name = "search_processing_service"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 1a04409f5c..2b3ee744ee 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -54,13 +54,11 @@ members = ["tools/native_app_server","unfurl","unfurl_service",- "webhook","upload_extractor_lambda_handler","upload_extractor_lambda_trigger","user_link_cleanup_handler","worker_trigger",- "macro_config",- "macro_queues",+ "macro_event_broker","prompt","workspace-hack","tools/xtask",@@ -142,6 +140,10 @@ pdfium-render = { version = "0.8.37", default-features = false, features = ["pdfpgvector = { version = "0.4", features = ["postgres", "sqlx"] }quote = "1"rand = "0.9.0"+rdkafka = { version = "0.37", default-features = false, features = [+ "dynamic-linking",+ "tokio",+] }recursion = "0.5.4"redis = "1.0.3"regex = "1.11.1"diff --git a/rust/cloud-storage/macro_event_broker/Cargo.toml b/rust/cloud-storage/macro_event_broker/Cargo.tomlnew file mode 100644index 0000000000..5f87f7a422--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/Cargo.toml@@ -0,0 +1,25 @@+[package]+edition = "2024"+name = "macro_event_broker"+publish = false+version = "0.1.0"++[features]+default = ["ports", "outbound"]+outbound = ["dep:rdkafka", "ports"]+ports = ["dep:tokio"]++[dependencies]+rootcause = { workspace = true }+rdkafka = { workspace = true, optional = true }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true, features = ["macros"], optional = true }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }+macro_event_topics = { path = "../macro_event_topics" }++[dev-dependencies]+tokio = { workspace = true }diff --git a/rust/cloud-storage/macro_event_broker/examples/example_event.rs b/rust/cloud-storage/macro_event_broker/examples/example_event.rsnew file mode 100644index 0000000000..a118059080--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/examples/example_event.rs@@ -0,0 +1,143 @@+use macro_event_broker::{+ Event, EventBrokerError, EventPublisher, MacroEvent, MacroEventBroker, MacroEventBrokerService,+ TopicEvent,+};+use macro_event_topics::{MacroExampleTopic, Topic};+use serde::{Deserialize, Serialize};++/// Publisher used by the example. Real services should use the Kafka adapter.+pub struct ExampleEventPublisher;++impl EventPublisher for ExampleEventPublisher {+ async fn publish<T: Topic>(+ &self,+ topic: T,+ key: &str,+ payload: &[u8],+ ) -> Result<(), EventBrokerError> {+ println!(+ "publishing topic={} key={} payload={}",+ topic.as_str(),+ key,+ String::from_utf8_lossy(payload)+ );+ Ok(())+ }+}++/// Metadata for [`ExampleTopicEvent::Created`].+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ExampleCreatedMetadata {+ /// Human-readable name for the example event.+ pub name: String,+ /// Example count value.+ pub count: u32,+}++/// Metadata for [`ExampleTopicEvent::Updated`].+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ExampleUpdatedMetadata {+ /// Updated count value.+ pub count: String,+}++/// Events that can be published to [`MacroExampleTopic`].+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "event_type", content = "metadata")]+pub enum ExampleTopicEvent {+ /// Example creation event.+ #[serde(rename = "example.created")]+ Created(ExampleCreatedMetadata),+ /// Example update event.+ #[serde(rename = "example.updated")]+ Updated(ExampleUpdatedMetadata),+}++impl TopicEvent for ExampleTopicEvent {+ type Topic = MacroExampleTopic;++ fn schema_version(&self) -> u8 {+ 1+ }+}++/// Publishable event for [`MacroExampleTopic`].+pub struct ExampleMacroEvent {+ key: String,+ event: Event<ExampleTopicEvent>,+}++impl ExampleMacroEvent {+ /// Build a created event.+ pub fn created(key: impl Into<String>, metadata: ExampleCreatedMetadata) -> Self {+ Self::new(key, ExampleTopicEvent::Created(metadata))+ }++ /// Build an updated event.+ pub fn updated(key: impl Into<String>, metadata: ExampleUpdatedMetadata) -> Self {+ Self::new(key, ExampleTopicEvent::Updated(metadata))+ }++ /// Build an event from a topic-specific event variant.+ pub fn new(key: impl Into<String>, event: ExampleTopicEvent) -> Self {+ Self::with_event(key, Event::new(event))+ }++ /// Build an event from a pre-built envelope.+ pub fn with_event(key: impl Into<String>, event: Event<ExampleTopicEvent>) -> Self {+ Self {+ key: key.into(),+ event,+ }+ }+}++impl MacroEvent for ExampleMacroEvent {+ type EventPayload = ExampleTopicEvent;++ fn key(&self) -> &str {+ &self.key+ }++ fn event(&self) -> &Event<Self::EventPayload> {+ &self.event+ }++ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {+ Self::with_event(key, event)+ }+}++/// Consumer-specific event enum for a consumer that subscribes to `macro.example`.+pub enum ExampleConsumerEvent {+ /// Event received on [`MacroExampleTopic`].+ Example(ExampleMacroEvent),+}++impl ExampleConsumerEvent {+ /// Decode one Kafka message into this consumer's event enum.+ pub fn decode(topic: &str, key: &str, payload: &[u8]) -> Result<Self, EventBrokerError> {+ match topic {+ topic if topic == MacroExampleTopic.as_str() => {+ Ok(Self::Example(ExampleMacroEvent::decode(key, payload)?))+ }+ unknown => Err(EventBrokerError::UnknownTopic(unknown.to_string())),+ }+ }+}++#[tokio::main]+pub async fn main() -> Result<(), EventBrokerError> {+ let service = MacroEventBrokerService::new(ExampleEventPublisher);+ let event = ExampleMacroEvent::created(+ "example-123",+ ExampleCreatedMetadata {+ name: "hello".to_string(),+ count: 7,+ },+ );++ service.send_event(&event).await?;++ Ok(())+}diff --git a/rust/cloud-storage/macro_event_broker/src/domain/mod.rs b/rust/cloud-storage/macro_event_broker/src/domain/mod.rsnew file mode 100644index 0000000000..1e30fc3ae2--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/domain/mod.rs@@ -0,0 +1,10 @@+/// Domain models: per-topic event traits, [`Event`](models::Event), [`MacroEvent`](models::MacroEvent), and error types.+pub mod models;++/// Port traits: the inbound and outbound boundaries of the broker.+#[cfg(feature = "ports")]+pub mod ports;++/// Service orchestration for publishing events.+#[cfg(feature = "ports")]+pub mod service;diff --git a/rust/cloud-storage/macro_event_broker/src/domain/models.rs b/rust/cloud-storage/macro_event_broker/src/domain/models.rsnew file mode 100644index 0000000000..f8062fa1ba--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/domain/models.rs@@ -0,0 +1,131 @@+//! Domain models for the event broker.++use macro_event_topics::Topic;+use serde::{Deserialize, Serialize, de::DeserializeOwned};+use uuid::Uuid;++/// Event payload enum for a single [`Topic`].+///+/// Implement this trait for each topic-specific event enum. The enum should use+/// `#[serde(tag = "event_type", content = "metadata")]` so the wire payload is+/// self-describing while each variant still carries strongly typed metadata.+pub trait TopicEvent: Serialize + DeserializeOwned + Send + Sync {+ /// The concrete topic type that all variants of this event enum belong to.+ type Topic: Topic;++ /// Version of this concrete event variant's payload schema.+ fn schema_version(&self) -> u8;+}++/// Serializable event envelope published through the broker.+///+/// The envelope carries broker-agnostic information that is useful to downstream+/// consumers. The topic-specific event enum is flattened so the wire shape stays:+/// `event_id`, `schema_version`, `event_type`, and `metadata`.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct Event<E> {+ /// Unique identifier for this event instance.+ pub event_id: Uuid,+ /// Version of the event payload schema.+ pub schema_version: u8,+ /// Topic-specific event variant and strongly typed metadata.+ #[serde(flatten)]+ pub event: E,+}++impl<E: TopicEvent> Event<E> {+ /// Create a new event with a generated UUIDv7 event id.+ pub fn new(event: E) -> Self {+ Self::with_event_id(Uuid::now_v7(), event)+ }++ /// Create a new event with a generated UUIDv7 event id and explicit schema version.+ pub fn with_schema_version(event: E, schema_version: u8) -> Self {+ Self::with_event_id_and_schema_version(Uuid::now_v7(), schema_version, event)+ }++ /// Create a new event with an explicit event id.+ pub fn with_event_id(event_id: Uuid, event: E) -> Self {+ let schema_version = event.schema_version();+ Self::with_event_id_and_schema_version(event_id, schema_version, event)+ }++ /// Create a new event with an explicit event id and schema version.+ pub fn with_event_id_and_schema_version(event_id: Uuid, schema_version: u8, event: E) -> Self {+ Self {+ event_id,+ schema_version,+ event,+ }+ }++ /// Deserialize an event envelope from JSON payload bytes.+ pub fn decode(payload: &[u8]) -> Result<Self, EventBrokerError> {+ Ok(serde_json::from_slice(payload)?)+ }++ /// Kafka topic this event belongs to.+ pub fn topic(&self) -> E::Topic {+ E::Topic::default()+ }+}++/// Domain event that can be routed through the macro event broker.+///+/// Application code should define concrete types implementing this trait. Those+/// types own the broker key plus the typed [`Event`] envelope, keeping Kafka+/// routing metadata separate from the serialized payload.+pub trait MacroEvent: Send + Sync {+ /// Topic-specific event enum carried by this macro event.+ type EventPayload: TopicEvent;++ /// Kafka topic this event should be published to.+ fn topic(&self) -> <Self::EventPayload as TopicEvent>::Topic {+ <<Self as MacroEvent>::EventPayload as TopicEvent>::Topic::default()+ }++ /// Kafka message key used for partitioning and compaction.+ fn key(&self) -> &str;++ /// Serializable event envelope to publish.+ fn event(&self) -> &Event<Self::EventPayload>;++ /// Build this macro event from the Kafka message key and deserialized event envelope.+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self+ where+ Self: Sized;++ /// Decode this macro event from the Kafka message key and JSON payload bytes.+ fn decode<K: Into<String>>(key: K, payload: &[u8]) -> Result<Self, EventBrokerError>+ where+ Self: Sized,+ {+ Ok(Self::from_event(key.into(), Event::decode(payload)?))+ }+}++/// Errors that can occur when publishing or consuming an event.+#[derive(Debug, thiserror::Error)]+pub enum EventBrokerError {+ /// The event payload could not be serialized to or deserialized from JSON.+ #[error("failed to serialize or deserialize event payload")]+ Serialization(#[from] serde_json::Error),+ /// The Kafka topic name is not handled by a consumer-specific event enum.+ #[error("unknown event topic: {0}")]+ UnknownTopic(String),+ /// The broker rejected or failed to deliver the message.+ #[error("failed to publish event: {0}")]+ Publish(String),+ /// An otherwise-unclassified internal error.+ #[error("internal event broker error: {0:?}")]+ Internal(rootcause::Report),+}++impl From<rootcause::Report> for EventBrokerError {+ fn from(report: rootcause::Report) -> Self {+ EventBrokerError::Internal(report)+ }+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/macro_event_broker/src/domain/models/test.rs b/rust/cloud-storage/macro_event_broker/src/domain/models/test.rsnew file mode 100644index 0000000000..95e2c942b1--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/domain/models/test.rs@@ -0,0 +1,124 @@+use macro_event_topics::{MacroExampleTopic, Topic};+use serde::{Deserialize, Serialize};+use serde_json::json;+use uuid::Uuid;++use super::*;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+struct ExampleCreatedMetadata {+ name: String,+ count: u32,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "event_type", content = "metadata")]+enum ExampleTopicEvent {+ #[serde(rename = "example.created")]+ Created(ExampleCreatedMetadata),+}++impl TopicEvent for ExampleTopicEvent {+ type Topic = MacroExampleTopic;++ fn schema_version(&self) -> u8 {+ 1+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct ExampleMacroEvent {+ key: String,+ event: Event<ExampleTopicEvent>,+}++impl ExampleMacroEvent {+ fn with_event(key: impl Into<String>, event: Event<ExampleTopicEvent>) -> Self {+ Self {+ key: key.into(),+ event,+ }+ }+}++impl MacroEvent for ExampleMacroEvent {+ type EventPayload = ExampleTopicEvent;++ fn key(&self) -> &str {+ &self.key+ }++ fn event(&self) -> &Event<Self::EventPayload> {+ &self.event+ }++ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {+ Self::with_event(key, event)+ }+}++enum ExampleConsumerEvent {+ Example(ExampleMacroEvent),+}++impl ExampleConsumerEvent {+ fn decode(topic: &str, key: &str, payload: &[u8]) -> Result<Self, EventBrokerError> {+ match topic {+ topic if topic == MacroExampleTopic.as_str() => {+ Ok(Self::Example(ExampleMacroEvent::decode(key, payload)?))+ }+ unknown => Err(EventBrokerError::UnknownTopic(unknown.to_string())),+ }+ }+}++fn example_event() -> Event<ExampleTopicEvent> {+ Event::with_event_id(+ Uuid::from_u128(1),+ ExampleTopicEvent::Created(ExampleCreatedMetadata {+ name: "hello".to_string(),+ count: 7,+ }),+ )+}++#[test]+fn event_serializes_to_tagged_wire_shape() {+ let event = example_event();++ assert_eq!(+ serde_json::to_value(&event).unwrap(),+ json!({+ "event_id": "00000000-0000-0000-0000-000000000001",+ "schema_version": 1,+ "event_type": "example.created",+ "metadata": {+ "name": "hello",+ "count": 7,+ },+ })+ );+}++#[test]+fn macro_event_decodes_from_payload() {+ let event = example_event();+ let payload = serde_json::to_vec(&event).unwrap();++ let decoded = ExampleMacroEvent::decode("msg-123", &payload).unwrap();++ assert_eq!(decoded.key(), "msg-123");+ assert_eq!(decoded.event(), &event);+}++#[test]+fn consumer_specific_enum_decodes_by_topic() {+ let event = example_event();+ let payload = serde_json::to_vec(&event).unwrap();++ let decoded = ExampleConsumerEvent::decode(MacroExampleTopic.as_str(), "msg-123", &payload)+ .expect("topic should decode");++ let ExampleConsumerEvent::Example(decoded) = decoded;+ assert_eq!(decoded.key(), "msg-123");+}diff --git a/rust/cloud-storage/macro_event_broker/src/domain/ports.rs b/rust/cloud-storage/macro_event_broker/src/domain/ports.rsnew file mode 100644index 0000000000..a24f43dc53--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/domain/ports.rs@@ -0,0 +1,33 @@+//! Port traits defining the broker's inbound and outbound boundaries.++use std::future::Future;++use macro_event_topics::Topic;++use crate::domain::models::{EventBrokerError, MacroEvent};++/// Inbound port: the public API for sending events through the broker.+///+/// Implemented by [`MacroEventBrokerService`](crate::domain::service::MacroEventBrokerService).+pub trait MacroEventBroker: Send + Sync + 'static {+ /// Serialize `event` to JSON and publish it to the topic declared by its typed payload,+ /// keyed by [`MacroEvent::key`].+ fn send_event<E: MacroEvent + ?Sized>(+ &self,+ event: &E,+ ) -> impl Future<Output = Result<(), EventBrokerError>> + Send;+}++/// Outbound port: the boundary to the underlying message broker (e.g. Kafka).+///+/// Kept byte-oriented so payload serialization stays the service's concern and the+/// port is trivial to mock or stub in tests.+pub trait EventPublisher: Send + Sync + 'static {+ /// Publish a raw `payload` to `topic`, keyed by `key`.+ fn publish<T: Topic>(+ &self,+ topic: T,+ key: &str,+ payload: &[u8],+ ) -> impl Future<Output = Result<(), EventBrokerError>> + Send;+}diff --git a/rust/cloud-storage/macro_event_broker/src/domain/service.rs b/rust/cloud-storage/macro_event_broker/src/domain/service.rsnew file mode 100644index 0000000000..31a17f232d--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/domain/service.rs@@ -0,0 +1,33 @@+//! The concrete event broker service.++#[cfg(test)]+mod test;++use macro_event_topics::Topic as _;++use crate::domain::models::{EventBrokerError, MacroEvent};+use crate::domain::ports::{EventPublisher, MacroEventBroker};++/// Orchestrates serializing events and handing them to an [`EventPublisher`].+pub struct MacroEventBrokerService<P: EventPublisher> {+ publisher: P,+}++impl<P: EventPublisher> MacroEventBrokerService<P> {+ /// Create a new service backed by the given outbound publisher.+ pub fn new(publisher: P) -> Self {+ Self { publisher }+ }+}++impl<P: EventPublisher> MacroEventBroker for MacroEventBrokerService<P> {+ #[tracing::instrument(err, skip(self, event), fields(topic = %event.topic().as_str(), key = %event.key()))]+ async fn send_event<E: MacroEvent + ?Sized>(&self, event: &E) -> Result<(), EventBrokerError> {+ let topic = event.topic();+ let key = event.key();+ let envelope = event.event();+ let payload = serde_json::to_vec(envelope)?;++ self.publisher.publish(topic, key, &payload).await+ }+}diff --git a/rust/cloud-storage/macro_event_broker/src/domain/service/test.rs b/rust/cloud-storage/macro_event_broker/src/domain/service/test.rsnew file mode 100644index 0000000000..ae2d337c76--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/domain/service/test.rs@@ -0,0 +1,115 @@+use std::sync::Mutex;++use macro_event_topics::{MacroExampleTopic, Topic};+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::*;+use crate::domain::models::{Event, EventBrokerError, MacroEvent, TopicEvent};+use crate::domain::ports::{EventPublisher, MacroEventBroker};++/// A captured publish call: topic, key, and raw payload bytes.+#[derive(Debug, Clone, PartialEq, Eq)]+struct Published {+ topic: String,+ key: String,+ payload: Vec<u8>,+}++/// In-memory publisher that records every call instead of hitting a broker.+#[derive(Default)]+struct RecordingPublisher {+ calls: Mutex<Vec<Published>>,+}++impl EventPublisher for RecordingPublisher {+ async fn publish<T: Topic>(+ &self,+ topic: T,+ key: &str,+ payload: &[u8],+ ) -> Result<(), EventBrokerError> {+ self.calls.lock().unwrap().push(Published {+ topic: topic.as_str().to_string(),+ key: key.to_string(),+ payload: payload.to_vec(),+ });+ Ok(())+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+struct ExampleCreatedMetadata {+ name: String,+ count: u32,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "event_type", content = "metadata")]+enum ExampleTopicEvent {+ #[serde(rename = "example.created")]+ Created(ExampleCreatedMetadata),+}++impl TopicEvent for ExampleTopicEvent {+ type Topic = MacroExampleTopic;++ fn schema_version(&self) -> u8 {+ 1+ }+}++struct ExampleMacroEvent {+ key: String,+ event: Event<ExampleTopicEvent>,+}++impl ExampleMacroEvent {+ fn with_event(key: impl Into<String>, event: Event<ExampleTopicEvent>) -> Self {+ Self {+ key: key.into(),+ event,+ }+ }+}++impl MacroEvent for ExampleMacroEvent {+ type EventPayload = ExampleTopicEvent;++ fn key(&self) -> &str {+ &self.key+ }++ fn event(&self) -> &Event<Self::EventPayload> {+ &self.event+ }++ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {+ Self::with_event(key, event)+ }+}++#[tokio::test]+async fn send_event_serializes_and_routes() {+ let service = MacroEventBrokerService::new(RecordingPublisher::default());+ let envelope = Event::with_event_id(+ Uuid::from_u128(1),+ ExampleTopicEvent::Created(ExampleCreatedMetadata {+ name: "hello".to_string(),+ count: 7,+ }),+ );+ let event = ExampleMacroEvent::with_event("msg-123", envelope.clone());++ service+ .send_event(&event)+ .await+ .expect("publish should succeed");++ let calls = service.publisher.calls.lock().unwrap();+ assert_eq!(calls.len(), 1);+ let call = &calls[0];+ assert_eq!(call.topic, MacroExampleTopic.as_str());+ assert_eq!(call.key, "msg-123");+ assert_eq!(call.payload, serde_json::to_vec(&envelope).unwrap());+}diff --git a/rust/cloud-storage/macro_event_broker/src/lib.rs b/rust/cloud-storage/macro_event_broker/src/lib.rsnew file mode 100644index 0000000000..d081712271--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/lib.rs@@ -0,0 +1,26 @@+#![deny(missing_docs)]+//! Event broker that publishes events to Kafka via a ports-and-adapters design.+//!+//! The [`domain`] layer defines typed event envelopes, per-topic+//! [`TopicEvent`](domain::models::TopicEvent) enums, the+//! [`MacroEvent`](domain::models::MacroEvent) event abstraction, the inbound+//! [`MacroEventBroker`](domain::ports::MacroEventBroker) API, the outbound+//! [`EventPublisher`](domain::ports::EventPublisher) port, and the+//! [`MacroEventBrokerService`](domain::service::MacroEventBrokerService) that ties+//! them together. Kafka topic definitions live in the `macro_event_topics` crate.+//! The [`outbound`] layer provides the Kafka adapter implementation.++/// Domain layer: models, ports, and service.+pub mod domain;++pub use domain::models::{Event, EventBrokerError, MacroEvent, TopicEvent};+pub use macro_event_topics::{MacroExampleTopic, Topic};++#[cfg(feature = "ports")]+pub use domain::ports::{EventPublisher, MacroEventBroker};+#[cfg(feature = "ports")]+pub use domain::service::MacroEventBrokerService;++/// Outbound layer: Kafka adapter for the [`EventPublisher`](domain::ports::EventPublisher) port.+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/macro_event_broker/src/outbound/kafka_event_publisher.rs b/rust/cloud-storage/macro_event_broker/src/outbound/kafka_event_publisher.rsnew file mode 100644index 0000000000..18b259a1a2--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/outbound/kafka_event_publisher.rs@@ -0,0 +1,57 @@+//! Kafka adapter for the [`EventPublisher`] port.+//!+//! Wraps an `rdkafka` [`FutureProducer`] to publish events. The broker address is+//! supplied by the caller (typically from environment configuration at the+//! consuming service), so no env wiring lives in this crate yet.++use std::time::Duration;++use macro_event_topics::Topic;+use rdkafka::ClientConfig;+use rdkafka::producer::{FutureProducer, FutureRecord};++use crate::domain::models::EventBrokerError;+use crate::domain::ports::EventPublisher;++/// How long a record may sit in the producer queue before delivery is considered failed.+const MESSAGE_TIMEOUT_MS: &str = "5000";++/// How long [`EventPublisher::publish`] waits for delivery confirmation before timing out.+const SEND_TIMEOUT: Duration = Duration::from_secs(5);++/// Kafka-backed implementation of [`EventPublisher`].+pub struct KafkaEventPublisher {+ producer: FutureProducer,+}++impl KafkaEventPublisher {+ /// Build a producer connected to the given comma-separated `brokers` list.+ pub fn new(brokers: &str) -> Result<Self, EventBrokerError> {+ let producer: FutureProducer = ClientConfig::new()+ .set("bootstrap.servers", brokers)+ .set("message.timeout.ms", MESSAGE_TIMEOUT_MS)+ .create()+ .map_err(|e| EventBrokerError::Publish(format!("failed to create producer: {e}")))?;++ Ok(Self { producer })+ }+}++impl EventPublisher for KafkaEventPublisher {+ #[tracing::instrument(err, skip(self, payload), fields(topic = %topic.as_str(), key = %key))]+ async fn publish<T: Topic>(+ &self,+ topic: T,+ key: &str,+ payload: &[u8],+ ) -> Result<(), EventBrokerError> {+ let record = FutureRecord::to(topic.as_str()).key(key).payload(payload);++ self.producer+ .send(record, SEND_TIMEOUT)+ .await+ .map_err(|(e, _)| EventBrokerError::Publish(e.to_string()))?;++ Ok(())+ }+}diff --git a/rust/cloud-storage/macro_event_broker/src/outbound/mod.rs b/rust/cloud-storage/macro_event_broker/src/outbound/mod.rsnew file mode 100644index 0000000000..c0bd839798--- /dev/null+++ b/rust/cloud-storage/macro_event_broker/src/outbound/mod.rs@@ -0,0 +1,2 @@+/// Kafka adapter implementing the [`EventPublisher`](crate::domain::ports::EventPublisher) port.+pub mod kafka_event_publisher;diff --git a/rust/cloud-storage/macro_event_topics/Cargo.toml b/rust/cloud-storage/macro_event_topics/Cargo.tomlnew file mode 100644index 0000000000..467f37bd65--- /dev/null+++ b/rust/cloud-storage/macro_event_topics/Cargo.toml@@ -0,0 +1,10 @@+[package]+edition = "2024"+name = "macro_event_topics"+publish = false+version = "0.1.0"++[dependencies]+sealed = "0.6.0"+thiserror = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/rust/cloud-storage/macro_event_topics/src/lib.rs b/rust/cloud-storage/macro_event_topics/src/lib.rsnew file mode 100644index 0000000000..fb7a8837d9--- /dev/null+++ b/rust/cloud-storage/macro_event_topics/src/lib.rs@@ -0,0 +1,31 @@+#![deny(missing_docs)]+//! Defines all topics for kafka.+//! This file is also programmatically grabbed in infra to ensure all kafka topics are created.++use sealed::sealed;++/// Errors that can occur for a Topic+#[derive(Debug, thiserror::Error)]+pub enum TopicError {+ /// The Kafka topic name is not known to this broker crate.+ #[error("unknown event topic: {0}")]+ UnknownTopic(String),+}++/// A Topic is mapped to a Kafka topic that events can be published to.+#[sealed]+pub trait Topic: Default + Copy + Send + Sync + 'static {+ /// The kafka topic name as a string.+ fn as_str(&self) -> &'static str;+}++/// Example kafka topic.+#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub struct MacroExampleTopic;++#[sealed]+impl Topic for MacroExampleTopic {+ fn as_str(&self) -> &'static str {+ "macro.example"+ }+}