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: stream crate (#1507)
Eric Hayesf25fa26aea7c
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex aa35eb6065..6b20d12620 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2009,6 +2009,7 @@ dependencies = ["serde_dynamo","serde_json","sqlx",+ "stream","strum","strum_macros","tokio",@@ -7709,6 +7710,15 @@ dependencies = ["uuid",]+[[package]]+name = "scc"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46e6f046b7fef48e2660c57ed794263155d713de679057f2d0c169bfc6e756cc"+dependencies = [+ "sdd",+]+[[package]]name = "schannel"version = "0.1.27"@@ -7817,6 +7827,12 @@ dependencies = ["untrusted",]+[[package]]+name = "sdd"+version = "3.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "490dcfcbfef26be6800d11870ff2df8774fa6e86d047e3e8c8a76b25655e41ca"+[[package]]name = "search_processing_service"version = "0.1.0"@@ -8247,6 +8263,32 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "serial_test"+version = "3.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d0b343e184fc3b7bb44dff0705fffcf4b3756ba6aff420dddd8b24ca145e555"+dependencies = [+ "futures-executor",+ "futures-util",+ "log",+ "once_cell",+ "parking_lot",+ "scc",+ "serial_test_derive",+]++[[package]]+name = "serial_test_derive"+version = "3.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f50427f258fb77356e4cd4aa0e87e2bd2c66dbcee41dc405282cae2bfc26c83"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.98",+]+[[package]]name = "servo_arc"version = "0.3.0"@@ -8847,6 +8889,27 @@ dependencies = ["tracing",]+[[package]]+name = "stream"+version = "0.1.0"+dependencies = [+ "anyhow",+ "async-stream",+ "async-trait",+ "dashmap",+ "futures",+ "model-entity",+ "redis",+ "serde",+ "serde_json",+ "serial_test",+ "thiserror 2.0.17",+ "tokio",+ "tokio-stream",+ "tokio-test",+ "tracing",+]+[[package]]name = "string_cache"version = "0.8.8"@@ -9287,6 +9350,18 @@ dependencies = ["futures-core","pin-project-lite","tokio",+ "tokio-util",+]++[[package]]+name = "tokio-test"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f6d24790a10a7af737693a3e8f1d03faef7e6ca0cc99aae5066f533766de545"+dependencies = [+ "futures-core",+ "tokio",+ "tokio-stream",][[package]]diff --git a/rust/cloud-storage/connection_gateway/Cargo.toml b/rust/cloud-storage/connection_gateway/Cargo.tomlindex c3f0ef2c74..174412ac3d 100644--- a/rust/cloud-storage/connection_gateway/Cargo.toml+++ b/rust/cloud-storage/connection_gateway/Cargo.toml@@ -62,6 +62,7 @@ serde_json = { workspace = true }sqlx = { workspace = true }strum = { workspace = true, features = ["derive"] }strum_macros = { workspace = true }+stream = { path = "../stream" }tokio = { workspace = true }tower = { workspace = true }tower-http = { workspace = true }diff --git a/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs b/rust/cloud-storage/connection_gateway/src/api/connection/messages.rsindex 37fa5278b0..a40486ed2e 100644--- a/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs+++ b/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs@@ -20,7 +20,9 @@ pub async fn handle_websocket_stream(while let Some(msg) = stream.next().await {match msg {Ok(msg) => {- handle_message(connection_context, msg, &sender).await?;+ if let Err(e) = handle_message(connection_context, msg, &sender).await {+ tracing::error!(error=?e, "error handling message");+ }}Err(err) => {match err@@ -84,13 +86,16 @@ pub async fn handle_message(match parsed_message {ToWebsocketMessage::TrackEntityMessage(message) => {+ let entity_id = message.extra.entity_id.to_string();+tracker::track_entity(+ sender,connection_context,TrackingData {entity: message.extra.entity_type- .with_entity_str(&message.extra.entity_id)+ .with_entity_str(&entity_id).with_connection_str(connection_context.connection_id).with_user_str(&connection_context.user_context.user_id),action: message.action,diff --git a/rust/cloud-storage/connection_gateway/src/context.rs b/rust/cloud-storage/connection_gateway/src/context.rsindex dfc35cb225..a9a5a883af 100644--- a/rust/cloud-storage/connection_gateway/src/context.rs+++ b/rust/cloud-storage/connection_gateway/src/context.rs@@ -10,12 +10,14 @@ use macro_middleware::auth::internal_access::InternalApiSecretKey;use redis::{RedisError, aio::MultiplexedConnection};use secretsmanager_client::LocalOrRemoteSecret;use std::sync::Arc;+use stream::domain::StreamManager;#[derive(Clone, FromRef)]pub struct ApiContext {pub connection_manager: crate::service::connection::ConnectionManager,pub frecency_ingestor_service: EventIngestorImpl<FrecencyPgStorage>,pub redis_client: Arc<redis::Client>,+ pub stream_manager: Arc<dyn StreamManager + Send + Sync>,}impl ApiContext {diff --git a/rust/cloud-storage/connection_gateway/src/main.rs b/rust/cloud-storage/connection_gateway/src/main.rsindex c284861ef7..e3dd17b77a 100644--- a/rust/cloud-storage/connection_gateway/src/main.rs+++ b/rust/cloud-storage/connection_gateway/src/main.rs@@ -30,6 +30,7 @@ use secretsmanager_client::LocalOrRemoteSecret;use service::dynamodb::create_dynamo_db_connection_manager;use service::redis::poll_messages;use sqlx::postgres::PgPoolOptions;+use stream::outbound::redis::{RedisStreamManager, RedisStreamRepo};use tower_http::cors::CorsLayer;env_var!(@@ -85,6 +86,11 @@ async fn main() -> Result<()> {let connection_manager = create_dynamo_db_connection_manager(dynamodb_client.clone()).await?;+ let stream_service = RedisStreamRepo::new((*redis_client).clone())+ .await+ .context("failed to create stream service")?;+ let stream_manager = RedisStreamManager::new(stream_service.obj());+let pgpool = PgPoolOptions::new().min_connections(3).max_connections(20)@@ -102,6 +108,7 @@ async fn main() -> Result<()> {connection_manager,redis_client: Arc::clone(&redis_client),frecency_ingestor_service: EventIngestorImpl::new(FrecencyPgStorage::new(pgpool.clone())),+ stream_manager,};tokio::spawn(poll_messages(context.clone()));diff --git a/rust/cloud-storage/connection_gateway/src/model/mod.rs b/rust/cloud-storage/connection_gateway/src/model/mod.rsindex cacd7326f0..7215a634d8 100644--- a/rust/cloud-storage/connection_gateway/src/model/mod.rs+++ b/rust/cloud-storage/connection_gateway/src/model/mod.rs@@ -1,4 +1,5 @@pub mod connection;pub mod message;pub mod sender;+pub mod stream;pub mod websocket;diff --git a/rust/cloud-storage/connection_gateway/src/model/stream.rs b/rust/cloud-storage/connection_gateway/src/model/stream.rsnew file mode 100644index 0000000000..8122247b7c--- /dev/null+++ b/rust/cloud-storage/connection_gateway/src/model/stream.rs@@ -0,0 +1,16 @@+use super::message::{Message, OutgoingMessage};+use stream::domain::StreamItem;++const STREAM_MESSAGE_TYPE: &str = "stream";++impl TryFrom<StreamItem> for OutgoingMessage {+ type Error = serde_json::Error;+ fn try_from(value: StreamItem) -> Result<Self, Self::Error> {+ serde_json::to_string(&value).map(|data| {+ OutgoingMessage::Message(Message {+ message_type: STREAM_MESSAGE_TYPE.into(),+ data,+ })+ })+ }+}diff --git a/rust/cloud-storage/connection_gateway/src/service/tracker.rs b/rust/cloud-storage/connection_gateway/src/service/tracker.rsindex 207962b6e6..bdde7404d7 100644--- a/rust/cloud-storage/connection_gateway/src/service/tracker.rs+++ b/rust/cloud-storage/connection_gateway/src/service/tracker.rs@@ -1,17 +1,26 @@use crate::{constants::DEFAULT_TIMEOUT_THRESHOLD,- model::{connection::ConnectionContext, message::Message},+ model::{+ connection::ConnectionContext,+ message::{Message, OutgoingMessage},+ },};use anyhow::Result;use frecency::domain::{models::EventRecord, ports::EventIngestorService};+use futures::StreamExt;use futures::TryFutureExt;use itertools::Itertools;use model_entity::{Entity, EntityType, TrackAction, TrackingData};+use tokio::sync::mpsc::Sender;use tracing::Level;use super::sender::send_message_to_entity;-pub async fn track_entity(ctx: ConnectionContext<'_>, data: TrackingData<'_>) -> Result<()> {+pub async fn track_entity(+ sender: &Sender<OutgoingMessage>,+ ctx: ConnectionContext<'_>,+ data: TrackingData<'_>,+) -> Result<()> {let fut = ctx.api_context.frecency_ingestor_service@@ -24,6 +33,26 @@ pub async fn track_entity(ctx: ConnectionContext<'_>, data: TrackingData<'_>) ->.add_connection_entity(data.entity.clone()).await.ok();+ let mut item_stream = ctx+ .api_context+ .stream_manager+ .subscribe(+ ctx.connection_id.to_owned(),+ data.entity.extra.extra.entity_id.to_string(),+ )+ .await?;+ let sender = sender.to_owned();+ tokio::spawn(async move {+ while let Some(item) = item_stream.next().await {+ let Ok(msg) = OutgoingMessage::try_from(item) else {+ tracing::warn!("stream item conversion failed, skipping");+ continue;+ };+ if sender.send(msg).await.is_err() {+ break;+ }+ }+ });}TrackAction::Close => {ctx.api_context@@ -31,6 +60,11 @@ pub async fn track_entity(ctx: ConnectionContext<'_>, data: TrackingData<'_>) ->.remove_connection_entity(&data.entity.extra).await.ok();++ ctx.api_context+ .stream_manager+ .unsubscribe(ctx.connection_id.to_owned())+ .await?;}TrackAction::Ping => {ctx.api_contextdiff --git a/rust/cloud-storage/stream/Cargo.toml b/rust/cloud-storage/stream/Cargo.tomlnew file mode 100644index 0000000000..2b9919367e--- /dev/null+++ b/rust/cloud-storage/stream/Cargo.toml@@ -0,0 +1,33 @@+[package]+name = "stream"+version = "0.1.0"+edition = "2024"+publish=false++[features]+redis-test=[]++[dependencies]+serde = { version = "1.0", features = ["derive"] }+serde_json = { workspace = true }+tokio = { version = "1", features = ["sync", "rt", "macros"] }+tokio-stream = { workspace = true, features = ["sync"] }+thiserror = { workspace = true }+futures = { workspace = true }+tracing = { workspace = true }+redis = { workspace = true, features = [+"streams",+"aio",+ "tokio-comp",+ "tokio-native-tls-comp",+] }+async-trait = { workspace = true }+async-stream = { workspace = true }+model-entity = { path = "../model-entity" }+anyhow = { workspace = true }+dashmap = { workspace = true }++[dev-dependencies]+tokio = { version = "1", features = ["rt-multi-thread", "macros"] }+tokio-test = "0.4"+serial_test = "3.3.1"diff --git a/rust/cloud-storage/stream/justfile b/rust/cloud-storage/stream/justfilenew file mode 100644index 0000000000..e48c0b0ee2--- /dev/null+++ b/rust/cloud-storage/stream/justfile@@ -0,0 +1,19 @@+export REDIS_URL := env('REDIS_URL', 'redis://127.0.0.1:6379')++mod ensure '../ensure.just'++# Start Redis container+start_redis:+ just ensure::ensure_redis stream-redis++# Stop Redis container+stop_redis:+ -docker stop stream-redis++# Run all tests (unit tests only, no Redis required)+test:+ cargo test -p stream++# Run integration tests (requires Redis)+test_integration *args: start_redis+ cargo test -p stream --features redis-test -- --ignored {{args}}diff --git a/rust/cloud-storage/stream/src/bin/stream_stdin.rs b/rust/cloud-storage/stream/src/bin/stream_stdin.rsnew file mode 100644index 0000000000..873c766695--- /dev/null+++ b/rust/cloud-storage/stream/src/bin/stream_stdin.rs@@ -0,0 +1,48 @@+use model_entity::EntityType;+use std::io::{self, BufRead};+use stream::domain::StreamId;+use stream::outbound::redis::RedisStreamRepo;++const ENTITY_TYPE: EntityType = EntityType::Channel;+// battlefield channel+const ENTITY_ID: &str = "019467c2-49d0-7d99-b0b9-d535811a337d";+const STREAM_ID: &str = "stdin";++fn main() -> anyhow::Result<()> {+ let db_url = std::env::var("DBURL")+ .or_else(|_| std::env::var("REDIS_URL"))+ .unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());++ let rt = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()?;++ let stream_id = StreamId {+ entity_type: ENTITY_TYPE,+ entity_id: ENTITY_ID.to_string(),+ stream_id: STREAM_ID.to_string(),+ };++ rt.block_on(async move {+ let client = redis::Client::open(db_url)?;+ let service = RedisStreamRepo::new(client).await?;+ let _ = service.cleanup_stream(&stream_id).await;+ let stream_service = service.obj();++ let stdin = io::stdin();+ for line in stdin.lock().lines() {+ let line = line?;+ let line = line.trim_end().to_string();+ if line.is_empty() {+ continue;+ }+ stream_service+ .append(&stream_id, serde_json::Value::String(line))+ .await?;+ }++ Ok::<(), anyhow::Error>(())+ })?;++ Ok(())+}diff --git a/rust/cloud-storage/stream/src/domain/ext.rs b/rust/cloud-storage/stream/src/domain/ext.rsnew file mode 100644index 0000000000..e51e22e38a--- /dev/null+++ b/rust/cloud-storage/stream/src/domain/ext.rs@@ -0,0 +1,51 @@+//! Extension traits for StreamRepo.++use super::StreamId;+use super::traits::*;+use futures::StreamExt;+use std::sync::Arc;+use std::time::Duration;++pub trait StreamManagerExt: StreamRepo {+ /// Create a durable stream from an async stream.+ /// Consumes the async stream and closes the durable stream when it ends.+ fn from_async_stream(+ self: Arc<Self>,+ id: StreamId,+ stream: PayloadStream,+ timeout: Option<Duration>,+ ) -> tokio::task::JoinHandle<()>;+}++impl<S> StreamManagerExt for S+where+ S: StreamRepo + ?Sized,+{+ /// Create a durable stream from an async stream+ /// Consume async stream and close the durable stream when it ends+ fn from_async_stream(+ self: Arc<Self>,+ id: StreamId,+ mut stream: PayloadStream,+ timeout: Option<Duration>,+ ) -> tokio::task::JoinHandle<()> {+ tokio::spawn({+ async move {+ let _ =+ tokio::time::timeout(timeout.unwrap_or(DEFAULT_STREAM_TIMEOUT), async move {+ while let Some(payload) = stream.next().await {+ if let Err(e) = self.append(&id, payload).await {+ tracing::error!(error=?e,"failed to append to stream");+ return;+ }+ }+ let _ = self.close(&id).await.inspect_err(+ |e| tracing::error!(error=?e, "failed to mark stream as closed stream"),+ );+ })+ .await+ .inspect_err(|e| tracing::error!(error=?e, "stream timed out"));+ }+ })+ }+}diff --git a/rust/cloud-storage/stream/src/domain/mod.rs b/rust/cloud-storage/stream/src/domain/mod.rsnew file mode 100644index 0000000000..167032516a--- /dev/null+++ b/rust/cloud-storage/stream/src/domain/mod.rs@@ -0,0 +1,9 @@+//! Domain types and traits for the stream service.++mod ext;+mod traits;+mod types;++pub use ext::*;+pub use traits::*;+pub use types::*;diff --git a/rust/cloud-storage/stream/src/domain/traits.rs b/rust/cloud-storage/stream/src/domain/traits.rsnew file mode 100644index 0000000000..452cb94b23--- /dev/null+++ b/rust/cloud-storage/stream/src/domain/traits.rs@@ -0,0 +1,52 @@+//! Core traits and types for the stream service.+use super::types::*;+use super::{StreamId, StreamItem};+use async_trait::async_trait;+use futures::stream::Stream;+use std::pin::Pin;+use std::time::Duration;+use tokio::sync::broadcast::Receiver;++/// Default stream should not last longer than 5 minutes+pub const DEFAULT_STREAM_TIMEOUT: Duration = Duration::from_secs(300);++/// A boxed stream that yields items with their offsets.+pub type ItemStream = Pin<Box<dyn Stream<Item = StreamItem> + Send>>;+/// A boxed stream of payloads to append.+pub type PayloadStream = Pin<Box<dyn Stream<Item = serde_json::Value> + Send>>;+pub type ItemId = String;++#[derive(Debug, Clone)]+pub enum Offset {+ Beginning,+ Location(String),+}++/// A stream service provides durable stream storage+/// This is the base trait of this crate and should be+/// used by consumers through the StreamManager+#[async_trait]+pub trait StreamRepo: Send + Sync + 'static {+ /// Append an item to an existing stream or create a new stream and append an item to it+ async fn append(&self, id: &StreamId, payload: serde_json::Value) -> Result<ItemId>;+ /// Get an async stream that will stream from the beginning of a stream and continue to+ /// listen for new items+ async fn stream_from_beginning(&self, id: &StreamId) -> Result<ItemStream>;+ /// Mark a stream as closed+ async fn close(&self, id: &StreamId) -> Result<()>;+ /// List active streams for an entity (implementations may treat all streams as active).+ async fn active_streams(&self, entity_id: &str) -> Result<Vec<StreamId>>;+ /// A receiver that receives StreamId's when new streams are created+ async fn notify(&self) -> Receiver<StreamId>;+}++/// Subscribe to all streams on an entity, returning a merged item stream.+#[async_trait]+pub trait StreamManager: Send + Sync + 'static {+ /// Subscribe to all current and future streams for an entity.+ /// Returns a merged stream of items from all streams.+ /// `sender_id` uniquely identifies the subscriber (e.g. a connection, not a user).+ async fn subscribe(&self, sender_id: String, entity_id: String) -> Result<ItemStream>;+ /// Cancel the subscription for the given sender, stopping its stream.+ async fn unsubscribe(&self, sender_id: String) -> Result<()>;+}diff --git a/rust/cloud-storage/stream/src/domain/types.rs b/rust/cloud-storage/stream/src/domain/types.rsnew file mode 100644index 0000000000..fc9f42434c--- /dev/null+++ b/rust/cloud-storage/stream/src/domain/types.rs@@ -0,0 +1,38 @@+use model_entity::EntityType;+use serde::{Deserialize, Serialize};+use thiserror::Error;++#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]+pub struct StreamId {+ pub entity_type: EntityType,+ pub entity_id: String,+ pub stream_id: String,+}++pub type Result<T> = std::result::Result<T, StreamServiceError>;++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct StreamItem {+ pub id: StreamId,+ pub payload: serde_json::Value,+}++impl StreamItem {+ pub fn new(id: StreamId, payload: serde_json::Value) -> Self {+ Self { id, payload }+ }+}++#[derive(Debug, Error)]+pub enum StreamServiceError {+ #[error("storage error {0}")]+ StorageError(String),+ #[error("serde error {0}")]+ SerdeError(serde_json::error::Error),+}++impl From<serde_json::error::Error> for StreamServiceError {+ fn from(value: serde_json::error::Error) -> Self {+ Self::SerdeError(value)+ }+}diff --git a/rust/cloud-storage/stream/src/lib.rs b/rust/cloud-storage/stream/src/lib.rsnew file mode 100644index 0000000000..006b073cae--- /dev/null+++ b/rust/cloud-storage/stream/src/lib.rs@@ -0,0 +1,2 @@+pub mod domain;+pub mod outbound;diff --git a/rust/cloud-storage/stream/src/outbound/mod.rs b/rust/cloud-storage/stream/src/outbound/mod.rsnew file mode 100644index 0000000000..027fbef58d--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/mod.rs@@ -0,0 +1 @@+pub mod redis;diff --git a/rust/cloud-storage/stream/src/outbound/redis/ext.rs b/rust/cloud-storage/stream/src/outbound/redis/ext.rsnew file mode 100644index 0000000000..fcf4417423--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/ext.rs@@ -0,0 +1,36 @@+use crate::domain::{StreamId, StreamServiceError};+use model_entity::EntityType;+use std::str::FromStr;++impl From<redis::RedisError> for StreamServiceError {+ fn from(value: redis::RedisError) -> Self {+ Self::StorageError(value.to_string())+ }+}++impl std::fmt::Display for StreamId {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{}:{}:{}",+ self.entity_type, self.entity_id, self.stream_id+ )+ }+}++impl TryFrom<String> for StreamId {+ type Error = StreamServiceError;+ fn try_from(value: String) -> Result<Self, Self::Error> {+ let err = || StreamServiceError::StorageError("Invalid key.".into());+ let (entity_type_str, rest) = value.split_once(':').ok_or_else(err)?;+ let last_colon = rest.rfind(':').ok_or_else(err)?;+ let (entity_id, stream_id) = rest.split_at(last_colon);+ let stream_id = stream_id.trim_start_matches(':');+ let entity_type = EntityType::from_str(entity_type_str).map_err(|_| err())?;+ Ok(StreamId {+ entity_type,+ entity_id: entity_id.to_string(),+ stream_id: stream_id.to_string(),+ })+ }+}diff --git a/rust/cloud-storage/stream/src/outbound/redis/manager.rs b/rust/cloud-storage/stream/src/outbound/redis/manager.rsnew file mode 100644index 0000000000..e772a9d963--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/manager.rs@@ -0,0 +1,81 @@+use crate::domain::{ItemStream, Result, StreamManager, StreamRepo};+use async_stream::stream;+use async_trait::async_trait;+use dashmap::DashMap;+use futures::stream::{SelectAll, StreamExt};+use std::sync::Arc;+use tokio::sync::oneshot;++/// Manages stream subscriptions backed by Redis.+pub struct RedisStreamManager {+ repo: Arc<dyn StreamRepo>,+ subscriptions: DashMap<String, oneshot::Sender<()>>,+}++impl RedisStreamManager {+ /// Create a new manager wrapping the given repo.+ pub fn new(repo: Arc<dyn StreamRepo>) -> Arc<Self> {+ Arc::new(Self {+ repo,+ subscriptions: DashMap::new(),+ })+ }+}++#[async_trait]+impl StreamManager for RedisStreamManager {+ #[tracing::instrument(err, skip(self))]+ async fn subscribe(&self, sender_id: String, entity_id: String) -> Result<ItemStream> {+ let repo = self.repo.clone();++ let active = repo.active_streams(&entity_id).await?;+ let mut notify_rx = repo.notify().await;++ let mut merged = SelectAll::new();+ for id in active {+ let s = repo.stream_from_beginning(&id).await?;+ merged.push(s);+ }++ let (cancel_tx, mut cancel_rx) = oneshot::channel::<()>();+ self.subscriptions.insert(sender_id, cancel_tx);++ let out = stream! {+ loop {+ tokio::select! {+ _ = &mut cancel_rx => break,+ item = merged.next(), if !merged.is_empty() => {+ if let Some(item) = item {+ yield item+ }+ // else: all current streams exhausted, keep listening+ }+ notification = notify_rx.recv() => {+ match notification {+ Ok(stream_id) if stream_id.entity_id == entity_id => {+ match repo.stream_from_beginning(&stream_id).await {+ Ok(stream) => merged.push(stream),+ Err(e) => {+ tracing::error!(error=?e, "failed to stream from beginning");+ }+ }+ },+ Ok(_) => continue,+ Err(_) => break+ }+ }+ }+ }+ };++ Ok(Box::pin(out))+ }++ #[tracing::instrument(err, skip(self))]+ async fn unsubscribe(&self, sender_id: String) -> Result<()> {+ if let Some((_, cancel_tx)) = self.subscriptions.remove(&sender_id) {+ let _ = cancel_tx.send(());+ }+ Ok(())+ }+}diff --git a/rust/cloud-storage/stream/src/outbound/redis/mod.rs b/rust/cloud-storage/stream/src/outbound/redis/mod.rsnew file mode 100644index 0000000000..888b4ed517--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/mod.rs@@ -0,0 +1,10 @@+mod ext;+mod manager;+mod repo;++#[cfg(test)]+#[cfg(feature = "redis-test")]+mod test;++pub use manager::*;+pub use repo::*;diff --git a/rust/cloud-storage/stream/src/outbound/redis/repo.rs b/rust/cloud-storage/stream/src/outbound/redis/repo.rsnew file mode 100644index 0000000000..22237ed33d--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/repo.rs@@ -0,0 +1,242 @@+use crate::domain::*;+use async_stream::stream;+use async_trait::async_trait;+use futures::StreamExt;+use redis::{AsyncCommands, Client, RedisResult, Value, streams::StreamReadReply};+use serde::{Deserialize, Serialize};+use std::sync::Arc;+use tokio::sync::OnceCell;+use tokio::sync::broadcast::{self, Receiver};+use tokio::task::JoinHandle;++const NOTIFY_CHANNEL: &str = "stream:notifications";+const NOTIFY_CHANNEL_BUFFER: usize = 1024;++#[derive(Serialize, Deserialize)]+#[serde(tag = "type", content = "value")]+enum StoredStreamItem {+ Value(serde_json::Value),+ End,+}++struct StreamNotifier {+ _listener: JoinHandle<()>,+ tx: broadcast::Sender<StreamId>,+}++impl StreamNotifier {+ pub async fn new(client: &Client) -> Self {+ // redis blocks the whole connection on pubsub so we need a new one+ // https://redis.io/docs/latest/develop/pubsub/+ let new_connection = client.clone();+ let (tx, _) = broadcast::channel(NOTIFY_CHANNEL_BUFFER);+ let listener = Self::spawn_subscriber(new_connection, tx.clone());+ Self {+ tx,+ _listener: listener,+ }+ }++ pub fn subscribe(&self) -> Receiver<StreamId> {+ self.tx.subscribe()+ }++ fn spawn_subscriber(client: Client, tx: broadcast::Sender<StreamId>) -> JoinHandle<()> {+ tracing::info!("Start notification subscriber");+ tokio::spawn(async move {+ loop {+ match client.get_async_pubsub().await {+ Ok(mut pubsub) => {+ if let Err(e) = pubsub.subscribe(NOTIFY_CHANNEL).await {+ tracing::error!(err=?e,"failed to subscribe to notify channel");+ }+ let mut stream = pubsub.on_message();+ while let Some(msg) = stream.next().await {+ if let Ok(stream_id) = msg+ .get_payload::<String>()+ .map_err(StreamServiceError::from)+ .and_then(|payload| {+ serde_json::from_str::<StreamId>(&payload).map_err(Into::into)+ })+ .inspect_err(|err| tracing::error!(error=?err, "failed to get notification payload"))+ {+ tracing::debug!(stream_id=?stream_id, "notify new stream");+ let _ = tx.send(stream_id).inspect_err(+ |err| tracing::error!(error=?err, "failed to forward notification"),+ );+ }+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to connect to pubsub");+ tokio::time::sleep(std::time::Duration::from_secs(1)).await;+ }+ }+ }+ })+ }+}++impl Drop for StreamNotifier {+ fn drop(&mut self) {+ self._listener.abort();+ }+}++/// Redis-backed stream service using Redis Streams for storage and Pub/Sub for notifications.+#[derive(Clone)]+pub struct RedisStreamRepo {+ client: Arc<Client>,+ notifier: Arc<OnceCell<StreamNotifier>>,+}++// block for 5 min max+const MAX_BLOCK_MS: usize = 1000 * 60 * 5;+const KEY: &str = "item";++impl RedisStreamRepo {+ /// Create a new Redis stream service.+ pub async fn new(client: Client) -> Result<Self> {+ Ok(Self {+ client: Arc::new(client),+ notifier: Arc::new(OnceCell::new()),+ })+ }++ pub fn obj(self) -> Arc<dyn StreamRepo> {+ Arc::new(self)+ }++ /// Delete stream data from redis+ /// Internal / testing only. Streams are cleaned using TTL for prod+ #[allow(unused)]+ pub async fn cleanup_stream(&self, id: &StreamId) -> Result<()> {+ let mut conn = self.client.get_multiplexed_async_connection().await?;+ conn.del(id.to_string())+ .await+ .map_err(|e| StreamServiceError::StorageError(e.to_string()))+ }++ async fn publish_item(+ conn: &mut redis::aio::MultiplexedConnection,+ id: &StreamId,+ item: &StoredStreamItem,+ ) -> Result<ItemId> {+ let json = serde_json::to_string(item).map_err(StreamServiceError::SerdeError)?;+ conn.xadd(id.to_string(), "*", &[(KEY, json)])+ .await+ .map_err(|e| StreamServiceError::StorageError(e.to_string()))+ }+}++#[async_trait]+impl StreamRepo for RedisStreamRepo {+ /// create and append to stream or append to stream+ async fn append(&self, id: &StreamId, payload: serde_json::Value) -> Result<ItemId> {+ let mut conn = self.client.get_multiplexed_async_connection().await?;++ let is_new: bool = !conn+ .exists(id.to_string())+ .await+ .map_err(|e| StreamServiceError::StorageError(e.to_string()))?;++ let item_id = Self::publish_item(&mut conn, id, &StoredStreamItem::Value(payload)).await?;++ if is_new {+ tracing::debug!(stream_id=?id, "New stream detected publishing notification");+ let notification = serde_json::to_string(id).expect("json");+ let _: RedisResult<()> = conn+ .publish(NOTIFY_CHANNEL, notification)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to publish new channel"));+ }++ Ok(item_id)+ }++ async fn stream_from_beginning(&self, id: &StreamId) -> Result<ItemStream> {+ let mut connection = self.client.get_multiplexed_async_connection().await?;+ let stream_key = id.to_string();+ let stream_id_for_item = id.clone();++ let stream = stream! {+ let mut last_id = "0".to_string();++ 'stream_loop: loop {+ let opts = redis::streams::StreamReadOptions::default().block(MAX_BLOCK_MS);++ let result: RedisResult<StreamReadReply> = connection+ .xread_options(&[&stream_key], &[&last_id], &opts).await;++ match result {+ Ok(reply) => {+ for stream_key in reply.keys {+ for entry in stream_key.ids {+ last_id = entry.id.clone();++ for (key, value) in entry.map {+ if key == KEY+ && let Value::BulkString(bytes) = value+ {+ match String::from_utf8(bytes) {+ Ok(json_str) => {+ match serde_json::from_str::<StoredStreamItem>(&json_str) {+ Ok(item) => match item {+ StoredStreamItem::Value(payload) => {++ yield StreamItem::new(stream_id_for_item.clone(), payload)+ }+ StoredStreamItem::End => {+ break 'stream_loop;+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to deserialize stream item");+ }+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "invalid UTF-8 in stream item");+ }+ }+ }+ }+ }+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to read from stream");+ break;+ }+ }+ }+ };+ Ok(Box::pin(stream))+ }++ async fn close(&self, id: &StreamId) -> Result<()> {+ let mut conn = self.client.get_multiplexed_async_connection().await?;+ Self::publish_item(&mut conn, id, &StoredStreamItem::End).await?;+ Ok(())+ }++ //TODO: this does a scan. this should be replaced with a dynamo or something+ async fn active_streams(&self, entity_id: &str) -> Result<Vec<StreamId>> {+ let mut conn = self.client.get_multiplexed_async_connection().await?;+ let pattern = format!("*:{}:*", entity_id);+ let iter = conn.scan_match::<&str, String>(&pattern).await?;+ let keys = iter.collect::<Vec<_>>().await;+ Ok(keys+ .into_iter()+ .filter_map(|s| StreamId::try_from(s).ok())+ .filter(|stream_id| stream_id.entity_id == entity_id)+ .collect())+ }++ async fn notify(&self) -> Receiver<StreamId> {+ self.notifier+ .get_or_init(|| StreamNotifier::new(&self.client))+ .await+ .subscribe()+ }+}diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/manager.rs b/rust/cloud-storage/stream/src/outbound/redis/test/manager.rsnew file mode 100644index 0000000000..bab28c4bb5--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/test/manager.rs@@ -0,0 +1,533 @@+use super::util::StreamGuard;+use crate::domain::{StreamId, StreamManager, StreamManagerExt};+use crate::outbound::redis::*;+use futures::StreamExt;+use serial_test::serial;+use std::sync::Arc;+use std::time::Duration;++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_no_streams() {+ let (service, _stream_id, _guard) = StreamGuard::new("manager_no_streams").await;+ let manager = RedisStreamManager::new(service);++ let mut stream = manager+ .subscribe("sender_1".into(), "entity_1".into())+ .await+ .expect("subscribe should succeed");++ // No messages should be received since there are no streams+ let result = tokio::time::timeout(Duration::from_millis(100), stream.next()).await;+ assert!(result.is_err(), "should timeout with no messages");+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_sub_then_start_related() {+ let entity_id = "manager_sub_then_start";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;+ let manager = RedisStreamManager::new(service.clone());++ let mut stream = manager+ .subscribe("sender_1".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Now create a stream by appending to it+ let item = serde_json::json!({"message": "hello from stream"});+ service+ .append(&stream_id, item.clone())+ .await+ .expect("append should succeed");++ // The subscriber should receive the item via the notification mechanism+ let received = tokio::time::timeout(Duration::from_secs(2), stream.next())+ .await+ .expect("should receive message")+ .expect("stream should not be closed");++ assert_eq!(received.payload, item);+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_sub_then_start_unrelated() {+ let (service, stream_id, _guard) = StreamGuard::new("manager_unrelated_entity").await;+ let manager = RedisStreamManager::new(service.clone());++ let mut stream = manager+ .subscribe("sender_1".into(), "different_entity".into())+ .await+ .expect("subscribe should succeed");++ tokio::time::sleep(Duration::from_millis(50)).await;++ // Create a stream on a different entity than we subscribed to+ let item = serde_json::json!({"message": "should not receive"});+ service+ .append(&stream_id, item)+ .await+ .expect("append should succeed");++ // Subscriber should NOT receive anything+ let result = tokio::time::timeout(Duration::from_millis(500), stream.next()).await;+ assert!(+ result.is_err(),+ "should timeout - no messages for unrelated entity"+ );+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_start_then_sub() {+ let entity_id = "manager_start_then_sub";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;++ // Create the stream and add items BEFORE subscribing+ let item1 = serde_json::json!({"message": "first"});+ let item2 = serde_json::json!({"message": "second"});++ service+ .append(&stream_id, item1.clone())+ .await+ .expect("append should succeed");+ service+ .append(&stream_id, item2.clone())+ .await+ .expect("append should succeed");++ // Now create manager and subscribe+ let manager = RedisStreamManager::new(service.clone());++ let mut stream = manager+ .subscribe("sender_1".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Should receive both items that were already in the stream+ let received1 = tokio::time::timeout(Duration::from_secs(2), stream.next())+ .await+ .expect("should receive first message")+ .expect("stream should not be closed");+ assert_eq!(received1.payload, item1);++ let received2 = tokio::time::timeout(Duration::from_secs(2), stream.next())+ .await+ .expect("should receive second message")+ .expect("stream should not be closed");+ assert_eq!(received2.payload, item2);+}++// =============================================================================+// Late join tests+// =============================================================================++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_late_join_multiple_streams_same_entity() {+ let entity_id = "late_join_multi_streams";+ let (service, stream_id_1, guard) = StreamGuard::new(entity_id).await;++ // Create a second stream for the same entity+ let stream_id_2 = StreamId {+ entity_id: entity_id.into(),+ entity_type: model_entity::EntityType::Chat,+ stream_id: format!("{}_stream_2", entity_id),+ };+ guard.add_stream_id(stream_id_2.clone());++ // Add items to first stream+ service+ .append(&stream_id_1, serde_json::json!({"stream": 1, "seq": 1}))+ .await+ .expect("append should succeed");+ service+ .append(&stream_id_1, serde_json::json!({"stream": 1, "seq": 2}))+ .await+ .expect("append should succeed");++ // Add items to second stream+ service+ .append(&stream_id_2, serde_json::json!({"stream": 2, "seq": 1}))+ .await+ .expect("append should succeed");+ service+ .append(&stream_id_2, serde_json::json!({"stream": 2, "seq": 2}))+ .await+ .expect("append should succeed");++ // Late join - subscribe after both streams have data+ let manager = RedisStreamManager::new(service.clone());++ let mut stream = manager+ .subscribe("sender_1".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Collect all received items+ let mut received = Vec::new();+ while let Ok(Some(item)) = tokio::time::timeout(Duration::from_millis(500), stream.next()).await+ {+ received.push(item.payload.clone());+ }++ // Should receive items from both streams (4 total)+ assert_eq!(+ received.len(),+ 4,+ "should receive all items from both streams"+ );++ // Count items per stream+ let stream1_count = received.iter().filter(|i| i["stream"] == 1).count();+ let stream2_count = received.iter().filter(|i| i["stream"] == 2).count();++ assert_eq!(stream1_count, 2, "should get 2 items from stream 1");+ assert_eq!(stream2_count, 2, "should get 2 items from stream 2");+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_late_join_during_active_streaming() {+ let entity_id = "late_join_active";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;++ // Add initial items before any subscriber+ service+ .append(&stream_id, serde_json::json!({"phase": "before", "seq": 1}))+ .await+ .expect("append should succeed");+ service+ .append(&stream_id, serde_json::json!({"phase": "before", "seq": 2}))+ .await+ .expect("append should succeed");++ let manager = RedisStreamManager::new(service.clone());++ // First subscriber joins+ let mut stream1 = manager+ .subscribe("sender_1".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Wait for first subscriber to get initial items+ tokio::time::sleep(Duration::from_millis(100)).await;++ // Add more items while first subscriber is connected+ service+ .append(&stream_id, serde_json::json!({"phase": "during", "seq": 3}))+ .await+ .expect("append should succeed");++ // Second subscriber joins mid-stream+ let mut stream2 = manager+ .subscribe("sender_2".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Add more items after second subscriber+ service+ .append(&stream_id, serde_json::json!({"phase": "after", "seq": 4}))+ .await+ .expect("append should succeed");+ service+ .append(&stream_id, serde_json::json!({"phase": "after", "seq": 5}))+ .await+ .expect("append should succeed");++ // Collect items from both streams+ async fn collect_items(stream: &mut crate::domain::ItemStream) -> Vec<serde_json::Value> {+ let mut received = Vec::new();+ while let Ok(Some(item)) =+ tokio::time::timeout(Duration::from_millis(500), stream.next()).await+ {+ received.push(item.payload.clone());+ }+ received+ }++ let early_received = collect_items(&mut stream1).await;+ let late_received = collect_items(&mut stream2).await;++ // First subscriber should get all 5 items+ assert_eq!(+ early_received.len(),+ 5,+ "early subscriber should get all 5 items"+ );++ // Second subscriber should also get all 5 items (stream_from_beginning)+ assert_eq!(+ late_received.len(),+ 5,+ "late subscriber should get all 5 items from beginning"+ );++ // Verify late subscriber got items in correct order+ for (i, item) in late_received.iter().enumerate() {+ assert_eq!(+ item["seq"],+ i + 1,+ "late subscriber items should be in order"+ );+ }+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_unsub_during_stream() {+ let entity_id = "manager_unsub_during";+ let sender_id = "sender_unsub";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;+ let manager = RedisStreamManager::new(service.clone());++ // Create stream with initial item+ let item1 = serde_json::json!({"seq": 1});+ service+ .append(&stream_id, item1.clone())+ .await+ .expect("append should succeed");++ let mut stream = manager+ .subscribe(sender_id.into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Receive first item+ let received = tokio::time::timeout(Duration::from_secs(2), stream.next())+ .await+ .expect("should receive message")+ .expect("stream should not be closed");+ assert_eq!(received.payload, item1);++ // Unsubscribe via the manager+ manager+ .unsubscribe(sender_id.into())+ .await+ .expect("unsubscribe should succeed");++ // Stream should terminate+ let result = tokio::time::timeout(Duration::from_millis(500), stream.next()).await;+ assert!(+ matches!(result, Ok(None)),+ "stream should end after unsubscribe"+ );++ // Append more items — should not panic+ service+ .append(&stream_id, serde_json::json!({"seq": 2}))+ .await+ .expect("append should succeed");+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_unsub_no_items_after() {+ let entity_id = "manager_unsub_no_items_after";+ let sender_id = "sender_unsub_no_items";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;+ let manager = RedisStreamManager::new(service.clone());++ service+ .append(&stream_id, serde_json::json!({"seq": 1}))+ .await+ .expect("append should succeed");++ let mut stream = manager+ .subscribe(sender_id.into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Confirm subscription is live+ let received = tokio::time::timeout(Duration::from_secs(2), stream.next())+ .await+ .expect("should receive message")+ .expect("stream should not be closed");+ assert_eq!(received.payload, serde_json::json!({"seq": 1}));++ // Unsubscribe+ manager+ .unsubscribe(sender_id.into())+ .await+ .expect("unsubscribe should succeed");++ // Stream must yield None (terminated)+ let terminated = tokio::time::timeout(Duration::from_secs(2), stream.next())+ .await+ .expect("stream should resolve, not hang");+ assert!(terminated.is_none(), "stream should end after unsubscribe");++ // Append items *after* the stream has ended+ for i in 2..=10 {+ service+ .append(&stream_id, serde_json::json!({"seq": i}))+ .await+ .expect("append should succeed");+ }++ // Drain anything remaining — nothing should come through+ let mut leaked = Vec::new();+ while let Ok(Some(item)) = tokio::time::timeout(Duration::from_millis(500), stream.next()).await+ {+ leaked.push(item.payload);+ }+ assert!(+ leaked.is_empty(),+ "no items should arrive after unsubscribe, but got: {leaked:?}"+ );+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_connection_closed() {+ // Unsubscribing and re-subscribing should work fine++ let entity_id = "manager_connection_closed";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;+ let manager = RedisStreamManager::new(service.clone());++ // Subscribe and immediately unsubscribe+ let _stream = manager+ .subscribe("sender_1".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");+ manager+ .unsubscribe("sender_1".into())+ .await+ .expect("unsubscribe should succeed");++ // Append data+ service+ .append(&stream_id, serde_json::json!({"test": "data"}))+ .await+ .expect("append should succeed");++ tokio::time::sleep(Duration::from_millis(100)).await;++ // Re-subscribe should work+ let mut stream2 = manager+ .subscribe("sender_2".into(), entity_id.into())+ .await+ .expect("new subscribe should succeed");++ // Should receive the item from stream_from_beginning+ let received = tokio::time::timeout(Duration::from_secs(2), stream2.next())+ .await+ .expect("should receive message")+ .expect("stream should not be closed");++ assert_eq!(received.payload, serde_json::json!({"test": "data"}));+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_stream_ends_close() {+ // Stream emits items then closes — all items should be received++ let entity_id = "state_stream_ends";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;++ // Create stream first+ service+ .append(&stream_id, serde_json::json!({"seq": 1}))+ .await+ .expect("append should succeed");++ let manager = RedisStreamManager::new(service.clone());++ let mut stream = manager+ .subscribe("sender_1".into(), entity_id.into())+ .await+ .expect("subscribe should succeed");++ // Emit more items+ service+ .append(&stream_id, serde_json::json!({"seq": 2}))+ .await+ .expect("append should succeed");+ service+ .append(&stream_id, serde_json::json!({"seq": 3}))+ .await+ .expect("append should succeed");++ // End the stream+ service+ .close(&stream_id)+ .await+ .expect("close should succeed");++ // Drain and count+ let mut count = 0;+ while let Ok(Some(_)) = tokio::time::timeout(Duration::from_millis(500), stream.next()).await {+ count += 1;+ }++ assert_eq!(count, 3, "should receive all 3 items");+}++async fn util_test_stream_exhausted(+ stream_id: StreamId,+ service: Arc<dyn crate::domain::StreamRepo>,+) {+ let entity_id = stream_id.entity_id.clone();++ let manager = RedisStreamManager::new(service.clone());++ let mut stream = manager+ .subscribe(entity_id.clone(), entity_id.clone())+ .await+ .expect("subscribe should succeed");++ // Create a finite stream with 3 items using from_async_stream+ let items: Vec<serde_json::Value> = (1..=3).map(|i| serde_json::json!({"seq": i})).collect();+ let input_stream = futures::stream::iter(items.clone());++ service.from_async_stream(stream_id.clone(), Box::pin(input_stream), None);++ let mut count = 0;+ while let Ok(Some(_)) = tokio::time::timeout(Duration::from_millis(1000), stream.next()).await {+ count += 1;+ }+ assert_eq!(count, 3, "should receive all 3 items");+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_stream_exhausted_single() {+ let entity_id = "state_stream_exhausted_single";+ let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;+ util_test_stream_exhausted(stream_id, service).await;+}++#[tokio::test(flavor = "multi_thread")]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_stream_exhausted_load() {+ let (service, _, guard) = StreamGuard::new("load_test_init").await;++ let tests = (0..50).map(|i| {+ let id = format!("exaust_load_{}", i);+ let stream_id = StreamId {+ entity_id: id.clone(),+ entity_type: model_entity::EntityType::Chat,+ stream_id: id.clone(),+ };+ guard.add_stream_id(stream_id.clone());++ util_test_stream_exhausted(stream_id, service.clone())+ });++ futures::future::join_all(tests).await;+}diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/mod.rs b/rust/cloud-storage/stream/src/outbound/redis/test/mod.rsnew file mode 100644index 0000000000..66dcf927ed--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/test/mod.rs@@ -0,0 +1,3 @@+mod manager;+mod repo;+mod util;diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/repo.rs b/rust/cloud-storage/stream/src/outbound/redis/test/repo.rsnew file mode 100644index 0000000000..599ae2a9a8--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/test/repo.rs@@ -0,0 +1,233 @@+use super::util::StreamGuard;+use crate::domain::StreamManagerExt;+use futures::StreamExt;+use serial_test::serial;+use std::time::Duration;++/// Integration test for RedisStreamService - requires a running Redis instance.+/// Run with: REDIS_URL=redis://localhost:6379 cargo test -p stream -- --ignored+#[tokio::test]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_redis_stream_service_append_and_read() {+ let (service, stream_id, _guard) = StreamGuard::new("append_and_read").await;++ let item1 = serde_json::json!({"message": "hello", "count": 1});+ let item2 = serde_json::json!({"message": "world", "count": 2});++ service+ .append(&stream_id, item1.clone())+ .await+ .expect("Failed to append item1");++ service+ .append(&stream_id, item2.clone())+ .await+ .expect("Failed to append item2");++ service+ .close(&stream_id)+ .await+ .expect("failed to close stream");++ // Read items back from the stream+ let mut stream = service+ .stream_from_beginning(&stream_id)+ .await+ .expect("Failed to create stream");++ let timeout = Duration::from_secs(5);+ let received1 = tokio::time::timeout(timeout, stream.next())+ .await+ .expect("Timeout waiting for item1")+ .expect("Stream ended unexpectedly");++ let received2 = tokio::time::timeout(timeout, stream.next())+ .await+ .expect("Timeout waiting for item2")+ .expect("Stream ended unexpectedly");++ let end = tokio::time::timeout(timeout, stream.next())+ .await+ .expect("Timed out waiting for end");++ assert_eq!(received1.payload, item1);+ assert_eq!(received2.payload, item2);+ assert_eq!(received1.id, stream_id);+ assert_eq!(received2.id, stream_id);+ assert!(end.is_none());+}++#[tokio::test]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_from_async_stream() {+ // Use StreamGuard for cleanup, but get the concrete service for extension trait+ let (service, stream_id, _guard) = StreamGuard::new("from_async_stream").await;++ let items = (1..=5)+ .map(|i| serde_json::json!({"index": i}))+ .collect::<Vec<_>>();++ let input_stream = futures::stream::iter(items.clone());+ service+ .clone()+ .from_async_stream(stream_id.clone(), Box::pin(input_stream), None);++ let mut output_stream = service+ .stream_from_beginning(&stream_id)+ .await+ .expect("Failed to create stream");++ let timeout = Duration::from_secs(5);+ for (i, expected) in items.iter().enumerate() {+ let received = tokio::time::timeout(timeout, output_stream.next())+ .await+ .unwrap_or_else(|_| panic!("Timeout waiting for item {}", i + 1))+ .unwrap_or_else(|| panic!("Stream ended unexpectedly at item {}", i + 1));+ assert_eq!(&received.payload, expected, "Mismatch at item {}", i + 1);+ }++ let end = tokio::time::timeout(timeout, output_stream.next())+ .await+ .expect("Timeout waiting for stream end");+ assert!(end.is_none(), "Expected stream to be closed after 5 items");+}++#[tokio::test]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_notify_on_multiple_new_streams() {+ let (_, stream_id1, _guard1) = StreamGuard::new("notify_multi_1").await;+ let (service, stream_id2, _guard2) = StreamGuard::new("notify_multi_2").await;++ let mut notify = service.notify().await;+ let timeout = Duration::from_millis(500);++ // First stream creation - should notify+ service+ .append(&stream_id1, serde_json::json!({"stream": 1}))+ .await+ .expect("Failed to append to stream 1");++ let notified = tokio::time::timeout(timeout, notify.recv())+ .await+ .expect("Timeout waiting for notification on first stream")+ .expect("Notify channel closed");+ assert_eq!(notified.entity_id, stream_id1.entity_id);++ // Second stream creation - should notify+ service+ .append(&stream_id2, serde_json::json!({"stream": 2}))+ .await+ .expect("Failed to append to stream 2");++ let notified = tokio::time::timeout(timeout, notify.recv())+ .await+ .expect("Timeout waiting for notification on second stream")+ .expect("Notify channel closed");+ assert_eq!(notified.entity_id, stream_id2.entity_id);+}++#[tokio::test]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_notify_only_on_new_stream() {+ let (service, stream_id, _guard) = StreamGuard::new("notify_test").await;++ let mut notify = service.notify().await;++ // First append creates a new stream - should notify+ service+ .append(&stream_id, serde_json::json!({"item": 1}))+ .await+ .expect("Failed to append first item");++ let timeout = Duration::from_millis(500);+ let notified_id = tokio::time::timeout(timeout, notify.recv())+ .await+ .expect("Timeout waiting for notification on new stream")+ .expect("Notify channel closed");+ assert_eq!(notified_id.entity_id, stream_id.entity_id);+ assert_eq!(notified_id.stream_id, stream_id.stream_id);++ // Additional appends to same stream - should NOT notify+ for i in 2..=5 {+ service+ .append(&stream_id, serde_json::json!({"item": i}))+ .await+ .unwrap_or_else(|_| panic!("Failed to append item {}", i));+ }++ let result = tokio::time::timeout(timeout, notify.recv()).await;+ assert!(+ result.is_err(),+ "Should not receive notification when appending to existing stream"+ );+}++#[tokio::test]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_active_streams() {+ let entity_id = "active_streams_test_entity";++ // Create two streams with the same entity_id but different stream_ids+ let (service, stream_id1, _guard1) =+ StreamGuard::new_with_stream_id(entity_id, "stream_a").await;+ let (_, stream_id2, _guard2) = StreamGuard::new_with_stream_id(entity_id, "stream_b").await;++ // Append to first stream+ service+ .append(&stream_id1, serde_json::json!({"test": "stream1"}))+ .await+ .expect("Failed to append to stream 1");++ // Append to second stream+ service+ .append(&stream_id2, serde_json::json!({"test": "stream2"}))+ .await+ .expect("Failed to append to stream 2");++ // Query active streams for the entity+ let active = service+ .active_streams(entity_id)+ .await+ .expect("Failed to get active streams");++ // Verify both streams are returned+ assert_eq!(active.len(), 2, "Expected 2 active streams");++ let stream_ids: Vec<&str> = active.iter().map(|s| s.stream_id.as_str()).collect();+ assert!(+ stream_ids.contains(&"stream_a"),+ "Expected stream_a in active streams"+ );+ assert!(+ stream_ids.contains(&"stream_b"),+ "Expected stream_b in active streams"+ );++ // All returned streams should have the correct entity_id+ for stream in &active {+ assert_eq!(stream.entity_id, entity_id);+ }+}++#[tokio::test]+#[serial]+#[ignore = "Redis doesn't exist in CI"]+async fn test_active_streams_empty() {+ let (service, _, _guard) = StreamGuard::new("active_streams_empty").await;++ // Query for a non-existent entity+ let active = service+ .active_streams("nonexistent_entity_12345")+ .await+ .expect("Failed to get active streams");++ assert!(+ active.is_empty(),+ "Expected no active streams for non-existent entity"+ );+}diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/util.rs b/rust/cloud-storage/stream/src/outbound/redis/test/util.rsnew file mode 100644index 0000000000..e7f5bc9cd1--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis/test/util.rs@@ -0,0 +1,77 @@+use crate::domain::{StreamId, StreamRepo};+use crate::outbound::redis::*;+use redis::Client;+use std::cell::RefCell;+use std::sync::Arc;++pub struct StreamGuard {+ pub service: RedisStreamRepo,+ stream_ids: RefCell<Vec<StreamId>>,+}++impl StreamGuard {+ pub async fn new(name: &str) -> (Arc<dyn StreamRepo>, StreamId, Self) {+ Self::new_with_stream_id(name, "stream").await+ }++ pub async fn new_with_stream_id(+ entity_id: &str,+ stream_id: &str,+ ) -> (Arc<dyn StreamRepo>, StreamId, Self) {+ let service = connect_from_env().await;+ let service_external = connect_from_env().await;+ let stream_id = test_stream_id(entity_id, stream_id);++ let guard = Self {+ service,+ stream_ids: RefCell::new(vec![stream_id.clone()]),+ };++ (service_external.obj(), stream_id, guard)+ }++ /// Add a stream ID to be cleaned up when this guard is dropped+ pub fn add_stream_id(&self, stream_id: StreamId) {+ self.stream_ids.borrow_mut().push(stream_id);+ }+}++impl Drop for StreamGuard {+ fn drop(&mut self) {+ let service = self.service.clone();+ let stream_ids = self.stream_ids.take();+ let _ = std::thread::spawn(move || {+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(async {+ for stream_id in stream_ids {+ let _ = tokio::time::timeout(+ std::time::Duration::from_millis(100),+ service.cleanup_stream(&stream_id),+ )+ .await;+ }+ });+ })+ .join();+ }+}++pub async fn connect_from_env() -> RedisStreamRepo {+ let redis_url = std::env::var("REDIS_URL").expect("redis url");+ let client = Client::open(redis_url).expect("Failed to create Redis client");+ let service = RedisStreamRepo::new(client)+ .await+ .expect("Failed to create service");+ service+}++pub fn test_stream_id(entity_id: &str, stream_id: &str) -> StreamId {+ StreamId {+ entity_type: model_entity::EntityType::Chat,+ entity_id: entity_id.into(),+ stream_id: stream_id.into(),+ }+}