Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(calls): calls kafka topic (#5223)

Will Hutchinson6c7f11455f8d
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.json
index fd1d680513..7318542b84 100644
--- a/.github/kafka-cluster-topics.json
+++ b/.github/kafka-cluster-topics.json
@@ -1,5 +1,6 @@
[
"macro.bots",
+ "macro.calls",
"macro.channels",
"macro.chats",
"macro.documents",
diff --git a/.sqlx/query-444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7.json b/.sqlx/query-444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7.json
deleted file mode 100644
index 0f87a4867d..0000000000
--- a/.sqlx/query-444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT id FROM call_records WHERE egress_id = $1\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "444840cacdf181727100b5ee338de844abb56d9cb3a88034db7b285fcff7e9b7"
-}
diff --git a/.sqlx/query-7c00b4b9e2ad10c5623c11a66677744a09a7c86db747510990486b6428f3e012.json b/.sqlx/query-7c00b4b9e2ad10c5623c11a66677744a09a7c86db747510990486b6428f3e012.json
new file mode 100644
index 0000000000..95d617d3ff
--- /dev/null
+++ b/.sqlx/query-7c00b4b9e2ad10c5623c11a66677744a09a7c86db747510990486b6428f3e012.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, channel_id FROM call_records WHERE egress_id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "channel_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "7c00b4b9e2ad10c5623c11a66677744a09a7c86db747510990486b6428f3e012"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 4dae080195..d39738bb28 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2409,6 +2409,8 @@ dependencies = [
"macro_authorization",
"macro_aws_config",
"macro_db_migrator",
+ "macro_event_broker",
+ "macro_event_topics",
"macro_user_id",
"macro_uuid",
"mockall",
diff --git a/crates/call/Cargo.toml b/crates/call/Cargo.toml
index 25a6ca627d..7ef5fb5766 100644
--- a/crates/call/Cargo.toml
+++ b/crates/call/Cargo.toml
@@ -64,6 +64,8 @@ macro_authorization = { path = "../macro_authorization", optional = true, defaul
macro_aws_config = { path = "../macro_aws_config", optional = true, features = [
"s3",
] }
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model-entity = { path = "../model-entity" }
diff --git a/crates/call/src/domain/entity_mutation.rs b/crates/call/src/domain/entity_mutation.rs
index f75f452578..6696f198b5 100644
--- a/crates/call/src/domain/entity_mutation.rs
+++ b/crates/call/src/domain/entity_mutation.rs
@@ -6,6 +6,7 @@ use entity_access::domain::models::{
use entity_mutation::{
DeleteEntityPermanently, EntityMutationErrorCode, RenameEntity, UpdateEntitySharePolicy,
};
+use macro_event_broker::MacroEventBroker;
use model_entity::Entity;
use models_permissions::share_permission::UpdateSharePermissionRequestV2;
@@ -72,8 +73,8 @@ async fn require_archived_call<S: CallService>(
Ok(())
}
-impl<R, C, Cn, E, N, S, Sm, I, V, Vr> RenameEntity
- for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+impl<R, C, Cn, E, N, S, Sm, I, V, Vr, B> RenameEntity
+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>
where
R: CallRepository,
C: CallRtcClient,
@@ -85,6 +86,7 @@ where
I: CallSearchIndexer,
V: VoipPushSender,
Vr: VoiceRepository,
+ B: MacroEventBroker,
Self: CallService,
{
type Receipt = EditAccessLevel;
@@ -109,8 +111,8 @@ where
}
}
-impl<R, C, Cn, E, N, S, Sm, I, V, Vr> UpdateEntitySharePolicy
- for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+impl<R, C, Cn, E, N, S, Sm, I, V, Vr, B> UpdateEntitySharePolicy
+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>
where
R: CallRepository,
C: CallRtcClient,
@@ -122,6 +124,7 @@ where
I: CallSearchIndexer,
V: VoipPushSender,
Vr: VoiceRepository,
+ B: MacroEventBroker,
Self: CallService,
{
type Receipt = EditAccessLevel;
@@ -146,8 +149,8 @@ where
}
}
-impl<R, C, Cn, E, N, S, Sm, I, V, Vr> DeleteEntityPermanently
- for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+impl<R, C, Cn, E, N, S, Sm, I, V, Vr, B> DeleteEntityPermanently
+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>
where
R: CallRepository,
C: CallRtcClient,
@@ -159,6 +162,7 @@ where
I: CallSearchIndexer,
V: VoipPushSender,
Vr: VoiceRepository,
+ B: MacroEventBroker,
Self: CallService,
{
type Receipt = EditAccessLevel;
diff --git a/crates/call/src/domain/events.rs b/crates/call/src/domain/events.rs
new file mode 100644
index 0000000000..b43b5e8740
--- /dev/null
+++ b/crates/call/src/domain/events.rs
@@ -0,0 +1,207 @@
+//! Kafka event models for the `macro.calls` topic.
+//!
+//! Event payloads deliberately exclude transcript and summary text, recording
+//! locations, and share-permission objects. Consumers can fetch protected call
+//! content through authorized APIs using the published identifiers.
+
+#[cfg(test)]
+mod test;
+
+use chrono::{DateTime, Utc};
+use macro_event_broker::{Event, MacroEvent, TopicEvent};
+use macro_event_topics::MacroCallsTopic;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Metadata for [`CallTopicEvent::Started`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallStartedMetadata {
+ /// Identifier of the started call.
+ pub call_id: Uuid,
+ /// Identifier of the channel containing the call.
+ pub channel_id: Uuid,
+ /// User who created the call.
+ pub created_by: MacroUserIdStr<'static>,
+ /// Time at which the call was created.
+ pub created_at: DateTime<Utc>,
+ /// Whether recording was enabled when the call started.
+ pub recording_enabled: bool,
+}
+
+/// Reason an active call was archived as a call record.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum CallArchiveReason {
+ /// The final participant left the call.
+ LastParticipantLeft,
+ /// The room-finished webhook archived the call.
+ RoomFinished,
+}
+
+/// Metadata for [`CallTopicEvent::RecordArchived`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallRecordArchivedMetadata {
+ /// Identifier shared by the active call and archived call record.
+ pub call_id: Uuid,
+ /// Identifier of the channel containing the call record.
+ pub channel_id: Uuid,
+ /// User who created the call.
+ pub created_by: MacroUserIdStr<'static>,
+ /// Time at which the call started.
+ pub started_at: DateTime<Utc>,
+ /// Time at which the call was archived.
+ pub ended_at: DateTime<Utc>,
+ /// Call duration in milliseconds, when available.
+ pub duration_ms: Option<i64>,
+ /// Number of distinct participants over the call's lifetime.
+ pub participant_count: usize,
+ /// Whether the call has an associated recording.
+ pub has_recording: bool,
+ /// Reason the call was archived.
+ pub archive_reason: CallArchiveReason,
+}
+
+/// Metadata for [`CallTopicEvent::RecordUpdated`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallRecordUpdatedMetadata {
+ /// Identifier of the updated call record.
+ pub call_id: Uuid,
+ /// Identifier of the channel containing the call record.
+ pub channel_id: Uuid,
+ /// User who updated the record, or `None` for an internal caller.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// New custom display name, or `None` when unchanged.
+ pub custom_name: Option<String>,
+ /// New team-sharing value, or `None` when unchanged.
+ pub share_with_team: Option<bool>,
+}
+
+/// Metadata for [`CallTopicEvent::RecordDeleted`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallRecordDeletedMetadata {
+ /// Identifier of the deleted call record.
+ pub call_id: Uuid,
+ /// Identifier of the channel that contained the call record.
+ pub channel_id: Uuid,
+ /// User who deleted the record, or `None` for an internal caller.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+}
+
+/// Metadata for [`CallTopicEvent::RecordSummarized`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallRecordSummarizedMetadata {
+ /// Identifier of the summarized call record.
+ pub call_id: Uuid,
+ /// Identifier of the channel containing the call record.
+ pub channel_id: Uuid,
+ /// Whether an AI-generated display name was persisted with the summary.
+ pub ai_name_generated: bool,
+}
+
+/// Metadata for [`CallTopicEvent::RecordingReady`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CallRecordingReadyMetadata {
+ /// Identifier of the call record whose recording is ready.
+ pub call_id: Uuid,
+ /// Identifier of the channel containing the call record.
+ pub channel_id: Uuid,
+}
+
+/// Lifecycle and recording events published to [`MacroCallsTopic`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "event_type", content = "metadata")]
+pub enum CallTopicEvent {
+ /// A call was started.
+ #[serde(rename = "call.started")]
+ Started(CallStartedMetadata),
+ /// An active call was archived as a call record.
+ #[serde(rename = "call.record_archived")]
+ RecordArchived(CallRecordArchivedMetadata),
+ /// A call record's metadata was updated.
+ #[serde(rename = "call.record_updated")]
+ RecordUpdated(CallRecordUpdatedMetadata),
+ /// A call record was deleted.
+ #[serde(rename = "call.record_deleted")]
+ RecordDeleted(CallRecordDeletedMetadata),
+ /// A summary was persisted for a call record.
+ #[serde(rename = "call.record_summarized")]
+ RecordSummarized(CallRecordSummarizedMetadata),
+ /// A call record's recording became available.
+ #[serde(rename = "call.recording_ready")]
+ RecordingReady(CallRecordingReadyMetadata),
+}
+
+impl TopicEvent for CallTopicEvent {
+ type Topic = MacroCallsTopic;
+
+ const SCHEMA_VERSION: u8 = 1;
+}
+
+/// Publishable event for [`MacroCallsTopic`], keyed by the call's bare id.
+pub struct CallMacroEvent {
+ key: String,
+ event: Event<CallTopicEvent>,
+}
+
+impl CallMacroEvent {
+ /// Build a call-started event keyed by the call id.
+ pub fn started(metadata: CallStartedMetadata) -> Self {
+ let key = metadata.call_id.to_string();
+ Self::new(key, CallTopicEvent::Started(metadata))
+ }
+
+ /// Build a record-archived event keyed by the call id.
+ pub fn record_archived(metadata: CallRecordArchivedMetadata) -> Self {
+ let key = metadata.call_id.to_string();
+ Self::new(key, CallTopicEvent::RecordArchived(metadata))
+ }
+
+ /// Build a record-updated event keyed by the call id.
+ pub fn record_updated(metadata: CallRecordUpdatedMetadata) -> Self {
+ let key = metadata.call_id.to_string();
+ Self::new(key, CallTopicEvent::RecordUpdated(metadata))
+ }
+
+ /// Build a record-deleted event keyed by the call id.
+ pub fn record_deleted(metadata: CallRecordDeletedMetadata) -> Self {
+ let key = metadata.call_id.to_string();
+ Self::new(key, CallTopicEvent::RecordDeleted(metadata))
+ }
+
+ /// Build a record-summarized event keyed by the call id.
+ pub fn record_summarized(metadata: CallRecordSummarizedMetadata) -> Self {
+ let key = metadata.call_id.to_string();
+ Self::new(key, CallTopicEvent::RecordSummarized(metadata))
+ }
+
+ /// Build a recording-ready event keyed by the call id.
+ pub fn recording_ready(metadata: CallRecordingReadyMetadata) -> Self {
+ let key = metadata.call_id.to_string();
+ Self::new(key, CallTopicEvent::RecordingReady(metadata))
+ }
+
+ fn new(key: String, event: CallTopicEvent) -> Self {
+ Self::with_event(key, Event::new(event))
+ }
+
+ fn with_event(key: String, event: Event<CallTopicEvent>) -> Self {
+ Self { key, event }
+ }
+}
+
+impl MacroEvent for CallMacroEvent {
+ type EventPayload = CallTopicEvent;
+
+ fn key(&self) -> &str {
+ &self.key
+ }
+
+ fn event(&self) -> &Event<Self::EventPayload> {
+ &self.event
+ }
+
+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {
+ Self::with_event(key, event)
+ }
+}
diff --git a/crates/call/src/domain/events/test.rs b/crates/call/src/domain/events/test.rs
new file mode 100644
index 0000000000..f6559abf53
--- /dev/null
+++ b/crates/call/src/domain/events/test.rs
@@ -0,0 +1,244 @@
+use chrono::{DateTime, Utc};
+use macro_event_broker::{Event, MacroEvent};
+use macro_event_topics::{MacroCallsTopic, Topic};
+use macro_user_id::user_id::MacroUserIdStr;
+use serde_json::{Value, json};
+use uuid::Uuid;
+
+use super::*;
+
+const CALL_ID: &str = "0198a1b2-c3d4-7e5f-8061-728394a5b6c7";
+const CHANNEL_ID: &str = "3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90";
+const EVENT_ID: &str = "01998a30-1a2b-7c3d-9e4f-5a6b7c8d9e0f";
+
+fn uuid(value: &str) -> Uuid {
+ Uuid::parse_str(value).expect("valid uuid")
+}
+
+fn user_id(value: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(value.to_string()).expect("valid user id")
+}
+
+fn timestamp(value: &str) -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(value)
+ .expect("valid timestamp")
+ .with_timezone(&Utc)
+}
+
+fn topic_events() -> Vec<(CallTopicEvent, Value)> {
+ vec![
+ (
+ CallTopicEvent::Started(CallStartedMetadata {
+ call_id: uuid(CALL_ID),
+ channel_id: uuid(CHANNEL_ID),
+ created_by: user_id("macro|[email protected]"),
+ created_at: timestamp("2026-07-27T18:01:02Z"),
+ recording_enabled: true,
+ }),
+ json!({
+ "event_type": "call.started",
+ "metadata": {
+ "call_id": CALL_ID,
+ "channel_id": CHANNEL_ID,
+ "created_by": "macro|[email protected]",
+ "created_at": "2026-07-27T18:01:02Z",
+ "recording_enabled": true,
+ },
+ }),
+ ),
+ (
+ CallTopicEvent::RecordArchived(CallRecordArchivedMetadata {
+ call_id: uuid(CALL_ID),
+ channel_id: uuid(CHANNEL_ID),
+ created_by: user_id("macro|[email protected]"),
+ started_at: timestamp("2026-07-27T18:01:02Z"),
+ ended_at: timestamp("2026-07-27T18:03:07Z"),
+ duration_ms: None,
+ participant_count: 4,
+ has_recording: true,
+ archive_reason: CallArchiveReason::LastParticipantLeft,
+ }),
+ json!({
+ "event_type": "call.record_archived",
+ "metadata": {
+ "call_id": CALL_ID,
+ "channel_id": CHANNEL_ID,
+ "created_by": "macro|[email protected]",
+ "started_at": "2026-07-27T18:01:02Z",
+ "ended_at": "2026-07-27T18:03:07Z",
+ "duration_ms": null,
+ "participant_count": 4,
+ "has_recording": true,
+ "archive_reason": "last_participant_left",
+ },
+ }),
+ ),
+ (
+ CallTopicEvent::RecordUpdated(CallRecordUpdatedMetadata {
+ call_id: uuid(CALL_ID),
+ channel_id: uuid(CHANNEL_ID),
+ actor_user_id: Some(user_id("macro|[email protected]")),
+ custom_name: Some("Weekly planning".to_string()),
+ share_with_team: None,
+ }),
+ json!({
+ "event_type": "call.record_updated",
+ "metadata": {
+ "call_id": CALL_ID,
+ "channel_id": CHANNEL_ID,
+ "actor_user_id": "macro|[email protected]",
+ "custom_name": "Weekly planning",
+ "share_with_team": null,
+ },
+ }),
+ ),
+ (
+ CallTopicEvent::RecordDeleted(CallRecordDeletedMetadata {
+ call_id: uuid(CALL_ID),
+ channel_id: uuid(CHANNEL_ID),
+ actor_user_id: None,
+ }),
+ json!({
+ "event_type": "call.record_deleted",
+ "metadata": {
+ "call_id": CALL_ID,
+ "channel_id": CHANNEL_ID,
+ "actor_user_id": null,
+ },
+ }),
+ ),
+ (
+ CallTopicEvent::RecordSummarized(CallRecordSummarizedMetadata {
+ call_id: uuid(CALL_ID),
+ channel_id: uuid(CHANNEL_ID),
+ ai_name_generated: true,
+ }),
+ json!({
+ "event_type": "call.record_summarized",
+ "metadata": {
+ "call_id": CALL_ID,
+ "channel_id": CHANNEL_ID,
+ "ai_name_generated": true,
+ },
+ }),
+ ),
+ (
+ CallTopicEvent::RecordingReady(CallRecordingReadyMetadata {
+ call_id: uuid(CALL_ID),
+ channel_id: uuid(CHANNEL_ID),
+ }),
+ json!({
+ "event_type": "call.recording_ready",
+ "metadata": {
+ "call_id": CALL_ID,
+ "channel_id": CHANNEL_ID,
+ },
+ }),
+ ),
+ ]
+}
+
+fn macro_events() -> Vec<CallMacroEvent> {
+ topic_events()
+ .into_iter()
+ .map(|(event, _)| match event {
+ CallTopicEvent::Started(metadata) => CallMacroEvent::started(metadata),
+ CallTopicEvent::RecordArchived(metadata) => CallMacroEvent::record_archived(metadata),
+ CallTopicEvent::RecordUpdated(metadata) => CallMacroEvent::record_updated(metadata),
+ CallTopicEvent::RecordDeleted(metadata) => CallMacroEvent::record_deleted(metadata),
+ CallTopicEvent::RecordSummarized(metadata) => {
+ CallMacroEvent::record_summarized(metadata)
+ }
+ CallTopicEvent::RecordingReady(metadata) => CallMacroEvent::recording_ready(metadata),
+ })
+ .collect()
+}
+
+#[test]
+fn every_variant_has_exact_json_envelope() {
+ let event_id = uuid(EVENT_ID);
+
+ for (event, expected_payload) in topic_events() {
+ let mut expected = expected_payload;
+ let object = expected.as_object_mut().expect("expected object");
+ object.insert("event_id".to_string(), json!(EVENT_ID));
+ object.insert("schema_version".to_string(), json!(1));
+
+ assert_eq!(
+ serde_json::to_value(Event::with_event_id(event_id, event))
+ .expect("serializable event"),
+ expected
+ );
+ }
+}
+
+#[test]
+fn every_variant_round_trips() {
+ for original in macro_events() {
+ let payload = serde_json::to_vec(original.event()).expect("serializable event");
+ let decoded = CallMacroEvent::decode(original.key(), &payload).expect("decodable event");
+
+ assert_eq!(decoded.key(), CALL_ID);
+ assert_eq!(decoded.event(), original.event());
+ assert_eq!(decoded.topic(), MacroCallsTopic::TOPIC_STR);
+ assert_eq!(decoded.topic(), "macro.calls");
+ }
+}
+
+#[test]
+fn constructors_use_calls_topic_bare_call_id_key_and_schema_version_one() {
+ for event in macro_events() {
+ assert_eq!(event.key(), CALL_ID);
+ assert!(!event.key().starts_with("call|"));
+ assert_eq!(event.topic(), "macro.calls");
+ assert_eq!(event.event().schema_version, 1);
+ }
+}
+
+#[test]
+fn archive_reasons_use_exact_wire_names() {
+ assert_eq!(
+ serde_json::to_value(CallArchiveReason::LastParticipantLeft)
+ .expect("serializable archive reason"),
+ "last_participant_left"
+ );
+ assert_eq!(
+ serde_json::to_value(CallArchiveReason::RoomFinished).expect("serializable archive reason"),
+ "room_finished"
+ );
+}
+
+#[test]
+fn metadata_excludes_private_call_content_and_locations() {
+ let forbidden_fields = [
+ "transcript",
+ "transcript_text",
+ "summary",
+ "summary_text",
+ "recording_url",
+ "recording_key",
+ "share_permission",
+ ];
+
+ for event in macro_events() {
+ let value = serde_json::to_value(event.event()).expect("serializable event");
+ let metadata = &value["metadata"];
+
+ for field in forbidden_fields {
+ assert!(
+ !contains_field(metadata, field),
+ "metadata included {field}"
+ );
+ }
+ }
+}
+
+fn contains_field(value: &Value, field: &str) -> bool {
+ match value {
+ Value::Object(object) => {
+ object.contains_key(field) || object.values().any(|value| contains_field(value, field))
+ }
+ Value::Array(values) => values.iter().any(|value| contains_field(value, field)),
+ _ => false,
+ }
+}
diff --git a/crates/call/src/domain/mod.rs b/crates/call/src/domain/mod.rs
index c2acc673d8..31abcf6090 100644
--- a/crates/call/src/domain/mod.rs
+++ b/crates/call/src/domain/mod.rs
@@ -1,3 +1,6 @@
+/// Kafka event contracts for call lifecycle events.
+pub mod events;
+
/// Domain models for calls.
pub mod models;
diff --git a/crates/call/src/domain/models.rs b/crates/call/src/domain/models.rs
index 7d4ed32828..80918f00d9 100644
--- a/crates/call/src/domain/models.rs
+++ b/crates/call/src/domain/models.rs
@@ -29,6 +29,27 @@ pub struct Call {
pub egress_id: Option<String>,
}
+/// Facts committed when an active call is archived.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ArchivedCall {
+ /// The archived call record identifier.
+ pub call_id: Uuid,
+ /// The channel the call belongs to.
+ pub channel_id: Uuid,
+ /// User who created the call.
+ pub created_by: String,
+ /// When the call started.
+ pub started_at: DateTime<Utc>,
+ /// When the call ended.
+ pub ended_at: DateTime<Utc>,
+ /// Call duration in milliseconds.
+ pub duration_ms: i64,
+ /// Whether a recording egress was started before the call was archived.
+ pub has_recording: bool,
+ /// Number of distinct participants over the call's lifetime.
+ pub participant_count: usize,
+}
+
/// A participant in an active call.
#[derive(Debug, Clone)]
pub struct CallParticipant {
diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rs
index 5ee7cfb7a1..9af7564da5 100644
--- a/crates/call/src/domain/ports.rs
+++ b/crates/call/src/domain/ports.rs
@@ -18,8 +18,8 @@ use crate::domain::models::{
};
use super::models::{
- AddParticipantError, Call, CallActiveResponse, CallError, CallParticipant, CallRecord,
- CallRecordPreview, CallRecordTranscriptSegment, CallTokenResponse,
+ AddParticipantError, ArchivedCall, Call, CallActiveResponse, CallError, CallParticipant,
+ CallRecord, CallRecordPreview, CallRecordTranscriptSegment, CallTokenResponse,
CallTranscriptCustomSpeakerResult, CallWebhookEvent, EgressS3Config, EnrichedCallTranscript,
GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetCallRecordsRequest,
LeaveCallResponse, RingStatusResponse, TranscriptSegmentRequest, VerifiedRingToken,
@@ -135,8 +135,11 @@ pub trait CallRepository: Send + Sync + 'static {
/// Archive an active call to the permanent `call_records` and
/// `call_record_participants` tables, then delete the ephemeral rows.
- /// Returns the new `call_records` id.
- fn archive_call(&self, call_id: &Uuid) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;
+ /// Returns facts committed by the archive transaction.
+ fn archive_call(
+ &self,
+ call_id: &Uuid,
+ ) -> impl Future<Output = Result<ArchivedCall, Self::Err>> + Send;
/// Set the recording key on an archived call record.
fn set_recording_key(
@@ -146,10 +149,12 @@ pub trait CallRepository: Send + Sync + 'static {
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Find a call record by its egress ID (for webhook handling).
+ ///
+ /// Returns the archived call record's `(call_id, channel_id)` context.
fn get_call_record_by_egress_id(
&self,
egress_id: &str,
- ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<(Uuid, Uuid)>, Self::Err>> + Send;
/// Set the recording key on an active call (by egress ID).
///
@@ -316,22 +321,22 @@ pub trait CallRepository: Send + Sync + 'static {
///
/// Tolerates unknown `call_id` (no row matches): the summarization flow
/// can race with the record being deleted, so this is an idempotent no-op
- /// when the target row is gone.
+ /// when the target row is gone. Returns whether a row was updated.
fn insert_call_summary(
&self,
call_id: &Uuid,
summary: &str,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
/// Set `call_records.custom_name = $name` only when the existing value is
/// `NULL`. Used by the AI auto-naming flow so a user-set custom name is
- /// never overwritten. No-op if no row matches or the column is already
- /// populated.
+ /// never overwritten. Returns whether the conditional update persisted
+ /// the name; returns `false` if no row matches or the column is populated.
fn set_custom_name_if_null(
&self,
call_id: &Uuid,
name: &str,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
}
/// Storage port for generating signed recording GET URLs and deleting objects.
diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rs
index 85c5f26922..6e290e306a 100644
--- a/crates/call/src/domain/service.rs
+++ b/crates/call/src/domain/service.rs
@@ -5,9 +5,11 @@ mod test;
use connection::domain::ports::ConnectionService;
use entity_access::domain::models::{
- EditAccessLevel, EntityAccessReceipt, EntityPermission, EntityType, ViewAccessLevel,
+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityPermission, EntityType,
+ ViewAccessLevel,
};
use entity_access::domain::ports::EntityAccessService;
+use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use notification::domain::models::apple::VoipPushPayload;
@@ -24,12 +26,17 @@ use std::collections::{HashMap, HashSet};
use uuid::Uuid;
+use crate::domain::events::{
+ CallArchiveReason, CallMacroEvent, CallRecordArchivedMetadata, CallRecordDeletedMetadata,
+ CallRecordSummarizedMetadata, CallRecordUpdatedMetadata, CallRecordingReadyMetadata,
+ CallStartedMetadata,
+};
use crate::domain::models::{
EditCallRecordRequest, EditCallTranscriptRequest, VoipPushPayloadRequest,
};
use super::models::{
- AddParticipantError, Call, CallActiveResponse, CallError, CallRecord,
+ AddParticipantError, ArchivedCall, Call, CallActiveResponse, CallError, CallRecord,
CallRecordTranscriptSegment, CallTokenResponse, CallTranscriptCustomSpeakerResult,
EgressS3Config, EnrichedCallTranscript, GetBatchCallRecordPreviewRequest,
GetBatchCallRecordPreviewResponse, GetCallRecordsRequest, LeaveCallResponse, RingStatus,
@@ -52,6 +59,7 @@ pub struct CallServiceImpl<
I: CallSearchIndexer = NoOpCallSearchIndexer,
V: VoipPushSender = (),
Vr: VoiceRepository = NoOpVoiceRepository,
+ B: MacroEventBroker = NoopMacroEventBroker,
> {
repo: R,
rtc_client: C,
@@ -67,6 +75,7 @@ pub struct CallServiceImpl<
voip_push_sender: V,
voice_repo: Vr,
ring_status_base_url: Option<String>,
+ event_broker: B,
}
impl<
@@ -104,6 +113,7 @@ impl<
voip_push_sender: (),
voice_repo: NoOpVoiceRepository,
ring_status_base_url: None,
+ event_broker: NoopMacroEventBroker,
}
}
}
@@ -119,7 +129,8 @@ impl<
I: CallSearchIndexer,
V: VoipPushSender,
Vr: VoiceRepository,
-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+ B: MacroEventBroker,
+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>
{
/// Enable auto-recording with the given S3 configuration.
pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {
@@ -153,7 +164,7 @@ impl<
pub fn with_voip_push_sender<V2: VoipPushSender>(
self,
sender: V2,
- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V2, Vr> {
+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V2, Vr, B> {
CallServiceImpl {
repo: self.repo,
rtc_client: self.rtc_client,
@@ -169,6 +180,7 @@ impl<
voip_push_sender: sender,
voice_repo: self.voice_repo,
ring_status_base_url: self.ring_status_base_url,
+ event_broker: self.event_broker,
}
}
@@ -176,7 +188,7 @@ impl<
pub fn with_search_indexer<I2: CallSearchIndexer>(
self,
indexer: I2,
- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2, V, Vr> {
+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2, V, Vr, B> {
CallServiceImpl {
repo: self.repo,
rtc_client: self.rtc_client,
@@ -192,6 +204,7 @@ impl<
voip_push_sender: self.voip_push_sender,
voice_repo: self.voice_repo,
ring_status_base_url: self.ring_status_base_url,
+ event_broker: self.event_broker,
}
}
@@ -199,7 +212,7 @@ impl<
pub fn with_voice_repo<Vr2: VoiceRepository>(
self,
voice_repo: Vr2,
- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr2> {
+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr2, B> {
CallServiceImpl {
repo: self.repo,
rtc_client: self.rtc_client,
@@ -215,9 +228,70 @@ impl<
voip_push_sender: self.voip_push_sender,
voice_repo,
ring_status_base_url: self.ring_status_base_url,
+ event_broker: self.event_broker,
+ }
+ }
+
+ /// Replace the event broker while preserving every other service dependency.
+ pub fn with_event_broker<B2: MacroEventBroker>(
+ self,
+ event_broker: B2,
+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B2> {
+ CallServiceImpl {
+ repo: self.repo,
+ rtc_client: self.rtc_client,
+ connection_service: self.connection_service,
+ entity_access_service: self.entity_access_service,
+ notification_ingress: self.notification_ingress,
+ recording_storage: self.recording_storage,
+ search_indexer: self.search_indexer,
+ server_url: self.server_url,
+ egress_s3_config: self.egress_s3_config,
+ internal_call_secret: self.internal_call_secret,
+ summarizer: self.summarizer,
+ voip_push_sender: self.voip_push_sender,
+ voice_repo: self.voice_repo,
+ ring_status_base_url: self.ring_status_base_url,
+ event_broker,
}
}
+ fn publish_call_event(&self, event: &CallMacroEvent) {
+ publish_call_event(&self.event_broker, event);
+ }
+
+ fn publish_archived_call_event(
+ &self,
+ archived: &ArchivedCall,
+ archive_reason: CallArchiveReason,
+ ) {
+ let created_by = match MacroUserIdStr::parse_from_str(&archived.created_by) {
+ Ok(created_by) => created_by.into_owned(),
+ Err(error) => {
+ tracing::error!(
+ error = ?error,
+ call_id = %archived.call_id,
+ "failed to parse stored call creator; skipping archived event"
+ );
+ return;
+ }
+ };
+
+ self.publish_call_event(&CallMacroEvent::record_archived(
+ CallRecordArchivedMetadata {
+ call_id: archived.call_id,
+ channel_id: archived.channel_id,
+ created_by,
+ started_at: archived.started_at,
+ ended_at: archived.ended_at,
+ duration_ms: Some(archived.duration_ms),
+ participant_count: archived.participant_count,
+ has_recording: archived.has_recording,
+ archive_reason,
+ },
+ ));
+ }
+
/// Send a call event to all channel members (best-effort).
async fn send_call_event(
&self,
@@ -315,6 +389,15 @@ fn resolve_ring_status(
}
}
+fn event_actor_user_id(auth: &EntityAccessAuth) -> Option<MacroUserIdStr<'static>> {
+ match auth {
+ EntityAccessAuth::Authenticated(user_id) => Some(user_id.clone().into_owned()),
+ EntityAccessAuth::Bot(_)
+ | EntityAccessAuth::Unauthenticated
+ | EntityAccessAuth::Internal => None,
+ }
+}
+
fn exclude_voip_recipients<'a>(
recipient_ids: HashSet<MacroUserIdStr<'a>>,
voip_recipient_ids: &HashSet<MacroUserIdStr<'static>>,
@@ -394,7 +477,8 @@ impl<
I: CallSearchIndexer,
V: VoipPushSender,
Vr: VoiceRepository + Clone,
-> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+ B: MacroEventBroker + Clone,
+> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>
{
fn validate_internal_call(&self, token: &str) -> bool {
self.internal_call_secret
@@ -481,6 +565,27 @@ impl<
}
}
+ match MacroUserIdStr::parse_from_str(&call.created_by) {
+ Ok(created_by) => {
+ self.publish_call_event(&CallMacroEvent::started(
+ CallStartedMetadata {
+ call_id: call.id,
+ channel_id: call.channel_id,
+ created_by: created_by.into_owned(),
+ created_at: call.created_at,
+ recording_enabled: self.egress_s3_config.is_some(),
+ },
+ ));
+ }
+ Err(error) => {
+ tracing::error!(
+ error = ?error,
+ call_id = %call.id,
+ "failed to parse stored call creator; skipping started event"
+ );
+ }
+ }
+
// Notify channel members about the new call (best-effort).
self.send_call_event(
channel_id,
@@ -802,27 +907,28 @@ impl<
.map_err(|e| CallError::Internal(e.into()))?
{
tracing::info!(call_id = %call.id, room_name, "archiving call on room_finished");
- let channel_id = call.channel_id;
- self.repo
+ let archived = self
+ .repo
.archive_call(&call.id)
.await
.map_err(|e| CallError::Internal(e.into()))?;
+ self.publish_archived_call_event(&archived, CallArchiveReason::RoomFinished);
// Fire-and-forget summarization now that the
// `call_records` row is persisted.
- self.spawn_summarize_call(call.id);
- self.spawn_process_voices_for_call(call.id);
+ self.spawn_summarize_call(archived.call_id);
+ self.spawn_process_voices_for_call(archived.call_id);
- if let Err(e) = self.search_indexer.enqueue_upsert(&call.id).await {
- tracing::error!(error=?e, call_id=%call.id, "failed to enqueue call record for search indexing");
+ if let Err(e) = self.search_indexer.enqueue_upsert(&archived.call_id).await {
+ tracing::error!(error=?e, call_id=%archived.call_id, "failed to enqueue call record for search indexing");
}
self.send_call_event(
- &channel_id,
+ &archived.channel_id,
"call_ended",
&serde_json::json!({
- "channel_id": channel_id,
- "call_id": call.id,
+ "channel_id": archived.channel_id,
+ "call_id": archived.call_id,
}),
None,
)
@@ -911,20 +1017,24 @@ impl<
if remaining == 0 {
tracing::info!(call_id = %call.id, room_name, "last participant left, archiving call");
- let channel_id = call.channel_id;
let egress_id = call.egress_id.clone();
- self.repo
+ let archived = self
+ .repo
.archive_call(&call.id)
.await
.map_err(|e| CallError::Internal(e.into()))?;
+ self.publish_archived_call_event(
+ &archived,
+ CallArchiveReason::LastParticipantLeft,
+ );
// Fire-and-forget summarization now that the
// `call_records` row is persisted.
- self.spawn_summarize_call(call.id);
- self.spawn_process_voices_for_call(call.id);
+ self.spawn_summarize_call(archived.call_id);
+ self.spawn_process_voices_for_call(archived.call_id);
- if let Err(e) = self.search_indexer.enqueue_upsert(&call.id).await {
- tracing::error!(error=?e, call_id=%call.id, "failed to enqueue call record for search indexing");
+ if let Err(e) = self.search_indexer.enqueue_upsert(&archived.call_id).await {
+ tracing::error!(error=?e, call_id=%archived.call_id, "failed to enqueue call record for search indexing");
}
// Stop egress explicitly before deleting the room. DeleteRoom
@@ -948,11 +1058,11 @@ impl<
.ok();
self.send_call_event(
- &channel_id,
+ &archived.channel_id,
"call_ended",
&serde_json::json!({
- "channel_id": channel_id,
- "call_id": call.id,
+ "channel_id": archived.channel_id,
+ "call_id": archived.call_id,
}),
None,
)
@@ -1002,16 +1112,22 @@ impl<
tracing::info!(egress_id, recording_key, "egress recording completed");
// Find the archived call record by egress_id and update the recording key.
- if let Some(call_record_id) = self
+ if let Some((call_id, channel_id)) = self
.repo
.get_call_record_by_egress_id(egress_id)
.await
.map_err(|e| CallError::Internal(e.into()))?
{
self.repo
- .set_recording_key(&call_record_id, recording_key)
+ .set_recording_key(&call_id, recording_key)
.await
.map_err(|e| CallError::Internal(e.into()))?;
+ self.publish_call_event(&CallMacroEvent::recording_ready(
+ CallRecordingReadyMetadata {
+ call_id,
+ channel_id,
+ },
+ ));
} else {
// Call not yet archived — store on the active call so
// archive_call can carry it forward.
@@ -1110,6 +1226,7 @@ impl<
}
let call_id = Uuid::parse_str(&entity.entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;
+ let actor_user_id = event_actor_user_id(receipt.auth());
// Look up channel_id before deletion to keep the search-remove message id unique.
let channel_id = self
@@ -1125,6 +1242,16 @@ impl<
.await
.map_err(|e| CallError::Internal(e.into()))?;
+ if storage_keys.is_some()
+ && let Some(channel_id) = channel_id
+ {
+ self.publish_call_event(&CallMacroEvent::record_deleted(CallRecordDeletedMetadata {
+ call_id,
+ channel_id,
+ actor_user_id,
+ }));
+ }
+
if let Some(channel_id) = channel_id
&& let Err(e) = self
.search_indexer
@@ -1246,11 +1373,32 @@ impl<
let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
+ let actor_user_id = event_actor_user_id(receipt.auth());
+ let custom_name = request.custom_name.clone();
+ let share_with_team = request.share_with_team;
+ let channel_id = self
+ .repo
+ .get_call_record_by_call_id(&call_id)
+ .await
+ .map_err(|e| CallError::Internal(e.into()))?
+ .map(|record| record.channel_id);
self.repo
.patch_call_record(&call_id, &request)
.await
- .map_err(|e| CallError::Internal(e.into()))
+ .map_err(|e| CallError::Internal(e.into()))?;
+
+ if let Some(channel_id) = channel_id {
+ self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
+ call_id,
+ channel_id,
+ actor_user_id,
+ custom_name,
+ share_with_team,
+ }));
+ }
+
+ Ok(())
}
#[tracing::instrument(err, skip(self, request), fields(num_assignments = request.assignments.len()))]
@@ -1291,6 +1439,7 @@ impl<
let call_id = macro_uuid::string_to_uuid(&entity.entity_id)
.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call entity receipt")))?;
+ let actor_user_id = event_actor_user_id(receipt.auth());
let (new_value, channel_id) = self
.repo
@@ -1298,6 +1447,14 @@ impl<
.await
.map_err(|e| CallError::Internal(e.into()))?;
+ self.publish_call_event(&CallMacroEvent::record_updated(CallRecordUpdatedMetadata {
+ call_id,
+ channel_id,
+ actor_user_id,
+ custom_name: None,
+ share_with_team: Some(new_value),
+ }));
+
self.send_call_participant_event(
&call_id,
"call_share_with_team_toggled",
@@ -1372,38 +1529,30 @@ impl<
return Ok(());
};
- self.repo
+ let summary_persisted = self
+ .repo
.insert_call_summary(call_id, &summary)
.await
.inspect_err(|e| tracing::error!(error=?e, %call_id, "failed to persist call summary"))
.map_err(|e| CallError::Internal(e.into()))?;
- // Auto-generate a display name from the summary; only persisted when
- // the user has not already set one (`set_custom_name_if_null`). Best
- // effort — naming failures must not fail summarization.
- if record.custom_name.is_none() {
- match summarizer.generate_call_name(call_id, &summary).await {
- Ok(Some(name)) => {
- if let Err(e) = self.repo.set_custom_name_if_null(call_id, &name).await {
- tracing::error!(
- error=?e, %call_id,
- "failed to persist ai-generated call name"
- );
- }
- }
- Ok(None) => {
- tracing::info!(
- %call_id,
- "ai call naming returned no title; leaving name unset"
- );
- }
- Err(e) => {
- tracing::error!(
- error=?e, %call_id,
- "ai call naming failed after summary; leaving name unset"
- );
- }
- }
+ let ai_name_generated = generate_and_persist_call_name(
+ &self.repo,
+ summarizer,
+ call_id,
+ &summary,
+ record.custom_name.is_none(),
+ )
+ .await;
+
+ if summary_persisted {
+ self.publish_call_event(&CallMacroEvent::record_summarized(
+ CallRecordSummarizedMetadata {
+ call_id: *call_id,
+ channel_id: record.channel_id,
+ ai_name_generated,
+ },
+ ));
}
Ok(())
@@ -1447,20 +1596,22 @@ impl<
I: CallSearchIndexer,
V: VoipPushSender,
Vr: VoiceRepository + Clone,
-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+ B: MacroEventBroker + Clone,
+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>
{
/// Fire-and-forget spawn of [`CallService::summarize_call`] for `call_id`.
///
/// Called after the `call_records` row is persisted so that summarization
/// can run off the request path without blocking call completion. The
- /// spawned task owns cloned handles to `repo` and `summarizer`; errors
- /// are logged, never propagated. When no summarizer is configured this is
- /// a no-op and no task is spawned.
+ /// spawned task owns cloned handles to `repo`, `summarizer`, and the event
+ /// broker; errors are logged, never propagated. When no summarizer is
+ /// configured this is a no-op and no task is spawned.
fn spawn_summarize_call(&self, call_id: Uuid) {
let Some(summarizer) = self.summarizer.clone() else {
return;
};
let repo = self.repo.clone();
+ let event_broker = self.event_broker.clone();
tokio::spawn(async move {
if let Err(e) = generate_and_persist_custom_speakers(&repo, &summarizer, &call_id).await
{
@@ -1499,34 +1650,32 @@ impl<
}
};
- if let Err(e) = repo.insert_call_summary(&call_id, &summary).await {
- tracing::error!(error=?e, %call_id, "failed to persist call summary");
- return;
- }
-
- if record.custom_name.is_none() {
- match summarizer.generate_call_name(&call_id, &summary).await {
- Ok(Some(name)) => {
- if let Err(e) = repo.set_custom_name_if_null(&call_id, &name).await {
- tracing::error!(
- error=?e, %call_id,
- "failed to persist ai-generated call name"
- );
- }
- }
- Ok(None) => {
- tracing::info!(
- %call_id,
- "ai call naming returned no title; leaving name unset"
- );
- }
- Err(e) => {
- tracing::error!(
- error=?e, %call_id,
- "ai call naming failed after summary; leaving name unset"
- );
- }
+ let summary_persisted = match repo.insert_call_summary(&call_id, &summary).await {
+ Ok(persisted) => persisted,
+ Err(e) => {
+ tracing::error!(error=?e, %call_id, "failed to persist call summary");
+ return;
}
+ };
+
+ let ai_name_generated = generate_and_persist_call_name(
+ &repo,
+ &summarizer,
+ &call_id,
+ &summary,
+ record.custom_name.is_none(),
+ )
+ .await;
+
+ if summary_persisted {
+ publish_call_event(
+ &event_broker,
+ &CallMacroEvent::record_summarized(CallRecordSummarizedMetadata {
+ call_id,
+ channel_id: record.channel_id,
+ ai_name_generated,
+ }),
+ );
}
});
}
@@ -1547,6 +1696,55 @@ impl<
}
}
+fn publish_call_event<B: MacroEventBroker>(event_broker: &B, event: &CallMacroEvent) {
+ drop(event_broker.send_event(event).inspect_err(|error| {
+ tracing::error!(error = ?error, "failed to schedule call lifecycle event");
+ }));
+}
+
+async fn generate_and_persist_call_name<R, Sm>(
+ repo: &R,
+ summarizer: &Sm,
+ call_id: &Uuid,
+ summary: &str,
+ should_generate_name: bool,
+) -> bool
+where
+ R: CallRepository,
+ Sm: CallSummarizer,
+{
+ if !should_generate_name {
+ return false;
+ }
+
+ match summarizer.generate_call_name(call_id, summary).await {
+ Ok(Some(name)) => match repo.set_custom_name_if_null(call_id, &name).await {
+ Ok(name_persisted) => name_persisted,
+ Err(e) => {
+ tracing::error!(
+ error=?e, %call_id,
+ "failed to persist ai-generated call name"
+ );
+ false
+ }
+ },
+ Ok(None) => {
+ tracing::info!(
+ %call_id,
+ "ai call naming returned no title; leaving name unset"
+ );
+ false
+ }
+ Err(e) => {
+ tracing::error!(
+ error=?e, %call_id,
+ "ai call naming failed after summary; leaving name unset"
+ );
+ false
+ }
+ }
+}
+
async fn generate_and_persist_custom_speakers<R, Sm>(
repo: &R,
summarizer: &Sm,
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index ba6833a693..2a2f2c0ca9 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -1,20 +1,36 @@
use std::collections::{HashMap, HashSet};
-use std::sync::Mutex;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, OnceLock};
+use std::time::Duration;
+use chrono::{DateTime, Utc};
+use connection::domain::models::{ConnectionError, InvalidationEvent};
+use connection::domain::ports::ConnectionService;
+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, EntityType};
+use entity_access::domain::ports::NoOpEntityAccessService;
+use entity_mutation::DeleteEntityPermanently;
+use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use notification::domain::models::apple::VoipPushPayload;
+use notification::domain::service::NotificationIngress;
+use serde_json::json;
use uuid::Uuid;
use crate::domain::models::{
- Call, CallError, CallWebhookEvent, EgressS3Config, RingStatus, VerifiedRingToken,
- VoipPushPayloadRequest,
+ ArchivedCall, Call, CallError, CallParticipant, CallRecord, CallRecordTranscriptSegment,
+ CallWebhookEvent, DeletedCallRecordStorageKeys, EditCallRecordRequest, EgressS3Config,
+ RingStatus, VerifiedRingToken, VoipPushPayloadRequest,
+};
+use crate::domain::ports::{
+ CallRtcClient, CallService, CallSummarizer, MockCallRepository, MockCallRtcClient,
+ NoOpCallSearchIndexer, NoOpVoiceRepository,
};
-use crate::domain::ports::CallRtcClient;
use super::{
- derive_preview_key_from_recording_key, derive_preview_keys_from_recording_key,
- exclude_voip_recipients, extract_recording_key, resolve_ring_status,
+ CallServiceImpl, NoopCallSummarizer, derive_preview_key_from_recording_key,
+ derive_preview_keys_from_recording_key, exclude_voip_recipients, extract_recording_key,
+ resolve_ring_status,
};
#[cfg(feature = "outbound")]
@@ -51,7 +67,7 @@ impl MockRtcClient {
impl CallRtcClient for MockRtcClient {
async fn create_room(&self, _room_name: &str) -> anyhow::Result<()> {
- unreachable!("create_room not exercised by these tests")
+ Ok(())
}
async fn delete_room(&self, _room_name: &str) -> anyhow::Result<()> {
@@ -118,7 +134,7 @@ impl CallRtcClient for MockRtcClient {
_room_name: &str,
_s3_config: &EgressS3Config,
) -> anyhow::Result<String> {
- unreachable!("start_room_composite_egress not exercised by these tests")
+ Ok("egress-id".to_string())
}
async fn stop_egress(&self, _egress_id: &str) -> anyhow::Result<()> {
@@ -138,7 +154,1783 @@ impl CallRtcClient for MockRtcClient {
}
async fn dispatch_transcription_agent(&self, _room_name: &str) -> anyhow::Result<()> {
- unreachable!("dispatch_transcription_agent not exercised by these tests")
+ Ok(())
+ }
+}
+
+fn configured_repository_clones() -> &'static Mutex<HashMap<usize, MockCallRepository>> {
+ static REPOSITORIES: OnceLock<Mutex<HashMap<usize, MockCallRepository>>> = OnceLock::new();
+ REPOSITORIES.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn configure_repository_clone(repo: &MockCallRepository, cloned_repo: MockCallRepository) {
+ let repo_address = repo as *const MockCallRepository as usize;
+ let previous = configured_repository_clones()
+ .lock()
+ .unwrap()
+ .insert(repo_address, cloned_repo);
+ assert!(previous.is_none(), "repository clone already configured");
+}
+
+// Spawned post-archive workflows clone the repository. Tests that exercise a
+// spawned repository operation install a purpose-built clone; other tests get
+// the empty stable-voice result needed by the default voice-processing path.
+impl Clone for MockCallRepository {
+ fn clone(&self) -> Self {
+ let repo_address = self as *const Self as usize;
+ if let Some(repo) = configured_repository_clones()
+ .lock()
+ .unwrap()
+ .remove(&repo_address)
+ {
+ return repo;
+ }
+
+ let mut repo = Self::new();
+ repo.expect_get_stable_speaker_voices_for_call_record()
+ .returning(|_| Box::pin(async { Ok(Vec::new()) }));
+ repo
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct PublishedCallEvent {
+ topic: &'static str,
+ key: String,
+ envelope: serde_json::Value,
+}
+
+#[derive(Clone, Default)]
+struct RecordingEventBroker {
+ events: Arc<Mutex<Vec<PublishedCallEvent>>>,
+ attempts: Arc<AtomicUsize>,
+ fail_scheduling: bool,
+}
+
+impl RecordingEventBroker {
+ fn failing() -> Self {
+ Self {
+ fail_scheduling: true,
+ ..Self::default()
+ }
+ }
+
+ fn events(&self) -> Vec<PublishedCallEvent> {
+ self.events.lock().unwrap().clone()
+ }
+
+ fn attempts(&self) -> usize {
+ self.attempts.load(Ordering::SeqCst)
+ }
+}
+
+impl MacroEventBroker for RecordingEventBroker {
+ fn send_event<E: MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {
+ self.attempts.fetch_add(1, Ordering::SeqCst);
+ if self.fail_scheduling {
+ return Err(EventBrokerError::Publish(
+ "intentional scheduling failure".to_string(),
+ ));
+ }
+
+ self.events.lock().unwrap().push(PublishedCallEvent {
+ topic: event.topic(),
+ key: event.key().to_string(),
+ envelope: serde_json::to_value(event.event())?,
+ });
+
+ Ok(tokio::spawn(async { Ok(()) }))
+ }
+}
+
+#[derive(Clone, Copy)]
+struct StubConnectionService;
+
+impl ConnectionService for StubConnectionService {
+ async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ _invalidation_event: InvalidationEvent<'a, T>,
+ ) -> Result<(), ConnectionError> {
+ Ok(())
+ }
+
+ async fn send_channel_message<'a>(
+ &self,
+ _users: &[MacroUserIdStr<'a>],
+ _message_type: &str,
+ _message: serde_json::Value,
+ ) -> Result<(), ConnectionError> {
+ Ok(())
+ }
+}
+
+#[derive(Clone, Copy)]
+struct StubNotificationIngress;
+
+impl NotificationIngress for StubNotificationIngress {
+ async fn send_notification<
+ 'a,
+ T: notification::domain::models::Notification + Clone + 'static,
+ U: serde::Serialize + Send + Sync + 'static,
+ >(
+ &'a self,
+ _request: notification::domain::models::request::SendNotificationRequest<'a, T, U>,
+ ) -> Result<
+ Option<notification::domain::models::NotificationResult<'a>>,
+ rootcause::Report<notification::domain::service::SendNotificationError>,
+ > {
+ unreachable!("notification sending is not exercised by get_or_create_call tests")
+ }
+}
+
+#[derive(Clone, Copy)]
+struct StubRecordingStorage;
+
+impl crate::domain::ports::RecordingStorage for StubRecordingStorage {
+ async fn presign_recording_url(&self, _recording_key: &str) -> anyhow::Result<String> {
+ unreachable!("recording reads are not exercised by get_or_create_call tests")
+ }
+
+ async fn presign_recording_preview_url(&self, _preview_key: &str) -> anyhow::Result<String> {
+ unreachable!("recording reads are not exercised by get_or_create_call tests")
+ }
+
+ async fn delete_recording(&self, _recording_key: &str) -> anyhow::Result<()> {
+ unreachable!("recording deletion is not exercised by get_or_create_call tests")
+ }
+
+ async fn delete_recording_preview(&self, _preview_key: &str) -> anyhow::Result<()> {
+ unreachable!("recording deletion is not exercised by get_or_create_call tests")
+ }
+}
+
+const STARTED_EVENT_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b6c7);
+const STARTED_EVENT_CHANNEL_ID: Uuid = Uuid::from_u128(0x3f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7a90);
+const STARTED_EVENT_CREATOR: &str = "macro|[email protected]";
+
+#[derive(Clone, Copy)]
+enum GetOrCreateScenario {
+ CreatorWins,
+ RaceLoses,
+ ExistingCall,
+}
+
+fn started_event_timestamp() -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339("2026-07-27T18:01:02Z")
+ .expect("valid timestamp")
+ .with_timezone(&Utc)
+}
+
+fn started_event_call(created_by: &str) -> Call {
+ Call {
+ id: STARTED_EVENT_CALL_ID,
+ channel_id: STARTED_EVENT_CHANNEL_ID,
+ room_name: STARTED_EVENT_CHANNEL_ID.to_string(),
+ created_by: created_by.to_string(),
+ created_at: started_event_timestamp(),
+ egress_id: None,
+ }
+}
+
+fn mock_get_or_create_repo(
+ scenario: GetOrCreateScenario,
+ call: Call,
+ recording_enabled: bool,
+) -> MockCallRepository {
+ let mut repo = MockCallRepository::new();
+
+ match scenario {
+ GetOrCreateScenario::CreatorWins => {
+ repo.expect_get_call_by_channel_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(None) }));
+
+ repo.expect_create_call()
+ .times(1)
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(Some(call)) }));
+
+ repo.expect_resolve_channel_name()
+ .times(1)
+ .returning(|_, _| {
+ Box::pin(async {
+ Err(anyhow::anyhow!(
+ "skip push notifications in get_or_create_call tests"
+ ))
+ })
+ });
+ }
+ GetOrCreateScenario::RaceLoses => {
+ let mut sequence = mockall::Sequence::new();
+ repo.expect_get_call_by_channel_id()
+ .times(1)
+ .in_sequence(&mut sequence)
+ .returning(|_| Box::pin(async { Ok(None) }));
+ repo.expect_get_call_by_channel_id()
+ .times(1)
+ .in_sequence(&mut sequence)
+ .return_once(move |_| Box::pin(async move { Ok(Some(call)) }));
+ repo.expect_create_call()
+ .times(1)
+ .returning(|_, _, _, _| Box::pin(async { Ok(None) }));
+ }
+ GetOrCreateScenario::ExistingCall => {
+ repo.expect_get_call_by_channel_id()
+ .times(1)
+ .return_once(move |_| Box::pin(async move { Ok(Some(call)) }));
+ }
+ }
+
+ if recording_enabled {
+ repo.expect_set_egress_id()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+ }
+
+ repo.expect_find_active_call_for_user()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(None) }));
+ repo.expect_add_participant()
+ .times(1)
+ .returning(|call_id, user_id| {
+ let participant = CallParticipant {
+ call_id: *call_id,
+ user_id: user_id.as_ref().to_string(),
+ joined_at: started_event_timestamp(),
+ };
+ Box::pin(async move { Ok(participant) })
+ });
+
+ repo
+}
+
+type BaseGetOrCreateCallService = CallServiceImpl<
+ MockCallRepository,
+ MockRtcClient,
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ NoopCallSummarizer,
+>;
+
+fn build_get_or_create_service<B: MacroEventBroker + Clone>(
+ repo: MockCallRepository,
+ event_broker: B,
+ recording_enabled: bool,
+) -> impl CallService {
+ let service: BaseGetOrCreateCallService = CallServiceImpl::new(
+ repo,
+ MockRtcClient::new(),
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ "wss://livekit.example.com",
+ );
+ let service = if recording_enabled {
+ service.with_egress(EgressS3Config {
+ bucket: "recordings".to_string(),
+ region: "us-east-1".to_string(),
+ access_key: "access-key".to_string(),
+ secret: "secret".to_string(),
+ })
+ } else {
+ service
+ };
+
+ service.with_event_broker(event_broker)
+}
+
+async fn get_or_create_call(
+ scenario: GetOrCreateScenario,
+ created_by: &str,
+ broker: RecordingEventBroker,
+ recording_enabled: bool,
+) -> Result<crate::domain::models::CallTokenResponse, CallError> {
+ let call = started_event_call(created_by);
+ let repo = mock_get_or_create_repo(scenario, call, recording_enabled);
+ let service = build_get_or_create_service(repo, broker, recording_enabled);
+
+ service
+ .get_or_create_call(&STARTED_EVENT_CHANNEL_ID, user("[email protected]"))
+ .await
+}
+
+#[tokio::test]
+async fn get_or_create_call_publishes_started_event() {
+ let broker = RecordingEventBroker::default();
+
+ let response = get_or_create_call(
+ GetOrCreateScenario::CreatorWins,
+ STARTED_EVENT_CREATOR,
+ broker.clone(),
+ true,
+ )
+ .await
+ .expect("call creation succeeds");
+
+ assert_eq!(response.call_id, STARTED_EVENT_CALL_ID);
+ let events = broker.events();
+ let [published] = events.as_slice() else {
+ panic!("expected exactly one call event")
+ };
+ assert_eq!(published.topic, "macro.calls");
+ assert_eq!(published.key, STARTED_EVENT_CALL_ID.to_string());
+ assert!(!published.key.starts_with("call|"));
+
+ let event_id = published.envelope["event_id"]
+ .as_str()
+ .expect("event id is a string");
+ Uuid::parse_str(event_id).expect("event id is a UUID");
+
+ let mut envelope = published.envelope.clone();
+ envelope
+ .as_object_mut()
+ .expect("event envelope is an object")
+ .remove("event_id");
+ assert_eq!(
+ envelope,
+ json!({
+ "schema_version": 1,
+ "event_type": "call.started",
+ "metadata": {
+ "call_id": STARTED_EVENT_CALL_ID,
+ "channel_id": STARTED_EVENT_CHANNEL_ID,
+ "created_by": STARTED_EVENT_CREATOR,
+ "created_at": "2026-07-27T18:01:02Z",
+ "recording_enabled": true,
+ },
+ })
+ );
+}
+
+#[tokio::test]
+async fn get_or_create_call_race_loser_does_not_publish_started_event() {
+ let broker = RecordingEventBroker::default();
+
+ get_or_create_call(
+ GetOrCreateScenario::RaceLoses,
+ STARTED_EVENT_CREATOR,
+ broker.clone(),
+ false,
+ )
+ .await
+ .expect("race loser joins the winning call");
+
+ assert!(broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn get_or_create_call_existing_call_does_not_publish_started_event() {
+ let broker = RecordingEventBroker::default();
+
+ get_or_create_call(
+ GetOrCreateScenario::ExistingCall,
+ STARTED_EVENT_CREATOR,
+ broker.clone(),
+ false,
+ )
+ .await
+ .expect("existing call can be joined");
+
+ assert!(broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn broker_scheduling_failure_does_not_fail_call_creation() {
+ let broker = RecordingEventBroker::failing();
+
+ let response = get_or_create_call(
+ GetOrCreateScenario::CreatorWins,
+ STARTED_EVENT_CREATOR,
+ broker.clone(),
+ false,
+ )
+ .await
+ .expect("broker failure is best-effort");
+
+ assert_eq!(response.call_id, STARTED_EVENT_CALL_ID);
+ assert!(broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn malformed_stored_creator_skips_only_started_event() {
+ let broker = RecordingEventBroker::default();
+
+ let response = get_or_create_call(
+ GetOrCreateScenario::CreatorWins,
+ "malformed-user-id",
+ broker.clone(),
+ false,
+ )
+ .await
+ .expect("malformed stored creator does not fail call creation");
+
+ assert_eq!(response.call_id, STARTED_EVENT_CALL_ID);
+ assert!(broker.events().is_empty());
+}
+
+const ARCHIVED_EVENT_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b6d8);
+const ARCHIVED_EVENT_CHANNEL_ID: Uuid = Uuid::from_u128(0x4f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7a91);
+const ARCHIVED_EVENT_ROOM_NAME: &str = "archived-event-room";
+const ARCHIVED_EVENT_CREATOR: &str = "macro|[email protected]";
+const ARCHIVED_EVENT_PARTICIPANT: &str = "[email protected]";
+const RECORDING_READY_EGRESS_ID: &str = "recording-ready-egress";
+const RECORDING_READY_FILE_URL: &str =
+ "https://recordings.example.com/calls/0198a1b2-c3d4-7e5f-8061-728394a5b6d8/recording.mp4";
+const RECORDING_READY_KEY: &str = "0198a1b2-c3d4-7e5f-8061-728394a5b6d8/recording.mp4";
+
+fn archived_event_started_at() -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339("2026-07-27T18:01:02Z")
+ .expect("valid timestamp")
+ .with_timezone(&Utc)
+}
+
+fn archived_event_ended_at() -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339("2026-07-27T18:04:05Z")
+ .expect("valid timestamp")
+ .with_timezone(&Utc)
+}
+
+fn active_call_for_archived_event(created_by: &str, egress_id: Option<&str>) -> Call {
+ Call {
+ id: ARCHIVED_EVENT_CALL_ID,
+ channel_id: ARCHIVED_EVENT_CHANNEL_ID,
+ room_name: ARCHIVED_EVENT_ROOM_NAME.to_string(),
+ created_by: created_by.to_string(),
+ created_at: archived_event_started_at(),
+ egress_id: egress_id.map(str::to_string),
+ }
+}
+
+fn archived_call_for_event(
+ created_by: &str,
+ participant_count: usize,
+ has_recording: bool,
+) -> ArchivedCall {
+ ArchivedCall {
+ call_id: ARCHIVED_EVENT_CALL_ID,
+ channel_id: ARCHIVED_EVENT_CHANNEL_ID,
+ created_by: created_by.to_string(),
+ started_at: archived_event_started_at(),
+ ended_at: archived_event_ended_at(),
+ duration_ms: 183_000,
+ has_recording,
+ participant_count,
+ }
+}
+
+fn egress_ended_rtc_client(egress_id: Option<&str>, file_url: Option<&str>) -> MockCallRtcClient {
+ let event = CallWebhookEvent {
+ event: "egress_ended".to_string(),
+ id: "egress-ended-event-id".to_string(),
+ room_name: None,
+ participant_identity: None,
+ egress_id: egress_id.map(str::to_string),
+ file_url: file_url.map(str::to_string),
+ created_at: 1_775_000_000,
+ };
+ let mut rtc_client = MockCallRtcClient::new();
+ rtc_client
+ .expect_receive_webhook()
+ .times(1)
+ .return_once(move |body, auth_token| {
+ assert_eq!(body, "webhook-body");
+ assert_eq!(auth_token, "webhook-token");
+ Ok(event)
+ });
+ rtc_client
+}
+
+fn webhook_rtc_client(
+ event_type: &str,
+ participant_identity: Option<&'static str>,
+) -> MockCallRtcClient {
+ let event = CallWebhookEvent {
+ event: event_type.to_string(),
+ id: format!("{event_type}-event-id"),
+ room_name: Some(ARCHIVED_EVENT_ROOM_NAME.to_string()),
+ participant_identity: participant_identity.map(|email| user(email).into_owned()),
+ egress_id: None,
+ file_url: None,
+ created_at: 1_775_000_000,
+ };
+ let mut rtc_client = MockCallRtcClient::new();
+ rtc_client
+ .expect_receive_webhook()
+ .times(1)
+ .return_once(move |body, auth_token| {
+ assert_eq!(body, "webhook-body");
+ assert_eq!(auth_token, "webhook-token");
+ Ok(event)
+ });
+ rtc_client
+}
+
+type BaseWebhookCallService = CallServiceImpl<
+ MockCallRepository,
+ MockCallRtcClient,
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ NoopCallSummarizer,
+>;
+
+fn build_webhook_service(
+ repo: MockCallRepository,
+ rtc_client: MockCallRtcClient,
+ event_broker: RecordingEventBroker,
+) -> impl CallService {
+ let service: BaseWebhookCallService = CallServiceImpl::new(
+ repo,
+ rtc_client,
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ "wss://livekit.example.com",
+ );
+ service.with_event_broker(event_broker)
+}
+
+fn assert_archived_event(
+ event_broker: &RecordingEventBroker,
+ archive_reason: &str,
+ participant_count: usize,
+ has_recording: bool,
+) {
+ let events = event_broker.events();
+ let [published] = events.as_slice() else {
+ panic!("expected exactly one call event")
+ };
+ assert_eq!(published.topic, "macro.calls");
+ assert_eq!(published.key, ARCHIVED_EVENT_CALL_ID.to_string());
+
+ let event_id = published.envelope["event_id"]
+ .as_str()
+ .expect("event id is a string");
+ Uuid::parse_str(event_id).expect("event id is a UUID");
+
+ let mut envelope = published.envelope.clone();
+ envelope
+ .as_object_mut()
+ .expect("event envelope is an object")
+ .remove("event_id");
+ assert_eq!(
+ envelope,
+ json!({
+ "schema_version": 1,
+ "event_type": "call.record_archived",
+ "metadata": {
+ "call_id": ARCHIVED_EVENT_CALL_ID,
+ "channel_id": ARCHIVED_EVENT_CHANNEL_ID,
+ "created_by": ARCHIVED_EVENT_CREATOR,
+ "started_at": "2026-07-27T18:01:02Z",
+ "ended_at": "2026-07-27T18:04:05Z",
+ "duration_ms": 183_000,
+ "participant_count": participant_count,
+ "has_recording": has_recording,
+ "archive_reason": archive_reason,
+ },
+ })
+ );
+}
+
+#[tokio::test]
+async fn participant_left_publishes_last_participant_archived_event() {
+ let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);
+ let archived_call = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 4, false);
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_room_name()
+ .times(1)
+ .return_once(move |room_name| {
+ assert_eq!(room_name, ARCHIVED_EVENT_ROOM_NAME);
+ Box::pin(async move { Ok(Some(active_call)) })
+ });
+ repo.expect_remove_participant()
+ .times(1)
+ .returning(|call_id, participant_identity| {
+ assert_eq!(*call_id, ARCHIVED_EVENT_CALL_ID);
+ assert_eq!(
+ participant_identity.as_ref(),
+ user(ARCHIVED_EVENT_PARTICIPANT).as_ref()
+ );
+ Box::pin(async { Ok(()) })
+ });
+ repo.expect_get_participant_count()
+ .times(1)
+ .returning(|call_id| {
+ assert_eq!(*call_id, ARCHIVED_EVENT_CALL_ID);
+ Box::pin(async { Ok(0) })
+ });
+ repo.expect_archive_call()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, ARCHIVED_EVENT_CALL_ID);
+ Box::pin(async move { Ok(archived_call) })
+ });
+
+ let mut rtc_client = webhook_rtc_client("participant_left", Some(ARCHIVED_EVENT_PARTICIPANT));
+ rtc_client
+ .expect_delete_room()
+ .times(1)
+ .returning(|room_name| {
+ assert_eq!(room_name, ARCHIVED_EVENT_ROOM_NAME);
+ Box::pin(async { Ok(()) })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("participant-left webhook succeeds");
+
+ assert_archived_event(&event_broker, "last_participant_left", 4, false);
+}
+
+#[tokio::test]
+async fn room_finished_publishes_room_finished_archived_event() {
+ let active_call = active_call_for_archived_event(
+ Some("archived-event-egress"),
+ );
+ let archived_call = archived_call_for_event(ARCHIVED_EVENT_CREATOR, 3, true);
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_room_name()
+ .times(1)
+ .return_once(move |room_name| {
+ assert_eq!(room_name, ARCHIVED_EVENT_ROOM_NAME);
+ Box::pin(async move { Ok(Some(active_call)) })
+ });
+ repo.expect_archive_call()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, ARCHIVED_EVENT_CALL_ID);
+ Box::pin(async move { Ok(archived_call) })
+ });
+
+ let rtc_client = webhook_rtc_client("room_finished", None);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("room-finished webhook succeeds");
+
+ assert_archived_event(&event_broker, "room_finished", 3, true);
+}
+
+#[tokio::test]
+async fn failed_archive_does_not_publish_archived_event() {
+ let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_room_name()
+ .times(1)
+ .return_once(move |_| Box::pin(async move { Ok(Some(active_call)) }));
+ repo.expect_archive_call()
+ .times(1)
+ .returning(|_| Box::pin(async { Err(anyhow::anyhow!("archive failed")) }));
+
+ let rtc_client = webhook_rtc_client("room_finished", None);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ assert!(
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn malformed_archived_creator_skips_event_without_undoing_archival() {
+ let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);
+ let archived_call = archived_call_for_event("malformed-user-id", 1, false);
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_room_name()
+ .times(1)
+ .return_once(move |_| Box::pin(async move { Ok(Some(active_call)) }));
+ repo.expect_archive_call()
+ .times(1)
+ .return_once(move |_| Box::pin(async move { Ok(archived_call) }));
+
+ let rtc_client = webhook_rtc_client("room_finished", None);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("malformed creator does not undo archival");
+ assert!(event_broker.events().is_empty());
+}
+
+fn assert_recording_ready_event(event_broker: &RecordingEventBroker) {
+ let events = event_broker.events();
+ let [published] = events.as_slice() else {
+ panic!("expected exactly one recording-ready event")
+ };
+ assert_eq!(published.topic, "macro.calls");
+ assert_eq!(published.key, ARCHIVED_EVENT_CALL_ID.to_string());
+
+ let event_id = published.envelope["event_id"]
+ .as_str()
+ .expect("event id is a string");
+ Uuid::parse_str(event_id).expect("event id is a UUID");
+
+ let mut envelope = published.envelope.clone();
+ envelope
+ .as_object_mut()
+ .expect("event envelope is an object")
+ .remove("event_id");
+ assert_eq!(
+ envelope,
+ json!({
+ "schema_version": 1,
+ "event_type": "call.recording_ready",
+ "metadata": {
+ "call_id": ARCHIVED_EVENT_CALL_ID,
+ "channel_id": ARCHIVED_EVENT_CHANNEL_ID,
+ },
+ })
+ );
+ assert!(!published.envelope.to_string().contains(RECORDING_READY_KEY));
+}
+
+#[tokio::test]
+async fn archived_egress_ended_publishes_recording_ready_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_egress_id()
+ .times(1)
+ .returning(|egress_id| {
+ assert_eq!(egress_id, RECORDING_READY_EGRESS_ID);
+ Box::pin(async { Ok(Some((ARCHIVED_EVENT_CALL_ID, ARCHIVED_EVENT_CHANNEL_ID))) })
+ });
+ repo.expect_set_recording_key()
+ .times(1)
+ .returning(|call_id, recording_key| {
+ assert_eq!(*call_id, ARCHIVED_EVENT_CALL_ID);
+ assert_eq!(recording_key, RECORDING_READY_KEY);
+ Box::pin(async { Ok(()) })
+ });
+ let rtc_client = egress_ended_rtc_client(
+ Some(RECORDING_READY_EGRESS_ID),
+ Some(RECORDING_READY_FILE_URL),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("archived egress-ended webhook succeeds");
+
+ assert_recording_ready_event(&event_broker);
+}
+
+#[tokio::test]
+async fn active_egress_ended_does_not_publish_recording_ready_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_egress_id()
+ .times(1)
+ .returning(|egress_id| {
+ assert_eq!(egress_id, RECORDING_READY_EGRESS_ID);
+ Box::pin(async { Ok(None) })
+ });
+ repo.expect_set_active_call_recording_key()
+ .times(1)
+ .returning(|egress_id, recording_key| {
+ assert_eq!(egress_id, RECORDING_READY_EGRESS_ID);
+ assert_eq!(recording_key, RECORDING_READY_KEY);
+ Box::pin(async { Ok(true) })
+ });
+ let rtc_client = egress_ended_rtc_client(
+ Some(RECORDING_READY_EGRESS_ID),
+ Some(RECORDING_READY_FILE_URL),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("active egress-ended webhook succeeds");
+
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn egress_ended_with_missing_fields_does_not_publish_recording_ready_event() {
+ for (egress_id, file_url) in [
+ (None, Some(RECORDING_READY_FILE_URL)),
+ (Some(RECORDING_READY_EGRESS_ID), None),
+ ] {
+ let repo = MockCallRepository::new();
+ let rtc_client = egress_ended_rtc_client(egress_id, file_url);
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("incomplete egress-ended webhook is ignored");
+
+ assert!(event_broker.events().is_empty());
+ }
+}
+
+#[tokio::test]
+async fn unknown_egress_ended_does_not_publish_recording_ready_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_egress_id()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(None) }));
+ repo.expect_set_active_call_recording_key()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Ok(false) }));
+ let rtc_client = egress_ended_rtc_client(
+ Some(RECORDING_READY_EGRESS_ID),
+ Some(RECORDING_READY_FILE_URL),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("unknown egress-ended webhook is ignored");
+
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn failed_recording_key_persistence_does_not_publish_recording_ready_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_egress_id()
+ .times(1)
+ .returning(|_| {
+ Box::pin(async { Ok(Some((ARCHIVED_EVENT_CALL_ID, ARCHIVED_EVENT_CHANNEL_ID))) })
+ });
+ repo.expect_set_recording_key()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Err(anyhow::anyhow!("recording key write failed")) }));
+ let rtc_client = egress_ended_rtc_client(
+ Some(RECORDING_READY_EGRESS_ID),
+ Some(RECORDING_READY_FILE_URL),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_webhook_service(repo, rtc_client, event_broker.clone());
+
+ assert!(
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+}
+
+const MUTATED_EVENT_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b6e9);
+const MUTATED_EVENT_CHANNEL_ID: Uuid = Uuid::from_u128(0x5f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7a92);
+const MUTATED_EVENT_ACTOR: &str = "macro|[email protected]";
+
+fn call_record_for_mutation() -> CallRecord {
+ CallRecord {
+ call_id: MUTATED_EVENT_CALL_ID,
+ channel_id: MUTATED_EVENT_CHANNEL_ID,
+ room_name: "mutation-event-room".to_string(),
+ created_by: "macro|[email protected]".to_string(),
+ started_at: archived_event_started_at(),
+ ended_at: Some(archived_event_ended_at()),
+ duration_ms: Some(183_000),
+ egress_id: None,
+ recording_started_at: None,
+ recording_key: None,
+ preview_key: None,
+ recording_url: None,
+ recording_preview_url: None,
+ channel_name: None,
+ custom_name: None,
+ summary: None,
+ share_with_team: false,
+ is_active: false,
+ status: None,
+ user_access_level: None,
+ participants: Vec::new(),
+ transcript: Vec::new(),
+ }
+}
+
+fn authenticated_mutation_receipt() -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_authenticated_user(
+ &MUTATED_EVENT_CALL_ID.to_string(),
+ EntityType::Call,
+ )
+}
+
+fn internal_mutation_receipt() -> EntityAccessReceipt<EditAccessLevel> {
+ EntityAccessReceipt::dangerously_assert_internal_user(
+ &MUTATED_EVENT_CALL_ID.to_string(),
+ EntityType::Call,
+ )
+}
+
+type BaseMutationCallService = CallServiceImpl<
+ MockCallRepository,
+ MockRtcClient,
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ NoopCallSummarizer,
+>;
+
+fn build_mutation_service(
+ repo: MockCallRepository,
+ event_broker: RecordingEventBroker,
+) -> impl CallService + DeleteEntityPermanently<Receipt = EditAccessLevel> {
+ let service: BaseMutationCallService = CallServiceImpl::new(
+ repo,
+ MockRtcClient::new(),
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ "wss://livekit.example.com",
+ );
+ service.with_event_broker(event_broker)
+}
+
+fn assert_updated_event(
+ event_broker: &RecordingEventBroker,
+ actor_user_id: Option<&str>,
+ custom_name: Option<&str>,
+ share_with_team: Option<bool>,
+) {
+ let events = event_broker.events();
+ let [published] = events.as_slice() else {
+ panic!("expected exactly one call event")
+ };
+ assert_eq!(published.topic, "macro.calls");
+ assert_eq!(published.key, MUTATED_EVENT_CALL_ID.to_string());
+
+ let mut envelope = published.envelope.clone();
+ envelope
+ .as_object_mut()
+ .expect("event envelope is an object")
+ .remove("event_id");
+ assert_eq!(
+ envelope,
+ json!({
+ "schema_version": 1,
+ "event_type": "call.record_updated",
+ "metadata": {
+ "call_id": MUTATED_EVENT_CALL_ID,
+ "channel_id": MUTATED_EVENT_CHANNEL_ID,
+ "actor_user_id": actor_user_id,
+ "custom_name": custom_name,
+ "share_with_team": share_with_team,
+ },
+ })
+ );
+}
+
+fn assert_deleted_event(event_broker: &RecordingEventBroker) {
+ let events = event_broker.events();
+ let [published] = events.as_slice() else {
+ panic!("expected exactly one call event")
+ };
+ assert_eq!(published.topic, "macro.calls");
+ assert_eq!(published.key, MUTATED_EVENT_CALL_ID.to_string());
+
+ let mut envelope = published.envelope.clone();
+ envelope
+ .as_object_mut()
+ .expect("event envelope is an object")
+ .remove("event_id");
+ assert_eq!(
+ envelope,
+ json!({
+ "schema_version": 1,
+ "event_type": "call.record_deleted",
+ "metadata": {
+ "call_id": MUTATED_EVENT_CALL_ID,
+ "channel_id": MUTATED_EVENT_CHANNEL_ID,
+ "actor_user_id": MUTATED_EVENT_ACTOR,
+ },
+ })
+ );
+}
+
+fn mock_edit_repo(
+ record: Option<CallRecord>,
+ expected_custom_name: Option<&'static str>,
+ expected_share_with_team: Option<bool>,
+ expect_share_permission: bool,
+ patch_result: anyhow::Result<()>,
+) -> MockCallRepository {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ Box::pin(async move { Ok(record) })
+ });
+ repo.expect_patch_call_record()
+ .times(1)
+ .return_once(move |call_id, request| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ assert_eq!(request.custom_name.as_deref(), expected_custom_name);
+ assert_eq!(request.share_with_team, expected_share_with_team);
+ assert_eq!(request.share_permission.is_some(), expect_share_permission);
+ Box::pin(async move { patch_result })
+ });
+ repo
+}
+
+#[tokio::test]
+async fn edit_call_record_publishes_updated_event() {
+ let repo = mock_edit_repo(
+ Some(call_record_for_mutation()),
+ Some("Weekly sync"),
+ None,
+ false,
+ Ok(()),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ authenticated_mutation_receipt(),
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: None,
+ custom_name: Some("Weekly sync".to_string()),
+ },
+ )
+ .await
+ .expect("rename succeeds");
+
+ assert_updated_event(
+ &event_broker,
+ Some(MUTATED_EVENT_ACTOR),
+ Some("Weekly sync"),
+ None,
+ );
+}
+
+#[tokio::test]
+async fn edit_call_record_publishes_updated_event_when_name_is_cleared() {
+ let repo = mock_edit_repo(
+ Some(call_record_for_mutation()),
+ Some(""),
+ None,
+ false,
+ Ok(()),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ authenticated_mutation_receipt(),
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: None,
+ custom_name: Some(String::new()),
+ },
+ )
+ .await
+ .expect("clearing the name succeeds");
+
+ assert_updated_event(&event_broker, Some(MUTATED_EVENT_ACTOR), Some(""), None);
+}
+
+#[tokio::test]
+async fn edit_call_record_publishes_updated_event_for_share_permission_only() {
+ let repo = mock_edit_repo(Some(call_record_for_mutation()), None, None, true, Ok(()));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ authenticated_mutation_receipt(),
+ EditCallRecordRequest {
+ share_permission: Some(
+ models_permissions::share_permission::UpdateSharePermissionRequestV2 {
+ is_public: Some(true),
+ public_access_level: None,
+ channel_share_permissions: None,
+ },
+ ),
+ share_with_team: None,
+ custom_name: None,
+ },
+ )
+ .await
+ .expect("share-permission update succeeds");
+
+ assert_updated_event(&event_broker, Some(MUTATED_EVENT_ACTOR), None, None);
+ assert!(
+ !event_broker.events()[0]
+ .envelope
+ .to_string()
+ .contains("share_permission")
+ );
+}
+
+#[tokio::test]
+async fn edit_call_record_publishes_updated_event_without_an_internal_actor() {
+ let repo = mock_edit_repo(
+ Some(call_record_for_mutation()),
+ Some("Internal rename"),
+ Some(false),
+ false,
+ Ok(()),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ internal_mutation_receipt(),
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: Some(false),
+ custom_name: Some("Internal rename".to_string()),
+ },
+ )
+ .await
+ .expect("internal edit succeeds");
+
+ assert_updated_event(&event_broker, None, Some("Internal rename"), Some(false));
+}
+
+#[tokio::test]
+async fn edit_call_record_skips_updated_event_for_unknown_record() {
+ let repo = mock_edit_repo(None, Some("Unknown"), None, false, Ok(()));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .edit_call_record(
+ authenticated_mutation_receipt(),
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: None,
+ custom_name: Some("Unknown".to_string()),
+ },
+ )
+ .await
+ .expect("unknown record edit remains idempotent");
+
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn failed_edit_call_record_does_not_publish_updated_event() {
+ let repo = mock_edit_repo(
+ Some(call_record_for_mutation()),
+ Some("Failed rename"),
+ None,
+ false,
+ Err(anyhow::anyhow!("patch failed")),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ assert!(
+ service
+ .edit_call_record(
+ authenticated_mutation_receipt(),
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: None,
+ custom_name: Some("Failed rename".to_string()),
+ },
+ )
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn toggle_share_with_team_publishes_updated_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_toggle_share_with_team()
+ .times(1)
+ .returning(|call_id| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ Box::pin(async { Ok((true, MUTATED_EVENT_CHANNEL_ID)) })
+ });
+ repo.expect_get_participants()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Vec::new()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ let share_with_team = service
+ .toggle_share_with_team(authenticated_mutation_receipt())
+ .await
+ .expect("share toggle succeeds");
+
+ assert!(share_with_team);
+ assert_updated_event(&event_broker, Some(MUTATED_EVENT_ACTOR), None, Some(true));
+}
+
+#[tokio::test]
+async fn failed_toggle_share_with_team_does_not_publish_updated_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_toggle_share_with_team()
+ .times(1)
+ .returning(|_| Box::pin(async { Err(anyhow::anyhow!("toggle failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ assert!(
+ service
+ .toggle_share_with_team(authenticated_mutation_receipt())
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+}
+
+fn mock_delete_repo(
+ record: Option<CallRecord>,
+ delete_result: anyhow::Result<Option<DeletedCallRecordStorageKeys>>,
+) -> MockCallRepository {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ Box::pin(async move { Ok(record) })
+ });
+ repo.expect_delete_call_record()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ Box::pin(async move { delete_result })
+ });
+ repo
+}
+
+#[tokio::test]
+async fn delete_call_record_publishes_deleted_event() {
+ let repo = mock_delete_repo(
+ Some(call_record_for_mutation()),
+ Ok(Some(DeletedCallRecordStorageKeys::default())),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .delete_call_record(authenticated_mutation_receipt())
+ .await
+ .expect("deletion succeeds");
+
+ assert_deleted_event(&event_broker);
+}
+
+#[tokio::test]
+async fn no_op_delete_call_record_does_not_publish_deleted_event() {
+ let repo = mock_delete_repo(None, Ok(None));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ service
+ .delete_call_record(authenticated_mutation_receipt())
+ .await
+ .expect("unknown record deletion remains idempotent");
+
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn failed_delete_call_record_does_not_publish_deleted_event() {
+ let repo = mock_delete_repo(
+ Some(call_record_for_mutation()),
+ Err(anyhow::anyhow!("delete failed")),
+ );
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+
+ assert!(
+ service
+ .delete_call_record(authenticated_mutation_receipt())
+ .await
+ .is_err()
+ );
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn delete_entity_permanently_publishes_one_deleted_event() {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_record_by_call_id()
+ .times(2)
+ .returning(|call_id| {
+ assert_eq!(*call_id, MUTATED_EVENT_CALL_ID);
+ Box::pin(async { Ok(Some(call_record_for_mutation())) })
+ });
+ repo.expect_resolve_channel_name()
+ .times(1)
+ .returning(|channel_id, user_id| {
+ assert_eq!(*channel_id, MUTATED_EVENT_CHANNEL_ID);
+ assert_eq!(user_id.as_ref(), MUTATED_EVENT_ACTOR);
+ Box::pin(async { Ok(None) })
+ });
+ repo.expect_delete_call_record()
+ .times(1)
+ .returning(|_| Box::pin(async { Ok(Some(DeletedCallRecordStorageKeys::default())) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = build_mutation_service(repo, event_broker.clone());
+ let entity =
+ model_entity::EntityType::Call.with_entity_string(MUTATED_EVENT_CALL_ID.to_string());
+
+ service
+ .delete_entity_permanently(entity, authenticated_mutation_receipt())
+ .await
+ .expect("entity mutation deletion succeeds");
+
+ assert_deleted_event(&event_broker);
+}
+
+const SUMMARIZED_EVENT_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b700);
+const SUMMARIZED_EVENT_CHANNEL_ID: Uuid = Uuid::from_u128(0x6f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7a93);
+const SUMMARIZED_EVENT_SUMMARY: &str = "Private generated summary text";
+const SUMMARIZED_EVENT_NAME: &str = "Private generated call name";
+
+#[derive(Clone, Copy)]
+enum GeneratedNameResult {
+ Generated,
+ NoName,
+ Failed,
+}
+
+#[derive(Clone)]
+struct StubCallSummarizer {
+ summary: Option<&'static str>,
+ generated_name: GeneratedNameResult,
+ summary_calls: Arc<AtomicUsize>,
+ name_calls: Arc<AtomicUsize>,
+}
+
+impl StubCallSummarizer {
+ fn new(summary: Option<&'static str>, generated_name: GeneratedNameResult) -> Self {
+ Self {
+ summary,
+ generated_name,
+ summary_calls: Arc::new(AtomicUsize::new(0)),
+ name_calls: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+
+ fn name_calls(&self) -> usize {
+ self.name_calls.load(Ordering::SeqCst)
+ }
+}
+
+impl CallSummarizer for StubCallSummarizer {
+ type Err = anyhow::Error;
+
+ async fn summarize_call(
+ &self,
+ call_id: &Uuid,
+ transcript: Vec<CallRecordTranscriptSegment>,
+ ) -> Result<Option<String>, Self::Err> {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ assert_eq!(transcript.len(), 1);
+ self.summary_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(self.summary.map(str::to_string))
+ }
+
+ async fn generate_call_name(
+ &self,
+ call_id: &Uuid,
+ summary: &str,
+ ) -> Result<Option<String>, Self::Err> {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ assert_eq!(summary, SUMMARIZED_EVENT_SUMMARY);
+ self.name_calls.fetch_add(1, Ordering::SeqCst);
+
+ match self.generated_name {
+ GeneratedNameResult::Generated => Ok(Some(SUMMARIZED_EVENT_NAME.to_string())),
+ GeneratedNameResult::NoName => Ok(None),
+ GeneratedNameResult::Failed => Err(anyhow::anyhow!("call naming failed")),
+ }
+ }
+
+ async fn generate_custom_speakers(
+ &self,
+ _transcript: Vec<crate::domain::models::EnrichedCallTranscript>,
+ _candidate_speakers: Vec<MacroUserIdStr<'static>>,
+ ) -> Result<Vec<crate::domain::models::CallTranscriptCustomSpeakerResult>, Self::Err> {
+ Ok(Vec::new())
+ }
+}
+
+#[derive(Clone, Copy)]
+enum NamePersistence {
+ NotAttempted,
+ Persisted(bool),
+ Failed,
+}
+
+fn summarized_call_record(custom_name: Option<&str>) -> CallRecord {
+ CallRecord {
+ call_id: SUMMARIZED_EVENT_CALL_ID,
+ channel_id: SUMMARIZED_EVENT_CHANNEL_ID,
+ room_name: SUMMARIZED_EVENT_CHANNEL_ID.to_string(),
+ created_by: "macro|[email protected]".to_string(),
+ started_at: started_event_timestamp(),
+ ended_at: Some(started_event_timestamp()),
+ duration_ms: Some(10_000),
+ egress_id: None,
+ recording_started_at: None,
+ recording_key: None,
+ preview_key: None,
+ recording_url: None,
+ recording_preview_url: None,
+ channel_name: None,
+ custom_name: custom_name.map(str::to_string),
+ summary: None,
+ share_with_team: false,
+ is_active: false,
+ status: None,
+ user_access_level: None,
+ participants: Vec::new(),
+ transcript: vec![CallRecordTranscriptSegment {
+ transcript_id: Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b701),
+ segment_id: Some("segment-1".to_string()),
+ speaker_id: "macro|[email protected]".to_string(),
+ diarized_speaker_id: Some("speaker-1".to_string()),
+ content: "Discuss the event publication behavior.".to_string(),
+ started_at: started_event_timestamp(),
+ ended_at: Some(started_event_timestamp()),
+ sequence_num: 1,
+ }],
+ }
+}
+
+fn mock_summarization_repo(
+ custom_name: Option<&str>,
+ summary_persisted: Option<bool>,
+ name_persistence: NamePersistence,
+) -> MockCallRepository {
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_enhanced_call_record_transcripts()
+ .times(1)
+ .returning(|call_id| {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ Box::pin(async { Ok(Vec::new()) })
+ });
+
+ let record = summarized_call_record(custom_name);
+ repo.expect_get_call_record_by_call_id()
+ .times(1)
+ .return_once(move |call_id| {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ Box::pin(async move { Ok(Some(record)) })
+ });
+
+ if let Some(summary_persisted) = summary_persisted {
+ repo.expect_insert_call_summary()
+ .times(1)
+ .returning(move |call_id, summary| {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ assert_eq!(summary, SUMMARIZED_EVENT_SUMMARY);
+ Box::pin(async move { Ok(summary_persisted) })
+ });
+ }
+
+ match name_persistence {
+ NamePersistence::NotAttempted => {}
+ NamePersistence::Persisted(name_persisted) => {
+ repo.expect_set_custom_name_if_null()
+ .times(1)
+ .returning(move |call_id, name| {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ assert_eq!(name, SUMMARIZED_EVENT_NAME);
+ Box::pin(async move { Ok(name_persisted) })
+ });
+ }
+ NamePersistence::Failed => {
+ repo.expect_set_custom_name_if_null()
+ .times(1)
+ .returning(|call_id, name| {
+ assert_eq!(*call_id, SUMMARIZED_EVENT_CALL_ID);
+ assert_eq!(name, SUMMARIZED_EVENT_NAME);
+ Box::pin(async { Err(anyhow::anyhow!("name persistence failed")) })
+ });
+ }
+ }
+
+ repo
+}
+
+type SummarizationCallService<B> = CallServiceImpl<
+ MockCallRepository,
+ MockRtcClient,
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ StubCallSummarizer,
+ NoOpCallSearchIndexer,
+ (),
+ NoOpVoiceRepository,
+ B,
+>;
+
+fn build_summarization_service<B: MacroEventBroker>(
+ repo: MockCallRepository,
+ summarizer: StubCallSummarizer,
+ event_broker: B,
+) -> SummarizationCallService<B> {
+ let service = CallServiceImpl::new(
+ repo,
+ MockRtcClient::new(),
+ StubConnectionService,
+ NoOpEntityAccessService,
+ StubNotificationIngress,
+ StubRecordingStorage,
+ "wss://livekit.example.com",
+ )
+ .with_summarizer(summarizer);
+
+ service.with_event_broker(event_broker)
+}
+
+async fn run_direct_summarization(
+ custom_name: Option<&str>,
+ summary: Option<&'static str>,
+ summary_persisted: Option<bool>,
+ generated_name: GeneratedNameResult,
+ name_persistence: NamePersistence,
+ event_broker: RecordingEventBroker,
+) -> (RecordingEventBroker, StubCallSummarizer) {
+ let repo = mock_summarization_repo(custom_name, summary_persisted, name_persistence);
+ let summarizer = StubCallSummarizer::new(summary, generated_name);
+ let observed_broker = event_broker.clone();
+ let service = build_summarization_service(repo, summarizer.clone(), event_broker);
+
+ service
+ .summarize_call(&SUMMARIZED_EVENT_CALL_ID)
+ .await
+ .expect("summarization succeeds");
+
+ (observed_broker, summarizer)
+}
+
+fn assert_summarized_event(event_broker: &RecordingEventBroker, ai_name_generated: bool) {
+ let events = event_broker.events();
+ let [published] = events.as_slice() else {
+ panic!("expected exactly one summarized event")
+ };
+ assert_eq!(published.topic, "macro.calls");
+ assert_eq!(published.key, SUMMARIZED_EVENT_CALL_ID.to_string());
+
+ let event_id = published.envelope["event_id"]
+ .as_str()
+ .expect("event id is a string");
+ Uuid::parse_str(event_id).expect("event id is a UUID");
+
+ let mut envelope = published.envelope.clone();
+ envelope
+ .as_object_mut()
+ .expect("event envelope is an object")
+ .remove("event_id");
+ assert_eq!(
+ envelope,
+ json!({
+ "schema_version": 1,
+ "event_type": "call.record_summarized",
+ "metadata": {
+ "call_id": SUMMARIZED_EVENT_CALL_ID,
+ "channel_id": SUMMARIZED_EVENT_CHANNEL_ID,
+ "ai_name_generated": ai_name_generated,
+ },
+ })
+ );
+
+ let serialized_event = published.envelope.to_string();
+ assert!(!serialized_event.contains(SUMMARIZED_EVENT_SUMMARY));
+ assert!(!serialized_event.contains(SUMMARIZED_EVENT_NAME));
+}
+
+async fn wait_for_spawned_work(mut is_complete: impl FnMut() -> bool) {
+ tokio::time::timeout(Duration::from_secs(2), async {
+ while !is_complete() {
+ tokio::task::yield_now().await;
+ }
+ })
+ .await
+ .expect("spawned summarization completed before timeout");
+}
+
+#[tokio::test]
+async fn summarize_call_publishes_record_summarized_event() {
+ let (broker, _) = run_direct_summarization(
+ None,
+ Some(SUMMARIZED_EVENT_SUMMARY),
+ Some(true),
+ GeneratedNameResult::Generated,
+ NamePersistence::Persisted(true),
+ RecordingEventBroker::default(),
+ )
+ .await;
+ assert_summarized_event(&broker, true);
+
+ let (no_summary_broker, no_summary_summarizer) = run_direct_summarization(
+ None,
+ None,
+ None,
+ GeneratedNameResult::Generated,
+ NamePersistence::NotAttempted,
+ RecordingEventBroker::default(),
+ )
+ .await;
+ assert!(no_summary_broker.events().is_empty());
+ assert_eq!(no_summary_summarizer.name_calls(), 0);
+
+ let (deleted_record_broker, _) = run_direct_summarization(
+ None,
+ Some(SUMMARIZED_EVENT_SUMMARY),
+ Some(false),
+ GeneratedNameResult::Generated,
+ NamePersistence::Persisted(false),
+ RecordingEventBroker::default(),
+ )
+ .await;
+ assert!(deleted_record_broker.events().is_empty());
+
+ let failing_broker = RecordingEventBroker::failing();
+ let (observed_failing_broker, _) = run_direct_summarization(
+ Some("User-provided name"),
+ Some(SUMMARIZED_EVENT_SUMMARY),
+ Some(true),
+ GeneratedNameResult::Generated,
+ NamePersistence::NotAttempted,
+ failing_broker,
+ )
+ .await;
+ assert_eq!(observed_failing_broker.attempts(), 1);
+ assert!(observed_failing_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn spawned_summarization_publishes_record_summarized_event() {
+ let event_broker = RecordingEventBroker::default();
+ let summarizer = StubCallSummarizer::new(
+ Some(SUMMARIZED_EVENT_SUMMARY),
+ GeneratedNameResult::Generated,
+ );
+ let service =
+ build_summarization_service(MockCallRepository::new(), summarizer, event_broker.clone());
+ configure_repository_clone(
+ &service.repo,
+ mock_summarization_repo(None, Some(true), NamePersistence::Persisted(true)),
+ );
+
+ service.spawn_summarize_call(SUMMARIZED_EVENT_CALL_ID);
+ wait_for_spawned_work(|| !event_broker.events().is_empty()).await;
+ assert_summarized_event(&event_broker, true);
+
+ let failing_broker = RecordingEventBroker::failing();
+ let summarizer = StubCallSummarizer::new(
+ Some(SUMMARIZED_EVENT_SUMMARY),
+ GeneratedNameResult::Generated,
+ );
+ let service = build_summarization_service(
+ MockCallRepository::new(),
+ summarizer,
+ failing_broker.clone(),
+ );
+ configure_repository_clone(
+ &service.repo,
+ mock_summarization_repo(None, Some(true), NamePersistence::Persisted(true)),
+ );
+
+ service.spawn_summarize_call(SUMMARIZED_EVENT_CALL_ID);
+ wait_for_spawned_work(|| failing_broker.attempts() == 1).await;
+ assert!(failing_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn summarized_event_reports_ai_name_persistence() {
+ let cases = [
+ (
+ None,
+ GeneratedNameResult::Generated,
+ NamePersistence::Persisted(true),
+ true,
+ 1,
+ ),
+ (
+ Some("User-provided name"),
+ GeneratedNameResult::Generated,
+ NamePersistence::NotAttempted,
+ false,
+ 0,
+ ),
+ (
+ None,
+ GeneratedNameResult::NoName,
+ NamePersistence::NotAttempted,
+ false,
+ 1,
+ ),
+ (
+ None,
+ GeneratedNameResult::Failed,
+ NamePersistence::NotAttempted,
+ false,
+ 1,
+ ),
+ (
+ None,
+ GeneratedNameResult::Generated,
+ NamePersistence::Persisted(false),
+ false,
+ 1,
+ ),
+ (
+ None,
+ GeneratedNameResult::Generated,
+ NamePersistence::Failed,
+ false,
+ 1,
+ ),
+ ];
+
+ for (custom_name, generated_name, name_persistence, expected_ai_name, expected_name_calls) in
+ cases
+ {
+ let (broker, summarizer) = run_direct_summarization(
+ custom_name,
+ Some(SUMMARIZED_EVENT_SUMMARY),
+ Some(true),
+ generated_name,
+ name_persistence,
+ RecordingEventBroker::default(),
+ )
+ .await;
+
+ assert_summarized_event(&broker, expected_ai_name);
+ assert_eq!(summarizer.name_calls(), expected_name_calls);
}
}
@@ -504,9 +2296,9 @@ async fn enroll_stable_speaker_voices_links_all_voices_for_consistent_diarized_s
.await?;
}
- let call_record_id = call_repo.archive_call(&CALL1).await?;
+ let archived = call_repo.archive_call(&CALL1).await?;
- super::enroll_stable_speaker_voices_for_call_record(&call_repo, &voice_repo, call_record_id)
+ super::enroll_stable_speaker_voices_for_call_record(&call_repo, &voice_repo, archived.call_id)
.await;
let mut user_a_voices = voice_repo.get_user_voices(&MACRO_USER_A).await?;
diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rs
index 59631743cc..b658d9cd77 100644
--- a/crates/call/src/outbound/pg_call_repo.rs
+++ b/crates/call/src/outbound/pg_call_repo.rs
@@ -8,7 +8,7 @@ mod test;
use std::collections::{HashMap, HashSet};
use channels::outbound::channel_name::batch_resolve_channel_names;
-use chrono::Utc;
+use chrono::{SubsecRound, Utc};
use entity_access::domain::models::AccessLevel;
use filter_ast::Expr;
use item_filters::{
@@ -22,7 +22,7 @@ use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::models::{
- AddParticipantError, Call, CallParticipant, CallRecord, CallRecordParticipant,
+ AddParticipantError, ArchivedCall, Call, CallParticipant, CallRecord, CallRecordParticipant,
CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,
DeletedCallRecordStorageKeys, EditCallRecordRequest, EnrichedCallTranscript,
TranscriptSegmentRequest, WithCallId,
@@ -697,7 +697,7 @@ impl CallRepository for PgCallRepo {
}
#[tracing::instrument(err, skip(self))]
- async fn archive_call(&self, call_id: &Uuid) -> Result<Uuid, Self::Err> {
+ async fn archive_call(&self, call_id: &Uuid) -> Result<ArchivedCall, Self::Err> {
let mut tx = self.pool.begin().await?;
// Fetch and lock the active call so concurrent archive_call callers serialize.
@@ -742,11 +742,12 @@ impl CallRepository for PgCallRepo {
}
}
- let now = Utc::now();
- let duration_ms = now
+ let ended_at = Utc::now().trunc_subsecs(6);
+ let duration_ms = ended_at
.signed_duration_since(call.created_at)
.num_milliseconds()
.max(0);
+ let has_recording = call.egress_id.is_some();
// Insert into call_records (including egress_id and any early recording keys).
// The record keeps the same id as the original call.
sqlx::query!(
@@ -759,7 +760,7 @@ impl CallRepository for PgCallRepo {
call.room_name,
call.created_by,
call.created_at,
- now,
+ ended_at,
duration_ms,
call.egress_id,
call.recording_key,
@@ -771,8 +772,9 @@ impl CallRepository for PgCallRepo {
.execute(tx.as_mut())
.await?;
- // Copy all participants (including soft-deleted) to call_record_participants.
- sqlx::query!(
+ // Copy all lifetime-distinct participants (including soft-deleted) to
+ // call_record_participants. Each inserted row represents one participant.
+ let participant_count = sqlx::query!(
r#"
INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)
SELECT $1, user_id, joined_at, left_at
@@ -783,7 +785,8 @@ impl CallRepository for PgCallRepo {
call_id,
)
.execute(tx.as_mut())
- .await?;
+ .await?
+ .rows_affected() as usize;
// Copy transcripts to call_record_transcripts, rolling up consecutive
// segments that share both speaker_id and diarized_speaker_id when the
@@ -875,8 +878,19 @@ impl CallRepository for PgCallRepo {
.execute(tx.as_mut())
.await?;
+ let archived = ArchivedCall {
+ call_id: call.id,
+ channel_id: call.channel_id,
+ created_by: call.created_by,
+ started_at: call.created_at,
+ ended_at,
+ duration_ms,
+ has_recording,
+ participant_count,
+ };
+
tx.commit().await?;
- Ok(*call_id)
+ Ok(archived)
}
#[tracing::instrument(err, skip(self))]
@@ -901,15 +915,16 @@ impl CallRepository for PgCallRepo {
async fn get_call_record_by_egress_id(
&self,
egress_id: &str,
- ) -> Result<Option<Uuid>, Self::Err> {
- sqlx::query_scalar!(
+ ) -> Result<Option<(Uuid, Uuid)>, Self::Err> {
+ let record = sqlx::query!(
r#"
- SELECT id FROM call_records WHERE egress_id = $1
+ SELECT id, channel_id FROM call_records WHERE egress_id = $1
"#,
egress_id,
)
.fetch_optional(&self.pool)
- .await
+ .await?;
+ Ok(record.map(|record| (record.id, record.channel_id)))
}
#[tracing::instrument(err, skip(self))]
@@ -1912,9 +1927,9 @@ impl CallRepository for PgCallRepo {
}
#[tracing::instrument(skip(self, summary), err)]
- async fn insert_call_summary(&self, call_id: &Uuid, summary: &str) -> Result<(), Self::Err> {
+ async fn insert_call_summary(&self, call_id: &Uuid, summary: &str) -> Result<bool, Self::Err> {
// Tolerate missing rows: summarization can race with record deletion.
- sqlx::query!(
+ let result = sqlx::query!(
r#"
UPDATE call_records SET summary = $2 WHERE id = $1
"#,
@@ -1923,14 +1938,14 @@ impl CallRepository for PgCallRepo {
)
.execute(&self.pool)
.await?;
- Ok(())
+ Ok(result.rows_affected() > 0)
}
#[tracing::instrument(skip(self, name), err)]
- async fn set_custom_name_if_null(&self, call_id: &Uuid, name: &str) -> Result<(), Self::Err> {
+ async fn set_custom_name_if_null(&self, call_id: &Uuid, name: &str) -> Result<bool, Self::Err> {
let mut tx = self.pool.begin().await?;
- edit::set_custom_name_if_null(&mut tx, call_id, name).await?;
+ let persisted = edit::set_custom_name_if_null(&mut tx, call_id, name).await?;
tx.commit().await?;
- Ok(())
+ Ok(persisted)
}
}
diff --git a/crates/call/src/outbound/pg_call_repo/edit.rs b/crates/call/src/outbound/pg_call_repo/edit.rs
index b51d87568c..b553570fc5 100644
--- a/crates/call/src/outbound/pg_call_repo/edit.rs
+++ b/crates/call/src/outbound/pg_call_repo/edit.rs
@@ -168,20 +168,20 @@ pub(super) async fn set_custom_name(
/// Set `call_records.custom_name` only when the existing value is `NULL`.
///
/// Used by the AI auto-naming flow so a user-set name is never overwritten.
-/// No-op if no `call_records` row matches.
+/// Returns whether the conditional update persisted the name.
pub(super) async fn set_custom_name_if_null(
transaction: &mut Transaction<'_, Postgres>,
call_id: &Uuid,
custom_name: &str,
-) -> Result<(), sqlx::Error> {
- sqlx::query!(
+) -> Result<bool, sqlx::Error> {
+ let result = sqlx::query!(
r#"UPDATE call_records SET custom_name = $2 WHERE id = $1 AND custom_name IS NULL"#,
call_id,
custom_name,
)
.execute(transaction.as_mut())
.await?;
- Ok(())
+ Ok(result.rows_affected() > 0)
}
/// Apply per-(call_record_id, diarized_speaker_id) `custom_speaker` overrides.
diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rs
index e971cf0735..ecc26465a8 100644
--- a/crates/call/src/outbound/pg_call_repo/test.rs
+++ b/crates/call/src/outbound/pg_call_repo/test.rs
@@ -511,8 +511,9 @@ async fn archive_call_creates_record_and_deletes_ephemeral(
pool: Pool<Postgres>,
) -> anyhow::Result<()> {
let repo = repo(pool.clone());
+ repo.set_egress_id(&CALL1, "egress-archive-test").await?;
- let record_id = repo.archive_call(&CALL1).await?;
+ let archived = repo.archive_call(&CALL1).await?;
// Ephemeral call should be gone.
assert!(repo.get_call_by_channel_id(&CH1).await?.is_none());
@@ -525,13 +526,22 @@ async fn archive_call_creates_record_and_deletes_ephemeral(
FROM call_records
WHERE id = $1
"#,
- record_id,
+ archived.call_id,
)
.fetch_one(&pool)
.await?;
- assert_eq!(record.channel_id, CH1);
- assert_eq!(record.created_by, USER_A.as_ref());
+ assert_eq!(archived.call_id, CALL1);
+ assert_eq!(archived.channel_id, CH1);
+ assert_eq!(archived.created_by, USER_A.as_ref());
+ assert_eq!(archived.started_at, record.started_at);
+ assert_eq!(archived.ended_at, record.ended_at);
+ assert_eq!(archived.duration_ms, record.duration_ms);
+ assert!(archived.has_recording);
+ assert_eq!(archived.participant_count, 2);
+
+ assert_eq!(record.channel_id, archived.channel_id);
+ assert_eq!(record.created_by, archived.created_by);
assert!(record.duration_ms >= 0);
assert!(record.ended_at >= record.started_at);
@@ -543,12 +553,12 @@ async fn archive_call_creates_record_and_deletes_ephemeral(
WHERE call_record_id = $1
ORDER BY joined_at ASC
"#,
- record_id,
+ archived.call_id,
)
.fetch_all(&pool)
.await?;
- assert_eq!(participants.len(), 2);
+ assert_eq!(participants.len(), archived.participant_count);
assert!(participants.contains(&USER_A.to_string()));
assert!(participants.contains(&USER_B.to_string()));
Ok(())
@@ -575,7 +585,9 @@ async fn archive_call_preserves_soft_deleted_participants(
assert_eq!(repo.get_participant_count(&CALL1).await?, 0);
// Archive the call.
- let record_id = repo.archive_call(&CALL1).await?;
+ let archived = repo.archive_call(&CALL1).await?;
+ assert_eq!(archived.participant_count, 2);
+ assert!(!archived.has_recording);
// call_record_participants should have both participants with left_at set.
let rows = sqlx::query!(
@@ -585,12 +597,12 @@ async fn archive_call_preserves_soft_deleted_participants(
WHERE call_record_id = $1
ORDER BY joined_at ASC
"#,
- record_id,
+ archived.call_id,
)
.fetch_all(&pool)
.await?;
- assert_eq!(rows.len(), 2);
+ assert_eq!(rows.len(), archived.participant_count);
let user_ids: Vec<&str> = rows.iter().map(|r| r.user_id.as_str()).collect();
assert!(user_ids.contains(&USER_A.as_ref()));
assert!(user_ids.contains(&USER_B.as_ref()));
@@ -600,6 +612,21 @@ async fn archive_call_preserves_soft_deleted_participants(
Ok(())
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn archive_call_returns_no_result_when_call_is_missing(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool.clone());
+
+ assert!(repo.archive_call(&CALL2).await.is_err());
+ assert!(repo.get_call_record_by_call_id(&CALL2).await?.is_none());
+
+ Ok(())
+}
+
/// Test helper: give `user_id` a brand new team owned by that user. Inserts
/// the parent `macro_user` and `User` rows that the `team_user` FK requires.
async fn give_user_a_team(
@@ -759,15 +786,15 @@ async fn archive_call_preserves_id_and_share_permission(
.fetch_one(&pool)
.await?;
- let record_id = repo.archive_call(&CALL1).await?;
+ let archived = repo.archive_call(&CALL1).await?;
// The call_record id should be the same as the original call id.
- assert_eq!(record_id, CALL1);
+ assert_eq!(archived.call_id, CALL1);
// The share_permission_id should carry over to the call_record.
let record_share_permission_id = sqlx::query_scalar!(
r#"SELECT share_permission_id FROM call_records WHERE id = $1"#,
- record_id,
+ archived.call_id,
)
.fetch_one(&pool)
.await?;
@@ -777,6 +804,40 @@ async fn archive_call_preserves_id_and_share_permission(
Ok(())
}
+// -- get_call_record_by_egress_id --------------------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn get_call_record_by_egress_id_returns_call_and_channel_context(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+
+ let context = repo.get_call_record_by_egress_id("egress-arch-1").await?;
+
+ assert_eq!(context, Some((CALL_ARCHIVED, CH1)));
+ Ok(())
+}
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn get_call_record_by_egress_id_returns_none_for_unknown_id(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = repo(pool);
+
+ let context = repo
+ .get_call_record_by_egress_id("unknown-egress-id")
+ .await?;
+
+ assert_eq!(context, None);
+ Ok(())
+}
+
// -- set_active_call_recording_key --------------------------------------------
#[sqlx::test(
@@ -813,15 +874,15 @@ async fn set_active_call_recording_key_updates_matching_call(
assert_eq!(call.egress_id.as_deref(), Some("egress-123"));
// Now archive and verify recording_key and preview key carry forward.
- let record_id = repo.archive_call(&CALL1).await?;
- let archived = sqlx::query!(
+ let archived = repo.archive_call(&CALL1).await?;
+ let recording = sqlx::query!(
r#"SELECT recording_key, preview_url FROM call_records WHERE id = $1"#,
- record_id,
+ archived.call_id,
)
.fetch_one(&pool)
.await?;
- assert_eq!(archived.recording_key.as_deref(), Some(recording_key));
- assert_eq!(archived.preview_url.as_deref(), Some(preview_key));
+ assert_eq!(recording.recording_key.as_deref(), Some(recording_key));
+ assert_eq!(recording.preview_url.as_deref(), Some(preview_key));
Ok(())
}
@@ -1034,7 +1095,7 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result
repo.create_transcript_segment(&CALL1, &seg, None).await?;
// Archive the call.
- let record_id = repo.archive_call(&CALL1).await?;
+ let archived = repo.archive_call(&CALL1).await?;
// Transcripts should be in call_record_transcripts.
let transcripts = sqlx::query!(
@@ -1043,7 +1104,7 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result
FROM call_record_transcripts
WHERE call_record_id = $1
"#,
- record_id,
+ archived.call_id,
)
.fetch_all(&pool)
.await?;
@@ -1150,7 +1211,7 @@ async fn archive_call_rolls_up_consecutive_same_speaker_transcripts(
.await?;
}
- let record_id = repo.archive_call(&CALL1).await?;
+ let archived = repo.archive_call(&CALL1).await?;
let rows = sqlx::query!(
r#"
@@ -1159,7 +1220,7 @@ async fn archive_call_rolls_up_consecutive_same_speaker_transcripts(
WHERE call_record_id = $1
ORDER BY sequence_num ASC
"#,
- record_id,
+ archived.call_id,
)
.fetch_all(&pool)
.await?;
@@ -1269,10 +1330,10 @@ async fn get_stable_speaker_voices_for_call_record_returns_all_voices_for_consis
.await?;
}
- let record_id = repo.archive_call(&CALL1).await?;
+ let archived = repo.archive_call(&CALL1).await?;
let mut stable = repo
- .get_stable_speaker_voices_for_call_record(&record_id)
+ .get_stable_speaker_voices_for_call_record(&archived.call_id)
.await?;
stable.sort();
@@ -2713,9 +2774,11 @@ async fn set_custom_name_if_null_writes_when_column_is_null(
) -> anyhow::Result<()> {
let repo = repo(pool.clone());
- repo.set_custom_name_if_null(&CALL_ARCHIVED, "AI Generated Name")
+ let persisted = repo
+ .set_custom_name_if_null(&CALL_ARCHIVED, "AI Generated Name")
.await?;
+ assert!(persisted);
let stored = sqlx::query_scalar!(
r#"SELECT custom_name FROM call_records WHERE id = $1"#,
CALL_ARCHIVED,
@@ -2743,9 +2806,11 @@ async fn set_custom_name_if_null_does_not_overwrite_existing_name(
.execute(&pool)
.await?;
- repo.set_custom_name_if_null(&CALL_ARCHIVED, "AI Generated")
+ let persisted = repo
+ .set_custom_name_if_null(&CALL_ARCHIVED, "AI Generated")
.await?;
+ assert!(!persisted);
let stored = sqlx::query_scalar!(
r#"SELECT custom_name FROM call_records WHERE id = $1"#,
CALL_ARCHIVED,
@@ -2763,9 +2828,11 @@ async fn set_custom_name_if_null_does_not_overwrite_existing_name(
async fn set_custom_name_if_null_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let repo = repo(pool.clone());
- // Idempotent on missing rows — must not error.
- repo.set_custom_name_if_null(&Uuid::now_v7(), "Whatever")
+ let persisted = repo
+ .set_custom_name_if_null(&Uuid::now_v7(), "Whatever")
.await?;
+
+ assert!(!persisted);
Ok(())
}
@@ -2779,8 +2846,9 @@ async fn insert_call_summary_sets_summary_text(pool: Pool<Postgres>) -> anyhow::
let repo = repo(pool.clone());
let summary = "A short synopsis of the call.";
- repo.insert_call_summary(&CALL_ARCHIVED, summary).await?;
+ let persisted = repo.insert_call_summary(&CALL_ARCHIVED, summary).await?;
+ assert!(persisted);
let stored = sqlx::query_scalar!(
r#"SELECT summary FROM call_records WHERE id = $1"#,
CALL_ARCHIVED,
@@ -2799,10 +2867,11 @@ async fn insert_call_summary_sets_summary_text(pool: Pool<Postgres>) -> anyhow::
async fn insert_call_summary_noop_for_unknown_id(pool: Pool<Postgres>) -> anyhow::Result<()> {
let repo = repo(pool.clone());
- // Unknown id should be an idempotent no-op (not an error).
- repo.insert_call_summary(&Uuid::now_v7(), "irrelevant")
+ let persisted = repo
+ .insert_call_summary(&Uuid::now_v7(), "irrelevant")
.await?;
+ assert!(!persisted);
// The archived fixture row must remain untouched.
let stored = sqlx::query_scalar!(
r#"SELECT summary FROM call_records WHERE id = $1"#,
diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rs
index 410d837a8c..c05b08b2dd 100644
--- a/crates/macro_event_topics/src/lib.rs
+++ b/crates/macro_event_topics/src/lib.rs
@@ -49,6 +49,8 @@ topics! {
MacroExampleTopic => "macro.example",
/// Bot lifecycle events (created / updated / deleted).
MacroBotsTopic => "macro.bots",
+ /// Call lifecycle and recording events.
+ MacroCallsTopic => "macro.calls",
/// Document lifecycle events (created / updated / deleted / copied).
MacroDocumentsTopic => "macro.documents",
/// User-scoped full Soup items produced from entity updates.
diff --git a/crates/macro_event_topics/src/test.rs b/crates/macro_event_topics/src/test.rs
index f7de8c8f7d..9960770730 100644
--- a/crates/macro_event_topics/src/test.rs
+++ b/crates/macro_event_topics/src/test.rs
@@ -24,6 +24,7 @@ fn all_topic_names_includes_declared_topics() {
assert!(all_topic_names().contains(&MacroTeamsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroChannelsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroBotsTopic::TOPIC_STR));
+ assert!(all_topic_names().contains(&MacroCallsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroWebhooksTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroMentionsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroChatsTopic::TOPIC_STR));
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 093938f4f2..c124d31529 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -356,6 +356,7 @@ pub(crate) type DssCallService = CallServiceImpl<
crate::service::call_search_indexer::SqsCallSearchIndexer,
DssVoipPushSender,
call::outbound::pg_voice_repo::PgVoiceRepo,
+ DssEventBroker,
>;
/// Type alias for the call router state.
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 6097897450..bb5e1031fc 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -673,7 +673,8 @@ async fn main() -> anyhow::Result<()> {
let call_service = Arc::new(
call_service_builder
.with_search_indexer(call_search_indexer)
- .with_voice_repo(PgVoiceRepo::new(db.clone())),
+ .with_voice_repo(PgVoiceRepo::new(db.clone()))
+ .with_event_broker(macro_event_broker.clone()),
);
let call_state = CallRouterState::new(