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
fix(stream): correct close behavior + remove scan (#1542)
Eric Hayese0828390e44d
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 752dd7d1cd..44a7164139 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -8917,9 +8917,9 @@ dependencies = ["serde","serde_json","serial_test",+ "sqlx","thiserror 2.0.17","tokio",- "tokio-stream","tokio-test","tracing",]@@ -9364,7 +9364,6 @@ dependencies = ["futures-core","pin-project-lite","tokio",- "tokio-util",][[package]]diff --git a/rust/cloud-storage/connection_gateway/src/main.rs b/rust/cloud-storage/connection_gateway/src/main.rsindex e3dd17b77a..2129b47f5a 100644--- a/rust/cloud-storage/connection_gateway/src/main.rs+++ b/rust/cloud-storage/connection_gateway/src/main.rs@@ -30,7 +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 stream::outbound::redis_pg::{RedisPostgresStreamManager, RedisPostgresStreamRepo};use tower_http::cors::CorsLayer;env_var!(@@ -86,11 +86,6 @@ 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)@@ -104,6 +99,9 @@ async fn main() -> Result<()> {).await?;+ let stream_service = RedisPostgresStreamRepo::new((*redis_client).clone(), pgpool.clone());+ let stream_manager = RedisPostgresStreamManager::new(stream_service.obj());+let context = context::ApiContext {connection_manager,redis_client: Arc::clone(&redis_client),diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex 295327cdb0..9352c70783 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -33,7 +33,7 @@ use models_permissions::share_permission::access_level::AccessLevel;use serde::{Deserialize, Serialize};use std::fmt;use std::sync::Arc;-use stream::domain::{PayloadStream, StreamId, StreamManagerExt};+use stream::domain::{PayloadStream, StreamId, StreamRepoExt};use tokio::sync::oneshot;use utoipa::ToSchema;@@ -279,7 +279,7 @@ pub async fn send_chat_message(let stream_handle =ctx.stream_repo.clone()- .from_async_stream(durable_stream_id, payload_stream, None);+ .from_async_stream(durable_stream_id, payload_stream, None, None);// Spawn post-processing tasklet ctx_clone = ctx.clone();diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rsindex f0a6e568d6..2c42e7737b 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs@@ -18,7 +18,7 @@ use model_entity::EntityType;use serde::{Deserialize, Serialize};use std::fmt;use std::sync::Arc;-use stream::domain::{StreamId, StreamManagerExt};+use stream::domain::{StreamId, StreamRepoExt};use utoipa::ToSchema;const SIMPLE_COMPLETION_DEFAULT_MODEL: Model = Model::Claude45Haiku;@@ -220,9 +220,12 @@ pub async fn simple_completion(};// Use the extension trait to handle spawning and stream management- ctx.stream_repo- .clone()- .from_async_stream(durable_stream_id, Box::pin(payload_stream), None);+ ctx.stream_repo.clone().from_async_stream(+ durable_stream_id,+ Box::pin(payload_stream),+ None,+ None,+ );Ok(Json(SimpleCompletionResponse { completion_id }))}diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 47ea0ad0e6..fe2f4732de 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -23,7 +23,7 @@ use soup::outbound::pg_soup_repo::PgSoupRepo;use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;-use stream::outbound::redis::RedisStreamRepo;+use stream::outbound::redis_pg::RedisPostgresStreamRepo;use sync_service_client::SyncServiceClient;mod api;@@ -187,11 +187,7 @@ async fn main() -> anyhow::Result<()> {}).context("failed to connect to redis")?,);-- let stream_repo = RedisStreamRepo::new((*redis_client).clone())- .await- .context("failed to create stream repo")?- .obj();+ let stream_repo = RedisPostgresStreamRepo::new((*redis_client).clone(), db.clone()).obj();tracing::info!("initialized stream repo");diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex 19c1accf81..24160127e1 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -83,6 +83,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./channels/.envecho "DATABASE_URL={{ MACRODB }}" >> ./comms_service/.envecho "DATABASE_URL={{ MACRODB }}" >> ./documents/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./stream/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-190e13cd096c3c62e7b961892744ac0c1869938293f683c2d4c82f5b92fbd4ce.json b/rust/cloud-storage/macro_db_client/.sqlx/query-190e13cd096c3c62e7b961892744ac0c1869938293f683c2d4c82f5b92fbd4ce.jsondeleted file mode 100644index b3cfeaaeb2..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-190e13cd096c3c62e7b961892744ac0c1869938293f683c2d4c82f5b92fbd4ce.json+++ /dev/null@@ -1,27 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"ChatMessage\" (\"chatId\", \"content\", \"role\", \"model\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id;\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Jsonb",- "Text",- "Text",- "Timestamp",- "Timestamp"- ]- },- "nullable": [- false- ]- },- "hash": "190e13cd096c3c62e7b961892744ac0c1869938293f683c2d4c82f5b92fbd4ce"-}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c.jsondeleted file mode 100644index d0932f3682..0000000000--- a/rust/cloud-storage/macro_db_client/.sqlx/query-73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c.json+++ /dev/null@@ -1,27 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO \"ChatMessage\" (\"chatId\", \"content\", \"role\", \"model\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id;\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "Jsonb",- "Text",- "Text",- "Timestamp",- "Timestamp"- ]- },- "nullable": [- false- ]- },- "hash": "73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c"-}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260217194926_active_streams.sql b/rust/cloud-storage/macro_db_client/migrations/20260217194926_active_streams.sqlnew file mode 100644index 0000000000..219de019e3--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260217194926_active_streams.sql@@ -0,0 +1,5 @@+CREATE TABLE IF NOT EXISTS active_streams (+ entity_id TEXT NOT NULL,+ stream_key TEXT NOT NULL,+ PRIMARY KEY (entity_id, stream_key)+);diff --git a/rust/cloud-storage/stream/Cargo.toml b/rust/cloud-storage/stream/Cargo.tomlindex 2b9919367e..2ce4e7ad97 100644--- a/rust/cloud-storage/stream/Cargo.toml+++ b/rust/cloud-storage/stream/Cargo.toml@@ -10,8 +10,7 @@ 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"] }+tokio = { version = "1", features = ["sync", "rt", "macros", "time"] }thiserror = { workspace = true }futures = { workspace = true }tracing = { workspace = true }@@ -26,6 +25,7 @@ async-stream = { workspace = true }model-entity = { path = "../model-entity" }anyhow = { workspace = true }dashmap = { workspace = true }+sqlx = { workspace = true }[dev-dependencies]tokio = { version = "1", features = ["rt-multi-thread", "macros"] }diff --git a/rust/cloud-storage/stream/src/bin/stream_stdin.rs b/rust/cloud-storage/stream/src/bin/stream_stdin.rsindex 873c766695..5b4bb65d31 100644--- a/rust/cloud-storage/stream/src/bin/stream_stdin.rs+++ b/rust/cloud-storage/stream/src/bin/stream_stdin.rs@@ -1,7 +1,7 @@use model_entity::EntityType;use std::io::{self, BufRead};use stream::domain::StreamId;-use stream::outbound::redis::RedisStreamRepo;+use stream::outbound::redis_pg::RedisPostgresStreamRepo;const ENTITY_TYPE: EntityType = EntityType::Channel;// battlefield channel@@ -9,9 +9,11 @@ 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")+ let redis_url = std::env::var("DBURL").or_else(|_| std::env::var("REDIS_URL")).unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string());+ let database_url = std::env::var("DATABASE_URL")+ .unwrap_or_else(|_| "postgres://localhost/macrodb".to_string());let rt = tokio::runtime::Builder::new_current_thread().enable_all()@@ -24,8 +26,9 @@ fn main() -> anyhow::Result<()> {};rt.block_on(async move {- let client = redis::Client::open(db_url)?;- let service = RedisStreamRepo::new(client).await?;+ let client = redis::Client::open(redis_url)?;+ let pool = sqlx::PgPool::connect(&database_url).await?;+ let service = RedisPostgresStreamRepo::new(client, pool);let _ = service.cleanup_stream(&stream_id).await;let stream_service = service.obj();diff --git a/rust/cloud-storage/stream/src/domain/ext.rs b/rust/cloud-storage/stream/src/domain/ext.rsindex e51e22e38a..fc046dd2d8 100644--- a/rust/cloud-storage/stream/src/domain/ext.rs+++ b/rust/cloud-storage/stream/src/domain/ext.rs@@ -6,46 +6,59 @@ use futures::StreamExt;use std::sync::Arc;use std::time::Duration;-pub trait StreamManagerExt: StreamRepo {+const DEFAULT_CLOSE_DELAY: std::time::Duration = std::time::Duration::from_secs(60);++pub trait StreamRepoExt: StreamRepo {/// Create a durable stream from an async stream./// Consumes the async stream and closes the durable stream when it ends.+ /// If `close_delay` is provided, waits that duration before closing.fn from_async_stream(self: Arc<Self>,id: StreamId,stream: PayloadStream,timeout: Option<Duration>,+ close_delay: Option<Duration>,) -> tokio::task::JoinHandle<()>;}-impl<S> StreamManagerExt for S+impl<S> StreamRepoExt for SwhereS: StreamRepo + ?Sized,{- /// Create a durable stream from an async stream- /// Consume async stream and close the durable stream when it ends+ /// Create a durable stream from an async stream.+ /// Consume async stream and close the durable stream when it ends.+ /// If `close_delay` is provided, waits that duration before closing.fn from_async_stream(self: Arc<Self>,id: StreamId,mut stream: PayloadStream,timeout: Option<Duration>,+ close_delay: 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 writer = self.clone();+ let writer_id = id.clone();+ tokio::spawn(async move {+ let consumed =+ tokio::time::timeout(timeout.unwrap_or(DEFAULT_STREAM_TIMEOUT), async move {+ while let Some(payload) = stream.next().await {+ if let Err(e) = writer.append(&writer_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"));+ }+ })+ .await;++ if consumed.is_ok() {+ tokio::time::sleep(close_delay.unwrap_or(DEFAULT_CLOSE_DELAY)).await;+ } else {+ tracing::error!("stream timed out");}++ let _ = self+ .close(&id)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to mark stream as closed"));})}}diff --git a/rust/cloud-storage/stream/src/domain/traits.rs b/rust/cloud-storage/stream/src/domain/traits.rsindex 452cb94b23..fa0d41a7df 100644--- a/rust/cloud-storage/stream/src/domain/traits.rs+++ b/rust/cloud-storage/stream/src/domain/traits.rs@@ -16,12 +16,6 @@ pub type ItemStream = Pin<Box<dyn Stream<Item = StreamItem> + Send>>;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 StreamManagerdiff --git a/rust/cloud-storage/stream/src/outbound/mod.rs b/rust/cloud-storage/stream/src/outbound/mod.rsindex 027fbef58d..858cbad431 100644--- a/rust/cloud-storage/stream/src/outbound/mod.rs+++ b/rust/cloud-storage/stream/src/outbound/mod.rs@@ -1 +1 @@-pub mod redis;+pub mod redis_pg;diff --git a/rust/cloud-storage/stream/src/outbound/redis/ext.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/ext.rssimilarity index 100%rename from rust/cloud-storage/stream/src/outbound/redis/ext.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/ext.rsdiff --git a/rust/cloud-storage/stream/src/outbound/redis/manager.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/manager.rssimilarity index 93%rename from rust/cloud-storage/stream/src/outbound/redis/manager.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/manager.rsindex e772a9d963..c760dfba02 100644--- a/rust/cloud-storage/stream/src/outbound/redis/manager.rs+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/manager.rs@@ -6,13 +6,13 @@ use futures::stream::{SelectAll, StreamExt};use std::sync::Arc;use tokio::sync::oneshot;-/// Manages stream subscriptions backed by Redis.-pub struct RedisStreamManager {+/// Manages stream subscriptions backed by Redis and PostgreSQL.+pub struct RedisPostgresStreamManager {repo: Arc<dyn StreamRepo>,subscriptions: DashMap<String, oneshot::Sender<()>>,}-impl RedisStreamManager {+impl RedisPostgresStreamManager {/// Create a new manager wrapping the given repo.pub fn new(repo: Arc<dyn StreamRepo>) -> Arc<Self> {Arc::new(Self {@@ -23,7 +23,7 @@ impl RedisStreamManager {}#[async_trait]-impl StreamManager for RedisStreamManager {+impl StreamManager for RedisPostgresStreamManager {#[tracing::instrument(err, skip(self))]async fn subscribe(&self, sender_id: String, entity_id: String) -> Result<ItemStream> {let repo = self.repo.clone();diff --git a/rust/cloud-storage/stream/src/outbound/redis/mod.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/mod.rssimilarity index 90%rename from rust/cloud-storage/stream/src/outbound/redis/mod.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/mod.rsindex 888b4ed517..897dbd0dd7 100644--- a/rust/cloud-storage/stream/src/outbound/redis/mod.rs+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/mod.rs@@ -1,5 +1,6 @@mod ext;mod manager;+mod queries;mod repo;#[cfg(test)]diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rsnew file mode 100644index 0000000000..e373cacdd0--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/mod.rs@@ -0,0 +1,47 @@+#[cfg(test)]+mod test;++use sqlx::PgPool;++/// Insert a new active stream entry, ignoring conflicts.+pub(crate) async fn insert_active_stream(+ pool: &PgPool,+ entity_id: &str,+ stream_key: &str,+) -> Result<(), sqlx::Error> {+ sqlx::query(+ "INSERT INTO active_streams (entity_id, stream_key) VALUES ($1, $2) ON CONFLICT DO NOTHING",+ )+ .bind(entity_id)+ .bind(stream_key)+ .execute(pool)+ .await?;+ Ok(())+}++/// Delete an active stream entry.+pub(crate) async fn delete_active_stream(+ pool: &PgPool,+ entity_id: &str,+ stream_key: &str,+) -> Result<(), sqlx::Error> {+ sqlx::query("DELETE FROM active_streams WHERE entity_id = $1 AND stream_key = $2")+ .bind(entity_id)+ .bind(stream_key)+ .execute(pool)+ .await?;+ Ok(())+}++/// Get all stream keys for a given entity.+pub(crate) async fn get_active_stream_keys(+ pool: &PgPool,+ entity_id: &str,+) -> Result<Vec<String>, sqlx::Error> {+ let rows: Vec<(String,)> =+ sqlx::query_as("SELECT stream_key FROM active_streams WHERE entity_id = $1")+ .bind(entity_id)+ .fetch_all(pool)+ .await?;+ Ok(rows.into_iter().map(|(key,)| key).collect())+}diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rsnew file mode 100644index 0000000000..e398beb9e1--- /dev/null+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/queries/test.rs@@ -0,0 +1,113 @@+use super::*;+use sqlx::PgPool;++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_insert_and_get(pool: PgPool) {+ insert_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();+ insert_active_stream(&pool, "entity_1", "stream_b")+ .await+ .unwrap();++ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert_eq!(keys.len(), 2);+ assert!(keys.contains(&"stream_a".to_string()));+ assert!(keys.contains(&"stream_b".to_string()));+}++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_insert_conflict_is_noop(pool: PgPool) {+ insert_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();+ // Duplicate insert should succeed (ON CONFLICT DO NOTHING)+ insert_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();++ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert_eq!(keys.len(), 1);+}++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_delete(pool: PgPool) {+ insert_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();+ insert_active_stream(&pool, "entity_1", "stream_b")+ .await+ .unwrap();++ delete_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();++ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert_eq!(keys, vec!["stream_b".to_string()]);+}++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_delete_nonexistent_is_noop(pool: PgPool) {+ delete_active_stream(&pool, "entity_1", "does_not_exist")+ .await+ .unwrap();+}++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_get_empty(pool: PgPool) {+ let keys = get_active_stream_keys(&pool, "no_such_entity")+ .await+ .unwrap();+ assert!(keys.is_empty());+}++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_get_filters_by_entity(pool: PgPool) {+ insert_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();+ insert_active_stream(&pool, "entity_2", "stream_b")+ .await+ .unwrap();++ let keys_1 = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert_eq!(keys_1, vec!["stream_a".to_string()]);++ let keys_2 = get_active_stream_keys(&pool, "entity_2").await.unwrap();+ assert_eq!(keys_2, vec!["stream_b".to_string()]);+}++#[sqlx::test(migrations = "../macro_db_client/migrations")]+async fn test_full_lifecycle(pool: PgPool) {+ // Start empty+ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert!(keys.is_empty());++ // Insert two streams+ insert_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();+ insert_active_stream(&pool, "entity_1", "stream_b")+ .await+ .unwrap();++ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert_eq!(keys.len(), 2);++ // Close one stream+ delete_active_stream(&pool, "entity_1", "stream_a")+ .await+ .unwrap();++ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert_eq!(keys, vec!["stream_b".to_string()]);++ // Close the other+ delete_active_stream(&pool, "entity_1", "stream_b")+ .await+ .unwrap();++ let keys = get_active_stream_keys(&pool, "entity_1").await.unwrap();+ assert!(keys.is_empty());+}diff --git a/rust/cloud-storage/stream/src/outbound/redis/repo.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rssimilarity index 72%rename from rust/cloud-storage/stream/src/outbound/redis/repo.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/repo.rsindex 7384bee0d8..d321219808 100644--- a/rust/cloud-storage/stream/src/outbound/redis/repo.rs+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs@@ -11,6 +11,8 @@ use tokio::task::JoinHandle;const NOTIFY_CHANNEL: &str = "stream:notifications";const NOTIFY_CHANNEL_BUFFER: usize = 1024;+/// TTL for a closed stream in Redis (60 seconds for consumers to finish reading)+const CLOSED_STREAM_TTL_SECS: i64 = 60;#[derive(Serialize, Deserialize)]#[serde(tag = "type", content = "value")]@@ -83,10 +85,12 @@ impl Drop for StreamNotifier {}}-/// Redis-backed stream service using Redis Streams for storage and Pub/Sub for notifications.+/// Redis + PostgreSQL backed stream service using Redis Streams for storage,+/// Pub/Sub for notifications, and PostgreSQL for active stream tracking.#[derive(Clone)]-pub struct RedisStreamRepo {- client: Arc<Client>,+pub struct RedisPostgresStreamRepo {+ redis_client: Arc<Client>,+ pg_pool: sqlx::PgPool,notifier: Arc<OnceCell<StreamNotifier>>,}@@ -94,27 +98,38 @@ pub struct RedisStreamRepo {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),+impl RedisPostgresStreamRepo {+ /// Create a new Redis + PostgreSQL stream service.+ /// The `active_streams` table must already exist (created via macro_db_client migration).+ pub fn new(redis_client: Client, pg_pool: sqlx::PgPool) -> Self {+ Self {+ redis_client: Arc::new(redis_client),+ pg_pool,notifier: Arc::new(OnceCell::new()),- })+ }}+ /// Wrap self in an `Arc<dyn StreamRepo>`.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+ /// Delete stream data from redis and postgres.+ /// 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())+ let mut conn = self.redis_client.get_multiplexed_async_connection().await?;+ let _: () = conn+ .del(id.to_string()).await- .map_err(|e| StreamServiceError::StorageError(e.to_string()))+ .map_err(|e| StreamServiceError::StorageError(e.to_string()))?;++ // Also clean up PostgreSQL entry+ let _ = super::queries::delete_active_stream(&self.pg_pool, &id.entity_id, &id.to_string())+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to clean stream from postgres"));++ Ok(())}async fn publish_item(@@ -130,10 +145,10 @@ impl RedisStreamRepo {}#[async_trait]-impl StreamRepo for RedisStreamRepo {- /// create and append to stream or append to stream+impl StreamRepo for RedisPostgresStreamRepo {+ /// Create and append to stream or append to an existing stream.async fn append(&self, id: &StreamId, payload: serde_json::Value) -> Result<ItemId> {- let mut conn = self.client.get_multiplexed_async_connection().await?;+ let mut conn = self.redis_client.get_multiplexed_async_connection().await?;let is_new: bool = !conn.exists(id.to_string())@@ -142,6 +157,12 @@ impl StreamRepo for RedisStreamRepo {let item_id = Self::publish_item(&mut conn, id, &StoredStreamItem::Value(payload)).await?;+ // Refresh TTL on every append so stream stays alive while being written to+ let _: RedisResult<()> = conn+ .expire(id.to_string(), DEFAULT_STREAM_TIMEOUT.as_secs() as i64)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to set stream TTL"));+if is_new {tracing::debug!(stream_id=?id, "New stream detected publishing notification");let notification = serde_json::to_string(id).expect("json");@@ -149,13 +170,21 @@ impl StreamRepo for RedisStreamRepo {.publish(NOTIFY_CHANNEL, notification).await.inspect_err(|e| tracing::error!(error=?e, "failed to publish new channel"));++ // Track in PostgreSQL+ let _ =+ super::queries::insert_active_stream(&self.pg_pool, &id.entity_id, &id.to_string())+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to track stream in postgres"),+ );}Ok(item_id)}async fn stream_from_beginning(&self, id: &StreamId) -> Result<ItemStream> {- let mut connection = self.client.get_multiplexed_async_connection().await?;+ let mut connection = self.redis_client.get_multiplexed_async_connection().await?;let stream_key = id.to_string();let stream_id_for_item = id.clone();@@ -215,28 +244,35 @@ impl StreamRepo for RedisStreamRepo {}async fn close(&self, id: &StreamId) -> Result<()> {- let mut conn = self.client.get_multiplexed_async_connection().await?;+ let mut conn = self.redis_client.get_multiplexed_async_connection().await?;Self::publish_item(&mut conn, id, &StoredStreamItem::End).await?;++ let _: RedisResult<()> = conn+ .expire(id.to_string(), CLOSED_STREAM_TTL_SECS)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to set closed stream TTL"));++ // Remove from PostgreSQL tracking+ let _ = super::queries::delete_active_stream(&self.pg_pool, &id.entity_id, &id.to_string())+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to remove stream from postgres"));+Ok(())}- //TODO: this does a scan. this should be replaced with a dynamo or somethingasync 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+ super::queries::get_active_stream_keys(&self.pg_pool, entity_id)+ .await+ .map_err(|e| StreamServiceError::StorageError(e.to_string()))?.into_iter()- .filter_map(|s| s.ok())- .filter_map(|s| StreamId::try_from(s).ok())- .filter(|stream_id| stream_id.entity_id == entity_id)- .collect())+ .map(StreamId::try_from)+ .collect::<Result<Vec<_>>>()+ .map_err(|e| StreamServiceError::StorageError(e.to_string()))}async fn notify(&self) -> Receiver<StreamId> {self.notifier- .get_or_init(|| StreamNotifier::new(&self.client))+ .get_or_init(|| StreamNotifier::new(&self.redis_client)).await.subscribe()}diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/manager.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rssimilarity index 95%rename from rust/cloud-storage/stream/src/outbound/redis/test/manager.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rsindex bab28c4bb5..ceaf3afb87 100644--- a/rust/cloud-storage/stream/src/outbound/redis/test/manager.rs+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rs@@ -1,6 +1,6 @@use super::util::StreamGuard;-use crate::domain::{StreamId, StreamManager, StreamManagerExt};-use crate::outbound::redis::*;+use crate::domain::{StreamId, StreamManager, StreamRepoExt};+use crate::outbound::redis_pg::*;use futures::StreamExt;use serial_test::serial;use std::sync::Arc;@@ -11,7 +11,7 @@ use std::time::Duration;#[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 manager = RedisPostgresStreamManager::new(service);let mut stream = manager.subscribe("sender_1".into(), "entity_1".into())@@ -29,7 +29,7 @@ async fn test_no_streams() {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 manager = RedisPostgresStreamManager::new(service.clone());let mut stream = manager.subscribe("sender_1".into(), entity_id.into())@@ -57,7 +57,7 @@ async fn test_sub_then_start_related() {#[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 manager = RedisPostgresStreamManager::new(service.clone());let mut stream = manager.subscribe("sender_1".into(), "different_entity".into())@@ -102,7 +102,7 @@ async fn test_start_then_sub() {.expect("append should succeed");// Now create manager and subscribe- let manager = RedisStreamManager::new(service.clone());+ let manager = RedisPostgresStreamManager::new(service.clone());let mut stream = manager.subscribe("sender_1".into(), entity_id.into())@@ -163,7 +163,7 @@ async fn test_late_join_multiple_streams_same_entity() {.expect("append should succeed");// Late join - subscribe after both streams have data- let manager = RedisStreamManager::new(service.clone());+ let manager = RedisPostgresStreamManager::new(service.clone());let mut stream = manager.subscribe("sender_1".into(), entity_id.into())@@ -209,7 +209,7 @@ async fn test_late_join_during_active_streaming() {.await.expect("append should succeed");- let manager = RedisStreamManager::new(service.clone());+ let manager = RedisPostgresStreamManager::new(service.clone());// First subscriber joinslet mut stream1 = manager@@ -287,7 +287,7 @@ 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());+ let manager = RedisPostgresStreamManager::new(service.clone());// Create stream with initial itemlet item1 = serde_json::json!({"seq": 1});@@ -335,7 +335,7 @@ 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());+ let manager = RedisPostgresStreamManager::new(service.clone());service.append(&stream_id, serde_json::json!({"seq": 1}))@@ -394,7 +394,7 @@ async fn test_connection_closed() {let entity_id = "manager_connection_closed";let (service, stream_id, _guard) = StreamGuard::new(entity_id).await;- let manager = RedisStreamManager::new(service.clone());+ let manager = RedisPostgresStreamManager::new(service.clone());// Subscribe and immediately unsubscribelet _stream = manager@@ -444,7 +444,7 @@ async fn test_stream_ends_close() {.await.expect("append should succeed");- let manager = RedisStreamManager::new(service.clone());+ let manager = RedisPostgresStreamManager::new(service.clone());let mut stream = manager.subscribe("sender_1".into(), entity_id.into())@@ -482,7 +482,7 @@ async fn util_test_stream_exhausted() {let entity_id = stream_id.entity_id.clone();- let manager = RedisStreamManager::new(service.clone());+ let manager = RedisPostgresStreamManager::new(service.clone());let mut stream = manager.subscribe(entity_id.clone(), entity_id.clone())@@ -493,7 +493,7 @@ async fn util_test_stream_exhausted(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);+ service.from_async_stream(stream_id.clone(), Box::pin(input_stream), None, None);let mut count = 0;while let Ok(Some(_)) = tokio::time::timeout(Duration::from_millis(1000), stream.next()).await {diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/mod.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/test/mod.rssimilarity index 100%rename from rust/cloud-storage/stream/src/outbound/redis/test/mod.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/test/mod.rsdiff --git a/rust/cloud-storage/stream/src/outbound/redis/test/repo.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rssimilarity index 99%rename from rust/cloud-storage/stream/src/outbound/redis/test/repo.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rsindex 599ae2a9a8..18989e4b41 100644--- a/rust/cloud-storage/stream/src/outbound/redis/test/repo.rs+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rs@@ -1,5 +1,5 @@use super::util::StreamGuard;-use crate::domain::StreamManagerExt;+use crate::domain::StreamRepoExt;use futures::StreamExt;use serial_test::serial;use std::time::Duration;@@ -72,7 +72,7 @@ async fn test_from_async_stream() {let input_stream = futures::stream::iter(items.clone());service.clone()- .from_async_stream(stream_id.clone(), Box::pin(input_stream), None);+ .from_async_stream(stream_id.clone(), Box::pin(input_stream), None, None);let mut output_stream = service.stream_from_beginning(&stream_id)diff --git a/rust/cloud-storage/stream/src/outbound/redis/test/util.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/test/util.rssimilarity index 85%rename from rust/cloud-storage/stream/src/outbound/redis/test/util.rsrename to rust/cloud-storage/stream/src/outbound/redis_pg/test/util.rsindex e7f5bc9cd1..6f44899c8d 100644--- a/rust/cloud-storage/stream/src/outbound/redis/test/util.rs+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/test/util.rs@@ -1,11 +1,11 @@use crate::domain::{StreamId, StreamRepo};-use crate::outbound::redis::*;+use crate::outbound::redis_pg::*;use redis::Client;use std::cell::RefCell;use std::sync::Arc;pub struct StreamGuard {- pub service: RedisStreamRepo,+ pub service: RedisPostgresStreamRepo,stream_ids: RefCell<Vec<StreamId>>,}@@ -59,13 +59,14 @@ impl Drop for StreamGuard {}}-pub async fn connect_from_env() -> RedisStreamRepo {+pub async fn connect_from_env() -> RedisPostgresStreamRepo {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)+ let database_url = std::env::var("DATABASE_URL").expect("database url");+ let pool = sqlx::PgPool::connect(&database_url).await- .expect("Failed to create service");- service+ .expect("Failed to connect to postgres");+ RedisPostgresStreamRepo::new(client, pool)}pub fn test_stream_id(entity_id: &str, stream_id: &str) -> StreamId {