use std::sync::Arc;
use std::time::Duration;
use serde_json::Value;
use tokio::sync::Mutex;
use uuid::Uuid;
use super::*;
use crate::events::{Event, SessionEventEnvelope};
use crate::workstreams::WorkstreamStore;
fn unique_session_id(label: &str) -> String {
format!("{label}-{}", Uuid::new_v4())
}
async fn seeded_store(
session_ids: Vec<String>,
) -> (SharedWorkstreamStore, WorkstreamId, tempfile::TempDir) {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("workstreams-test.json");
let id = WorkstreamId::new();
let now = chrono::Utc::now();
let raw = serde_json::json!({
"version": "1.0",
"active_workstream_id": Value::Null,
"workstreams": [{
"id": id,
"name": "t",
"session_ids": session_ids,
"created_at": now,
"updated_at": now,
"metadata": {},
}],
});
tokio::fs::write(&path, serde_json::to_string_pretty(&raw).unwrap())
.await
.expect("seed raw store file");
let store = WorkstreamStore::load(&path)
.await
.expect("load seeded store");
(Arc::new(Mutex::new(store)), id, dir)
}
fn session_started(session_id: &str) -> SessionEventEnvelope {
SessionEventEnvelope::new(
session_id.to_string(),
1,
chrono::Utc::now(),
Event::SessionStarted {
session_id: session_id.to_string(),
project: "p".to_string(),
},
)
}
#[tokio::test]
async fn fan_out_tags_events_from_bound_sessions_only() {
let s1 = unique_session_id("s1");
let s2 = unique_session_id("s2");
let s3 = unique_session_id("s3"); let (store, id, _dir) = seeded_store(vec![s1.clone(), s2.clone()]).await;
let mut stream = std::pin::pin!(aggregate_live(id, store));
crate::events::publish(session_started(&s1));
crate::events::publish(session_started(&s2));
crate::events::publish(session_started(&s3));
let first = tokio::time::timeout(Duration::from_secs(2), stream.next())
.await
.expect("timed out")
.expect("stream ended early");
assert_eq!(first.session_id, s1);
assert_eq!(first.event_type, "session_started");
let second = tokio::time::timeout(Duration::from_secs(2), stream.next())
.await
.expect("timed out")
.expect("stream ended early");
assert_eq!(second.session_id, s2);
let third = tokio::time::timeout(Duration::from_millis(300), stream.next()).await;
assert!(
third.is_err(),
"an event from an unbound session must not be forwarded"
);
}
#[tokio::test]
async fn activation_changed_event_is_forwarded_regardless_of_session_binding() {
let (store, id, _dir) = seeded_store(vec![]).await;
let mut stream = std::pin::pin!(aggregate_live(id, store));
let event = Event::WorkstreamActivationChanged {
new_active_id: Some(id.to_string()),
prior_id: None,
};
crate::events::publish(SessionEventEnvelope::new(
String::new(),
0,
chrono::Utc::now(),
event,
));
let forwarded = tokio::time::timeout(Duration::from_secs(2), stream.next())
.await
.expect("timed out waiting for the activation-changed event")
.expect("stream ended early");
assert_eq!(forwarded.event_type, "workstream_activation_changed");
match forwarded.payload {
Event::WorkstreamActivationChanged { new_active_id, .. } => {
assert_eq!(new_active_id, Some(id.to_string()));
}
other => panic!("expected WorkstreamActivationChanged, got {other:?}"),
}
}
#[tokio::test]
async fn state_inferred_event_is_forwarded_for_this_workstream_only() {
let (store, id, _dir) = seeded_store(vec![]).await;
let mut stream = std::pin::pin!(aggregate_live(id, store));
let other = WorkstreamId::new();
crate::events::publish(SessionEventEnvelope::new(
String::new(),
0,
chrono::Utc::now(),
Event::WorkstreamStateInferred {
workstream_id: other.to_string(),
state: "closed".to_string(),
reason: "closed".to_string(),
},
));
crate::events::publish(SessionEventEnvelope::new(
String::new(),
0,
chrono::Utc::now(),
Event::WorkstreamStateInferred {
workstream_id: id.to_string(),
state: "idle".to_string(),
reason: "deactivated".to_string(),
},
));
let forwarded = tokio::time::timeout(Duration::from_secs(2), stream.next())
.await
.expect("timed out waiting for the state-inferred event")
.expect("stream ended early");
match forwarded.payload {
Event::WorkstreamStateInferred {
workstream_id,
state,
..
} => {
assert_eq!(workstream_id, id.to_string());
assert_eq!(state, "idle");
}
other => panic!("expected WorkstreamStateInferred, got {other:?}"),
}
}
#[tokio::test]
async fn empty_workstream_stream_yields_nothing() {
let (store, id, _dir) = seeded_store(vec![]).await;
let mut stream = std::pin::pin!(aggregate_live(id, store));
crate::events::publish(session_started(&unique_session_id("unrelated")));
let outcome = tokio::time::timeout(Duration::from_millis(300), stream.next()).await;
assert!(
outcome.is_err(),
"an empty workstream must not forward any session's events"
);
}