BlueGit

ict rusty-teams

fix(calls): outgoing calls ack the server at once and stop ringing when the call is gone

- Trouter callbacks are answered when they arrive, the acceptance acknowledgement included. It waited for the call loop before, behind updateEndpointState (2.8 s on a cold start); the call controller ended the call with 408/10056 and never dialled the callee.
- conversationEnd before the callee joined, or addParticipantFailure for every callee, ends an outgoing call instead of ringing on until the timeout.
- call/rejection of an own offer clears the pending escalation or same-peer change.
- conversationEnd, call/rejection and addParticipantFailure write their codes (no names) to the call timeline.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-16 · 6 weeks ago

Hash
7a33c46aa5645fbbd3853cc84fc52b0790d3e886
Parent
b5537480
7 files changed +272 −46
crates/calling/src/call.rs +54 −27
@@ -41,7 +41,8 @@ use crate::mic_processing::MicSettings;
41 41 use crate::mute::{MuteCommand, MuteEffect};
42 42 use crate::push::CallNotification;
43 43 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
44 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};
44 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
45 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
45 46 use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
46 47 use crate::meeting_options::{self, OptionWrite};
47 48 use crate::recording::{Consent, RecordingPlan, RecordingStatus};
@@ -64,7 +65,7 @@ use crate::video_send::{LocalVideo, SendSource, VideoMode};
64 65 use crate::screen::{ShareKind, ShareSource, list_share_sources};
65 66 use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
66 67 use crate::trouter_events::{
67 CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,
68 CallEnd, CallEvent, CallbackLinks, ProgressStatus, classify, decode_body,
68 69 };
69 70 use crate::whiteboard;
70 71
@@ -210,6 +211,13 @@ impl CallSpec {
210 211 fn is_people(&self) -> bool {
211 212 matches!(self, CallSpec::People { .. })
212 213 }
214
215 fn callee_count(&self) -> usize {
216 match self {
217 CallSpec::People { callees, .. } => callees.len(),
218 CallSpec::Echo | CallSpec::Meeting(_) => 0,
219 }
220 }
213 221 }
214 222
215 223 pub(crate) struct IncomingCall {
@@ -594,7 +602,7 @@ async fn drive(
594 602 None => {
595 603 let links = inner.callback_links();
596 604 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
597 let callbacks = inner.register_route(links.call_id());
605 let callbacks = inner.register_route(&links);
598 606 (links, participant, callbacks, None)
599 607 }
600 608 };
@@ -657,7 +665,7 @@ async fn drive(
657 665 let mut outgoing_deadline: Option<Instant> = None;
658 666 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
659 667 let is_echo = matches!(spec, Some(CallSpec::Echo));
660 let mut callee_gate = CalleeGate::new(spec.as_ref().is_some_and(CallSpec::is_people));
668 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
661 669 let meeting_target = match &spec {
662 670 Some(CallSpec::Meeting(target)) => Some(target.clone()),
663 671 _ => None,
@@ -808,7 +816,6 @@ async fn drive(
808 816 timeline.record("updateEndpointState failed", error.to_string());
809 817 }
810 818
811 let replier = inner.replier.clone();
812 819 let mut stats_tick = interval(STATS_PERIOD);
813 820 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
814 821 let mut leave_at = hard_deadline;
@@ -882,10 +889,8 @@ async fn drive(
882 889 }
883 890 tokio::select! {
884 891 Some(callback) = callbacks.recv() => {
885 let request_id = callback.request_id;
886 892 match handle_callback(&callback, timeline) {
887 893 Ok(CallEvent::Acceptance(acceptance)) => {
888 replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string());
889 894 if !acceptance.from_mixer && callee_gate.callee_joined() {
890 895 advance(state, CallSignal::MediaConnected, control);
891 896 }
@@ -951,7 +956,6 @@ async fn drive(
951 956 }
952 957 }
953 958 Ok(CallEvent::MediaAnswer(answer)) => {
954 replier.reply(request_id, 200, "");
955 959 let action = negotiator.on_media_answer();
956 960 if action == MediaAction::ApplyOnSamePeer
957 961 && let Some(pending) = same_peer.take()
@@ -1005,7 +1009,6 @@ async fn drive(
1005 1009 }
1006 1010 }
1007 1011 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1008 replier.reply(request_id, 200, "");
1009 1012 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1010 1013 let result = match action {
1011 1014 MediaAction::AnswerOnNewPeer => {
@@ -1043,7 +1046,6 @@ async fn drive(
1043 1046 }
1044 1047 }
1045 1048 Ok(CallEvent::RosterUpdate(body)) => {
1046 replier.reply(request_id, 200, "");
1047 1049 if roster.apply(&body) {
1048 1050 let entries = roster.entries();
1049 1051 timeline.record("roster", format!("{} participant(s)", entries.len()));
@@ -1091,9 +1093,16 @@ async fn drive(
1091 1093 }
1092 1094 }
1093 1095 }
1094 Ok(CallEvent::AddParticipantFailure(_)) => {
1095 replier.reply(request_id, 200, "");
1096 Ok(CallEvent::AddParticipantFailure(body)) => {
1097 let bot_add = bot_pending;
1096 1098 bot_pending = false;
1099 if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) {
1100 let end = embedded_end(&body);
1101 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1102 report.end = end;
1103 advance(state, CallSignal::RemoteEnd(kind), control);
1104 break;
1105 }
1097 1106 if recording_flow.wanted() && roster.caption_bot().is_none() {
1098 1107 timeline.record("recorder bot failed", "addParticipantFailure");
1099 1108 recording_flow.failed();
@@ -1109,7 +1118,6 @@ async fn drive(
1109 1118 }
1110 1119 }
1111 1120 Ok(CallEvent::ConversationUpdate(body)) => {
1112 replier.reply(request_id, 200, "");
1113 1121 if let Some(thread) = chat_thread_id(&body)
1114 1122 && meeting_chat.as_ref() != Some(&thread)
1115 1123 {
@@ -1149,7 +1157,6 @@ async fn drive(
1149 1157 }
1150 1158 }
1151 1159 Ok(CallEvent::LocalParticipantUpdate(body)) => {
1152 replier.reply(request_id, 200, "");
1153 1160 let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1154 1161 if let Some(moved) = moved {
1155 1162 timeline.record("breakout", format!("moved to {}", moved.room_name));
@@ -1157,7 +1164,6 @@ async fn drive(
1157 1164 }
1158 1165 }
1159 1166 Ok(CallEvent::Replacement(body)) => {
1160 replier.reply(request_id, 200, "");
1161 1167 let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1162 1168 if let Some(moved) = invited {
1163 1169 timeline.record("breakout", format!("invited to {}", moved.room_name));
@@ -1165,17 +1171,14 @@ async fn drive(
1165 1171 }
1166 1172 }
1167 1173 Ok(CallEvent::ContentShareUpdate(body)) => {
1168 replier.reply(request_id, 200, "");
1169 1174 if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1170 1175 control.send(CallUpdate::Whiteboard(Some(share)));
1171 1176 }
1172 1177 }
1173 1178 Ok(CallEvent::ContentShareEnd(_)) => {
1174 replier.reply(request_id, 200, "");
1175 1179 control.send(CallUpdate::Whiteboard(None));
1176 1180 }
1177 1181 Ok(CallEvent::Transfer(event)) => {
1178 replier.reply(request_id, 200, "");
1179 1182 match event {
1180 1183 TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"),
1181 1184 completed if completed.succeeded() => {
@@ -1193,19 +1196,16 @@ async fn drive(
1193 1196 }
1194 1197 }
1195 1198 Ok(CallEvent::Reactions(events)) => {
1196 replier.reply(request_id, 200, "");
1197 1199 for event in events {
1198 1200 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
1199 1201 }
1200 1202 }
1201 1203 Ok(CallEvent::Progress(status)) => {
1202 replier.reply(request_id, 200, "");
1203 1204 if status == ProgressStatus::Ringing {
1204 1205 control.send(CallUpdate::Progress(Progress::Ringing));
1205 1206 }
1206 1207 }
1207 1208 Ok(CallEvent::ControlVideoStreaming(body)) => {
1208 replier.reply(request_id, 200, "");
1209 1209 let Some(request) = parse_request(&body) else { continue };
1210 1210 let Some(limits) = send_requests.admit(&request) else { continue };
1211 1211 let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
@@ -1217,23 +1217,44 @@ async fn drive(
1217 1217 }
1218 1218 }
1219 1219 Ok(CallEvent::Speakers(sources)) => {
1220 replier.reply(request_id, 200, "");
1221 1220 let speakers = roster.mris_for_sources(&sources);
1222 1221 if video.note_speakers(&speakers) {
1223 1222 send_receive_change(control, video.reselect(&roster));
1224 1223 }
1225 1224 control.send(CallUpdate::Speakers(speakers));
1226 1225 }
1226 Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => {
1227 live.skip_leave = true;
1228 let end = embedded_end(&body);
1229 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1230 report.end = end;
1231 advance(state, CallSignal::RemoteEnd(kind), control);
1232 break;
1233 }
1234 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1235 RejectedOffer::SamePeer => {
1236 same_peer_deadline = None;
1237 if let Some(pending) = same_peer.take() {
1238 rollback_offer(&current.peer).await;
1239 undo_change(pending.change, &mut local_video, control);
1240 }
1241 }
1242 RejectedOffer::NewPeer => {
1243 if let Some(pending) = next.take() {
1244 pending.session.peer.close();
1245 }
1246 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1247 }
1248 RejectedOffer::None => {}
1249 },
1227 1250 Ok(CallEvent::End(end)) => {
1228 replier.reply(request_id, 200, "");
1229 1251 let kind = end.kind();
1230 1252 report.end = Some(end);
1231 1253 advance(state, CallSignal::RemoteEnd(kind), control);
1232 1254 break;
1233 1255 }
1234 Ok(_) => replier.reply(request_id, 200, ""),
1256 Ok(_) => {}
1235 1257 Err(error) => {
1236 replier.reply(request_id, 200, "");
1237 1258 timeline.record("callback not understood", error.to_string());
1238 1259 }
1239 1260 }
@@ -2609,9 +2630,7 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
2609 2630 {
2610 2631 let waited = timeout(END_CALLBACK_WAIT, async {
2611 2632 while let Some(callback) = callbacks.recv().await {
2612 let request_id = callback.request_id;
2613 2633 let event = handle_callback(&callback, timeline);
2614 inner.replier.reply(request_id, 200, "");
2615 2634 if let Ok(CallEvent::End(end)) = event {
2616 2635 return Some(end);
2617 2636 }
@@ -2639,6 +2658,13 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
2639 2658 timeline.record("closed", "peer closed, call route removed");
2640 2659 }
2641 2660
2661 fn setup_end_kind(end: &CallEnd) -> EndKind {
2662 match end.kind() {
2663 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
2664 kind => kind,
2665 }
2666 }
2667
2642 2668 fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
2643 2669 let body = decode_body(callback)?;
2644 2670 let (_, event) = classify(&callback.path, body)?;
@@ -2646,6 +2672,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2646 2672 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2647 2673 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2648 2674 CallEvent::Progress(status) => format!("{status:?}"),
2675 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) => outcome_summary(body),
2649 2676 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2650 2677 _ => String::new(),
2651 2678 };
@@ -41,7 +41,8 @@ use crate::mic_processing::MicSettings;
41use crate::mute::{MuteCommand, MuteEffect};
41use crate::mute::{MuteCommand, MuteEffect};
42use crate::push::CallNotification;
42use crate::push::CallNotification;
43use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
43use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
44use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath};
44use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
45use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
45use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
46use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
46use crate::meeting_options::{self, OptionWrite};
47use crate::meeting_options::{self, OptionWrite};
47use crate::recording::{Consent, RecordingPlan, RecordingStatus};
48use crate::recording::{Consent, RecordingPlan, RecordingStatus};
@@ -64,7 +65,7 @@ use crate::video_send::{LocalVideo, SendSource, VideoMode};
64use crate::screen::{ShareKind, ShareSource, list_share_sources};
65use crate::screen::{ShareKind, ShareSource, list_share_sources};
65use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
66use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
66use crate::trouter_events::{
67use crate::trouter_events::{
67 CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body,
68 CallEnd, CallEvent, CallbackLinks, ProgressStatus, classify, decode_body,
68};
69};
69use crate::whiteboard;
70use crate::whiteboard;
70
71
@@ -210,6 +211,13 @@ impl CallSpec {
210 fn is_people(&self) -> bool {
211 fn is_people(&self) -> bool {
211 matches!(self, CallSpec::People { .. })
212 matches!(self, CallSpec::People { .. })
212 }
213 }
214
215 fn callee_count(&self) -> usize {
216 match self {
217 CallSpec::People { callees, .. } => callees.len(),
218 CallSpec::Echo | CallSpec::Meeting(_) => 0,
219 }
220 }
213}
221}
214
222
215pub(crate) struct IncomingCall {
223pub(crate) struct IncomingCall {
@@ -594,7 +602,7 @@ async fn drive(
594 None => {
602 None => {
595 let links = inner.callback_links();
603 let links = inner.callback_links();
596 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
604 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
597 let callbacks = inner.register_route(links.call_id());
605 let callbacks = inner.register_route(&links);
598 (links, participant, callbacks, None)
606 (links, participant, callbacks, None)
599 }
607 }
600 };
608 };
@@ -657,7 +665,7 @@ async fn drive(
657 let mut outgoing_deadline: Option<Instant> = None;
665 let mut outgoing_deadline: Option<Instant> = None;
658 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
666 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
659 let is_echo = matches!(spec, Some(CallSpec::Echo));
667 let is_echo = matches!(spec, Some(CallSpec::Echo));
660 let mut callee_gate = CalleeGate::new(spec.as_ref().is_some_and(CallSpec::is_people));
668 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
661 let meeting_target = match &spec {
669 let meeting_target = match &spec {
662 Some(CallSpec::Meeting(target)) => Some(target.clone()),
670 Some(CallSpec::Meeting(target)) => Some(target.clone()),
663 _ => None,
671 _ => None,
@@ -808,7 +816,6 @@ async fn drive(
808 timeline.record("updateEndpointState failed", error.to_string());
816 timeline.record("updateEndpointState failed", error.to_string());
809 }
817 }
810
818
811 let replier = inner.replier.clone();
812 let mut stats_tick = interval(STATS_PERIOD);
819 let mut stats_tick = interval(STATS_PERIOD);
813 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
820 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
814 let mut leave_at = hard_deadline;
821 let mut leave_at = hard_deadline;
@@ -882,10 +889,8 @@ async fn drive(
882 }
889 }
883 tokio::select! {
890 tokio::select! {
884 Some(callback) = callbacks.recv() => {
891 Some(callback) = callbacks.recv() => {
885 let request_id = callback.request_id;
886 match handle_callback(&callback, timeline) {
892 match handle_callback(&callback, timeline) {
887 Ok(CallEvent::Acceptance(acceptance)) => {
893 Ok(CallEvent::Acceptance(acceptance)) => {
888 replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string());
889 if !acceptance.from_mixer && callee_gate.callee_joined() {
894 if !acceptance.from_mixer && callee_gate.callee_joined() {
890 advance(state, CallSignal::MediaConnected, control);
895 advance(state, CallSignal::MediaConnected, control);
891 }
896 }
@@ -951,7 +956,6 @@ async fn drive(
951 }
956 }
952 }
957 }
953 Ok(CallEvent::MediaAnswer(answer)) => {
958 Ok(CallEvent::MediaAnswer(answer)) => {
954 replier.reply(request_id, 200, "");
955 let action = negotiator.on_media_answer();
959 let action = negotiator.on_media_answer();
956 if action == MediaAction::ApplyOnSamePeer
960 if action == MediaAction::ApplyOnSamePeer
957 && let Some(pending) = same_peer.take()
961 && let Some(pending) = same_peer.take()
@@ -1005,7 +1009,6 @@ async fn drive(
1005 }
1009 }
1006 }
1010 }
1007 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1011 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1008 replier.reply(request_id, 200, "");
1009 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1012 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1010 let result = match action {
1013 let result = match action {
1011 MediaAction::AnswerOnNewPeer => {
1014 MediaAction::AnswerOnNewPeer => {
@@ -1043,7 +1046,6 @@ async fn drive(
1043 }
1046 }
1044 }
1047 }
1045 Ok(CallEvent::RosterUpdate(body)) => {
1048 Ok(CallEvent::RosterUpdate(body)) => {
1046 replier.reply(request_id, 200, "");
1047 if roster.apply(&body) {
1049 if roster.apply(&body) {
1048 let entries = roster.entries();
1050 let entries = roster.entries();
1049 timeline.record("roster", format!("{} participant(s)", entries.len()));
1051 timeline.record("roster", format!("{} participant(s)", entries.len()));
@@ -1091,9 +1093,16 @@ async fn drive(
1091 }
1093 }
1092 }
1094 }
1093 }
1095 }
1094 Ok(CallEvent::AddParticipantFailure(_)) => {
1096 Ok(CallEvent::AddParticipantFailure(body)) => {
1095 replier.reply(request_id, 200, "");
1097 let bot_add = bot_pending;
1096 bot_pending = false;
1098 bot_pending = false;
1099 if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) {
1100 let end = embedded_end(&body);
1101 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1102 report.end = end;
1103 advance(state, CallSignal::RemoteEnd(kind), control);
1104 break;
1105 }
1097 if recording_flow.wanted() && roster.caption_bot().is_none() {
1106 if recording_flow.wanted() && roster.caption_bot().is_none() {
1098 timeline.record("recorder bot failed", "addParticipantFailure");
1107 timeline.record("recorder bot failed", "addParticipantFailure");
1099 recording_flow.failed();
1108 recording_flow.failed();
@@ -1109,7 +1118,6 @@ async fn drive(
1109 }
1118 }
1110 }
1119 }
1111 Ok(CallEvent::ConversationUpdate(body)) => {
1120 Ok(CallEvent::ConversationUpdate(body)) => {
1112 replier.reply(request_id, 200, "");
1113 if let Some(thread) = chat_thread_id(&body)
1121 if let Some(thread) = chat_thread_id(&body)
1114 && meeting_chat.as_ref() != Some(&thread)
1122 && meeting_chat.as_ref() != Some(&thread)
1115 {
1123 {
@@ -1149,7 +1157,6 @@ async fn drive(
1149 }
1157 }
1150 }
1158 }
1151 Ok(CallEvent::LocalParticipantUpdate(body)) => {
1159 Ok(CallEvent::LocalParticipantUpdate(body)) => {
1152 replier.reply(request_id, 200, "");
1153 let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1160 let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1154 if let Some(moved) = moved {
1161 if let Some(moved) = moved {
1155 timeline.record("breakout", format!("moved to {}", moved.room_name));
1162 timeline.record("breakout", format!("moved to {}", moved.room_name));
@@ -1157,7 +1164,6 @@ async fn drive(
1157 }
1164 }
1158 }
1165 }
1159 Ok(CallEvent::Replacement(body)) => {
1166 Ok(CallEvent::Replacement(body)) => {
1160 replier.reply(request_id, 200, "");
1161 let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1167 let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1162 if let Some(moved) = invited {
1168 if let Some(moved) = invited {
1163 timeline.record("breakout", format!("invited to {}", moved.room_name));
1169 timeline.record("breakout", format!("invited to {}", moved.room_name));
@@ -1165,17 +1171,14 @@ async fn drive(
1165 }
1171 }
1166 }
1172 }
1167 Ok(CallEvent::ContentShareUpdate(body)) => {
1173 Ok(CallEvent::ContentShareUpdate(body)) => {
1168 replier.reply(request_id, 200, "");
1169 if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1174 if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1170 control.send(CallUpdate::Whiteboard(Some(share)));
1175 control.send(CallUpdate::Whiteboard(Some(share)));
1171 }
1176 }
1172 }
1177 }
1173 Ok(CallEvent::ContentShareEnd(_)) => {
1178 Ok(CallEvent::ContentShareEnd(_)) => {
1174 replier.reply(request_id, 200, "");
1175 control.send(CallUpdate::Whiteboard(None));
1179 control.send(CallUpdate::Whiteboard(None));
1176 }
1180 }
1177 Ok(CallEvent::Transfer(event)) => {
1181 Ok(CallEvent::Transfer(event)) => {
1178 replier.reply(request_id, 200, "");
1179 match event {
1182 match event {
1180 TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"),
1183 TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"),
1181 completed if completed.succeeded() => {
1184 completed if completed.succeeded() => {
@@ -1193,19 +1196,16 @@ async fn drive(
1193 }
1196 }
1194 }
1197 }
1195 Ok(CallEvent::Reactions(events)) => {
1198 Ok(CallEvent::Reactions(events)) => {
1196 replier.reply(request_id, 200, "");
1197 for event in events {
1199 for event in events {
1198 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
1200 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
1199 }
1201 }
1200 }
1202 }
1201 Ok(CallEvent::Progress(status)) => {
1203 Ok(CallEvent::Progress(status)) => {
1202 replier.reply(request_id, 200, "");
1203 if status == ProgressStatus::Ringing {
1204 if status == ProgressStatus::Ringing {
1204 control.send(CallUpdate::Progress(Progress::Ringing));
1205 control.send(CallUpdate::Progress(Progress::Ringing));
1205 }
1206 }
1206 }
1207 }
1207 Ok(CallEvent::ControlVideoStreaming(body)) => {
1208 Ok(CallEvent::ControlVideoStreaming(body)) => {
1208 replier.reply(request_id, 200, "");
1209 let Some(request) = parse_request(&body) else { continue };
1209 let Some(request) = parse_request(&body) else { continue };
1210 let Some(limits) = send_requests.admit(&request) else { continue };
1210 let Some(limits) = send_requests.admit(&request) else { continue };
1211 let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
1211 let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
@@ -1217,23 +1217,44 @@ async fn drive(
1217 }
1217 }
1218 }
1218 }
1219 Ok(CallEvent::Speakers(sources)) => {
1219 Ok(CallEvent::Speakers(sources)) => {
1220 replier.reply(request_id, 200, "");
1221 let speakers = roster.mris_for_sources(&sources);
1220 let speakers = roster.mris_for_sources(&sources);
1222 if video.note_speakers(&speakers) {
1221 if video.note_speakers(&speakers) {
1223 send_receive_change(control, video.reselect(&roster));
1222 send_receive_change(control, video.reselect(&roster));
1224 }
1223 }
1225 control.send(CallUpdate::Speakers(speakers));
1224 control.send(CallUpdate::Speakers(speakers));
1226 }
1225 }
1226 Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => {
1227 live.skip_leave = true;
1228 let end = embedded_end(&body);
1229 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1230 report.end = end;
1231 advance(state, CallSignal::RemoteEnd(kind), control);
1232 break;
1233 }
1234 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1235 RejectedOffer::SamePeer => {
1236 same_peer_deadline = None;
1237 if let Some(pending) = same_peer.take() {
1238 rollback_offer(&current.peer).await;
1239 undo_change(pending.change, &mut local_video, control);
1240 }
1241 }
1242 RejectedOffer::NewPeer => {
1243 if let Some(pending) = next.take() {
1244 pending.session.peer.close();
1245 }
1246 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1247 }
1248 RejectedOffer::None => {}
1249 },
1227 Ok(CallEvent::End(end)) => {
1250 Ok(CallEvent::End(end)) => {
1228 replier.reply(request_id, 200, "");
1229 let kind = end.kind();
1251 let kind = end.kind();
1230 report.end = Some(end);
1252 report.end = Some(end);
1231 advance(state, CallSignal::RemoteEnd(kind), control);
1253 advance(state, CallSignal::RemoteEnd(kind), control);
1232 break;
1254 break;
1233 }
1255 }
1234 Ok(_) => replier.reply(request_id, 200, ""),
1256 Ok(_) => {}
1235 Err(error) => {
1257 Err(error) => {
1236 replier.reply(request_id, 200, "");
1237 timeline.record("callback not understood", error.to_string());
1258 timeline.record("callback not understood", error.to_string());
1238 }
1259 }
1239 }
1260 }
@@ -2609,9 +2630,7 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
2609 {
2630 {
2610 let waited = timeout(END_CALLBACK_WAIT, async {
2631 let waited = timeout(END_CALLBACK_WAIT, async {
2611 while let Some(callback) = callbacks.recv().await {
2632 while let Some(callback) = callbacks.recv().await {
2612 let request_id = callback.request_id;
2613 let event = handle_callback(&callback, timeline);
2633 let event = handle_callback(&callback, timeline);
2614 inner.replier.reply(request_id, 200, "");
2615 if let Ok(CallEvent::End(end)) = event {
2634 if let Ok(CallEvent::End(end)) = event {
2616 return Some(end);
2635 return Some(end);
2617 }
2636 }
@@ -2639,6 +2658,13 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
2639 timeline.record("closed", "peer closed, call route removed");
2658 timeline.record("closed", "peer closed, call route removed");
2640}
2659}
2641
2660
2661fn setup_end_kind(end: &CallEnd) -> EndKind {
2662 match end.kind() {
2663 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
2664 kind => kind,
2665 }
2666}
2667
2642fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
2668fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
2643 let body = decode_body(callback)?;
2669 let body = decode_body(callback)?;
2644 let (_, event) = classify(&callback.path, body)?;
2670 let (_, event) = classify(&callback.path, body)?;
@@ -2646,6 +2672,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2646 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2672 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2647 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2673 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2648 CallEvent::Progress(status) => format!("{status:?}"),
2674 CallEvent::Progress(status) => format!("{status:?}"),
2675 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) => outcome_summary(body),
2649 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2676 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2650 _ => String::new(),
2677 _ => String::new(),
2651 };
2678 };
crates/calling/src/callee_gate.rs +28 −7
@@ -1,21 +1,31 @@
1 1 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2 2 pub struct CalleeGate {
3 required: bool,
3 callees: usize,
4 failed: usize,
4 5 joined: bool,
5 6 media_connected: bool,
6 7 }
7 8
8 9 impl CalleeGate {
9 pub fn new(required: bool) -> Self {
10 pub fn new(callees: usize) -> Self {
10 11 CalleeGate {
11 required,
12 callees,
13 failed: 0,
12 14 joined: false,
13 15 media_connected: false,
14 16 }
15 17 }
16 18
17 19 pub fn is_waiting(&self) -> bool {
18 self.required && !self.joined
20 self.callees > 0 && !self.joined
21 }
22
23 pub fn callees_failed(&mut self, count: usize) -> bool {
24 if !self.is_waiting() {
25 return false;
26 }
27 self.failed += count;
28 self.failed >= self.callees
19 29 }
20 30
21 31 pub fn media_connected(&mut self) -> bool {
@@ -57,7 +67,7 @@ mod tests {
57 67
58 68 #[test]
59 69 fn media_waits_for_the_callee_when_required() {
60 let mut gate = CalleeGate::new(true);
70 let mut gate = CalleeGate::new(1);
61 71 assert!(!gate.media_connected());
62 72 assert!(gate.is_waiting());
63 73 assert!(gate.callee_joined());
@@ -67,14 +77,25 @@ mod tests {
67 77
68 78 #[test]
69 79 fn a_callee_before_media_does_not_fire_early() {
70 let mut gate = CalleeGate::new(true);
80 let mut gate = CalleeGate::new(1);
71 81 assert!(!gate.callee_joined());
72 82 assert!(gate.media_connected());
73 83 }
74 84
85 #[test]
86 fn the_call_fails_only_when_every_callee_failed() {
87 let mut gate = CalleeGate::new(3);
88 assert!(!gate.callees_failed(1));
89 assert!(gate.callees_failed(2));
90 let mut joined = CalleeGate::new(1);
91 joined.callee_joined();
92 assert!(!joined.callees_failed(1));
93 assert!(!CalleeGate::new(0).callees_failed(1));
94 }
95
75 96 #[test]
76 97 fn an_unrequired_gate_never_waits() {
77 let mut gate = CalleeGate::new(false);
98 let mut gate = CalleeGate::new(0);
78 99 assert!(!gate.is_waiting());
79 100 assert!(gate.media_connected());
80 101 assert!(!gate.callee_joined());
@@ -1,21 +1,31 @@
1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2pub struct CalleeGate {
2pub struct CalleeGate {
3 required: bool,
3 callees: usize,
4 failed: usize,
4 joined: bool,
5 joined: bool,
5 media_connected: bool,
6 media_connected: bool,
6}
7}
7
8
8impl CalleeGate {
9impl CalleeGate {
9 pub fn new(required: bool) -> Self {
10 pub fn new(callees: usize) -> Self {
10 CalleeGate {
11 CalleeGate {
11 required,
12 callees,
13 failed: 0,
12 joined: false,
14 joined: false,
13 media_connected: false,
15 media_connected: false,
14 }
16 }
15 }
17 }
16
18
17 pub fn is_waiting(&self) -> bool {
19 pub fn is_waiting(&self) -> bool {
18 self.required && !self.joined
20 self.callees > 0 && !self.joined
21 }
22
23 pub fn callees_failed(&mut self, count: usize) -> bool {
24 if !self.is_waiting() {
25 return false;
26 }
27 self.failed += count;
28 self.failed >= self.callees
19 }
29 }
20
30
21 pub fn media_connected(&mut self) -> bool {
31 pub fn media_connected(&mut self) -> bool {
@@ -57,7 +67,7 @@ mod tests {
57
67
58 #[test]
68 #[test]
59 fn media_waits_for_the_callee_when_required() {
69 fn media_waits_for_the_callee_when_required() {
60 let mut gate = CalleeGate::new(true);
70 let mut gate = CalleeGate::new(1);
61 assert!(!gate.media_connected());
71 assert!(!gate.media_connected());
62 assert!(gate.is_waiting());
72 assert!(gate.is_waiting());
63 assert!(gate.callee_joined());
73 assert!(gate.callee_joined());
@@ -67,14 +77,25 @@ mod tests {
67
77
68 #[test]
78 #[test]
69 fn a_callee_before_media_does_not_fire_early() {
79 fn a_callee_before_media_does_not_fire_early() {
70 let mut gate = CalleeGate::new(true);
80 let mut gate = CalleeGate::new(1);
71 assert!(!gate.callee_joined());
81 assert!(!gate.callee_joined());
72 assert!(gate.media_connected());
82 assert!(gate.media_connected());
73 }
83 }
74
84
85 #[test]
86 fn the_call_fails_only_when_every_callee_failed() {
87 let mut gate = CalleeGate::new(3);
88 assert!(!gate.callees_failed(1));
89 assert!(gate.callees_failed(2));
90 let mut joined = CalleeGate::new(1);
91 joined.callee_joined();
92 assert!(!joined.callees_failed(1));
93 assert!(!CalleeGate::new(0).callees_failed(1));
94 }
95
75 #[test]
96 #[test]
76 fn an_unrequired_gate_never_waits() {
97 fn an_unrequired_gate_never_waits() {
77 let mut gate = CalleeGate::new(false);
98 let mut gate = CalleeGate::new(0);
78 assert!(!gate.is_waiting());
99 assert!(!gate.is_waiting());
79 assert!(gate.media_connected());
100 assert!(gate.media_connected());
80 assert!(!gate.callee_joined());
101 assert!(!gate.callee_joined());
crates/calling/src/engine.rs +21 −12
@@ -20,7 +20,7 @@ use crate::signaling::{
20 20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
21 21 };
22 22 use crate::timeline::Timeline;
23 use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};
23 use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, callback_reply_body, classify, decode_body};
24 24
25 25 const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
26 26 const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
@@ -113,6 +113,11 @@ enum RingCommand {
113 113 Drop,
114 114 }
115 115
116 struct Route {
117 sender: mpsc::UnboundedSender<TrouterCallback>,
118 links: CallbackLinks,
119 }
120
116 121 pub(crate) struct Inner {
117 122 pub(crate) session: Session,
118 123 pub(crate) poll_session: Session,
@@ -121,7 +126,7 @@ pub(crate) struct Inner {
121 126 pub(crate) replier: CallbackReplier,
122 127 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
123 128 endpoint: Mutex<TrouterEndpoint>,
124 routes: Mutex<HashMap<String, mpsc::UnboundedSender<TrouterCallback>>>,
129 routes: Mutex<HashMap<String, Route>>,
125 130 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
126 131 seen: Mutex<HashMap<(String, String), Instant>>,
127 132 next_ring_id: AtomicU64,
@@ -137,9 +142,10 @@ impl Inner {
137 142 self.endpoint.lock().expect("endpoint lock").clone()
138 143 }
139 144
140 pub(crate) fn register_route(&self, call_id: &str) -> mpsc::UnboundedReceiver<TrouterCallback> {
145 pub(crate) fn register_route(&self, links: &CallbackLinks) -> mpsc::UnboundedReceiver<TrouterCallback> {
141 146 let (sender, receiver) = mpsc::unbounded_channel();
142 self.routes.lock().expect("routes lock").insert(call_id.to_owned(), sender);
147 let route = Route { sender, links: links.clone() };
148 self.routes.lock().expect("routes lock").insert(links.call_id().to_owned(), route);
143 149 receiver
144 150 }
145 151
@@ -181,12 +187,16 @@ impl Inner {
181 187 self.replier.reply(callback.request_id, 200, "");
182 188 return;
183 189 };
184 let sender = self.routes.lock().expect("routes lock").get(&call_id).cloned();
185 match sender {
186 Some(sender) => {
187 if let Err(rejected) = sender.send(callback) {
188 self.replier.reply(rejected.0.request_id, 200, "");
189 }
190 let route = self
191 .routes
192 .lock()
193 .expect("routes lock")
194 .get(&call_id)
195 .map(|route| (route.sender.clone(), callback_reply_body(&callback.path, &route.links)));
196 match route {
197 Some((sender, reply)) => {
198 self.replier.reply(callback.request_id, 200, reply);
199 let _ = sender.send(callback);
190 200 }
191 201 None => self.replier.reply(callback.request_id, 200, ""),
192 202 }
@@ -411,7 +421,7 @@ async fn ring_task(
411 421 let inner = engine.inner.clone();
412 422 let links = inner.callback_links();
413 423 let route_id = links.call_id().to_owned();
414 let mut callbacks = inner.register_route(&route_id);
424 let mut callbacks = inner.register_route(&links);
415 425 let timeline = Timeline::new(inner.config.trace);
416 426 let signaling = inner.signaling(timeline.clone());
417 427 let participant_id = if notification.participant_id.is_empty() {
@@ -462,7 +472,6 @@ async fn ring_task(
462 472 tokio::select! {
463 473 callback = callbacks.recv() => {
464 474 let Some(callback) = callback else { break };
465 inner.replier.reply(callback.request_id, 200, "");
466 475 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
467 476 if let Ok((_, CallEvent::End(end))) = event {
468 477 inner.emit(EngineEvent::RingEnded {
@@ -20,7 +20,7 @@ use crate::signaling::{
20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
21};
21};
22use crate::timeline::Timeline;
22use crate::timeline::Timeline;
23use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, classify, decode_body};
23use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, callback_reply_body, classify, decode_body};
24
24
25const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
25const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
26const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
26const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
@@ -113,6 +113,11 @@ enum RingCommand {
113 Drop,
113 Drop,
114}
114}
115
115
116struct Route {
117 sender: mpsc::UnboundedSender<TrouterCallback>,
118 links: CallbackLinks,
119}
120
116pub(crate) struct Inner {
121pub(crate) struct Inner {
117 pub(crate) session: Session,
122 pub(crate) session: Session,
118 pub(crate) poll_session: Session,
123 pub(crate) poll_session: Session,
@@ -121,7 +126,7 @@ pub(crate) struct Inner {
121 pub(crate) replier: CallbackReplier,
126 pub(crate) replier: CallbackReplier,
122 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
127 pub(crate) gate: Arc<tokio::sync::Mutex<()>>,
123 endpoint: Mutex<TrouterEndpoint>,
128 endpoint: Mutex<TrouterEndpoint>,
124 routes: Mutex<HashMap<String, mpsc::UnboundedSender<TrouterCallback>>>,
129 routes: Mutex<HashMap<String, Route>>,
125 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
130 rings: Mutex<HashMap<u64, mpsc::UnboundedSender<RingCommand>>>,
126 seen: Mutex<HashMap<(String, String), Instant>>,
131 seen: Mutex<HashMap<(String, String), Instant>>,
127 next_ring_id: AtomicU64,
132 next_ring_id: AtomicU64,
@@ -137,9 +142,10 @@ impl Inner {
137 self.endpoint.lock().expect("endpoint lock").clone()
142 self.endpoint.lock().expect("endpoint lock").clone()
138 }
143 }
139
144
140 pub(crate) fn register_route(&self, call_id: &str) -> mpsc::UnboundedReceiver<TrouterCallback> {
145 pub(crate) fn register_route(&self, links: &CallbackLinks) -> mpsc::UnboundedReceiver<TrouterCallback> {
141 let (sender, receiver) = mpsc::unbounded_channel();
146 let (sender, receiver) = mpsc::unbounded_channel();
142 self.routes.lock().expect("routes lock").insert(call_id.to_owned(), sender);
147 let route = Route { sender, links: links.clone() };
148 self.routes.lock().expect("routes lock").insert(links.call_id().to_owned(), route);
143 receiver
149 receiver
144 }
150 }
145
151
@@ -181,12 +187,16 @@ impl Inner {
181 self.replier.reply(callback.request_id, 200, "");
187 self.replier.reply(callback.request_id, 200, "");
182 return;
188 return;
183 };
189 };
184 let sender = self.routes.lock().expect("routes lock").get(&call_id).cloned();
190 let route = self
185 match sender {
191 .routes
186 Some(sender) => {
192 .lock()
187 if let Err(rejected) = sender.send(callback) {
193 .expect("routes lock")
188 self.replier.reply(rejected.0.request_id, 200, "");
194 .get(&call_id)
189 }
195 .map(|route| (route.sender.clone(), callback_reply_body(&callback.path, &route.links)));
196 match route {
197 Some((sender, reply)) => {
198 self.replier.reply(callback.request_id, 200, reply);
199 let _ = sender.send(callback);
190 }
200 }
191 None => self.replier.reply(callback.request_id, 200, ""),
201 None => self.replier.reply(callback.request_id, 200, ""),
192 }
202 }
@@ -411,7 +421,7 @@ async fn ring_task(
411 let inner = engine.inner.clone();
421 let inner = engine.inner.clone();
412 let links = inner.callback_links();
422 let links = inner.callback_links();
413 let route_id = links.call_id().to_owned();
423 let route_id = links.call_id().to_owned();
414 let mut callbacks = inner.register_route(&route_id);
424 let mut callbacks = inner.register_route(&links);
415 let timeline = Timeline::new(inner.config.trace);
425 let timeline = Timeline::new(inner.config.trace);
416 let signaling = inner.signaling(timeline.clone());
426 let signaling = inner.signaling(timeline.clone());
417 let participant_id = if notification.participant_id.is_empty() {
427 let participant_id = if notification.participant_id.is_empty() {
@@ -462,7 +472,6 @@ async fn ring_task(
462 tokio::select! {
472 tokio::select! {
463 callback = callbacks.recv() => {
473 callback = callbacks.recv() => {
464 let Some(callback) = callback else { break };
474 let Some(callback) = callback else { break };
465 inner.replier.reply(callback.request_id, 200, "");
466 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
475 let event = decode_body(&callback).and_then(|body| classify(&callback.path, body));
467 if let Ok((_, CallEvent::End(end))) = event {
476 if let Ok((_, CallEvent::End(end))) = event {
468 inner.emit(EngineEvent::RingEnded {
477 inner.emit(EngineEvent::RingEnded {
crates/calling/src/lib.rs +1 −0
@@ -41,6 +41,7 @@ pub mod voice_high_pass;
41 41 pub mod wav_dump;
42 42 pub mod mute;
43 43 pub mod organizer;
44 pub mod outcome;
44 45 pub mod pcm;
45 46 pub mod push;
46 47 pub mod reaction;
@@ -41,6 +41,7 @@ pub mod voice_high_pass;
41pub mod wav_dump;
41pub mod wav_dump;
42pub mod mute;
42pub mod mute;
43pub mod organizer;
43pub mod organizer;
44pub mod outcome;
44pub mod pcm;
45pub mod pcm;
45pub mod push;
46pub mod push;
46pub mod reaction;
47pub mod reaction;
crates/calling/src/outcome.rs added +117 −0
@@ -0,0 +1,117 @@
1 use serde_json::Value;
2
3 use crate::trouter_events::CallEnd;
4
5 const OUTCOME_KEYS: [&str; 6] = ["code", "subCode", "phrase", "reason", "resultCategories", "failureReason"];
6 const MAX_FIELDS: usize = 12;
7
8 pub fn outcome_summary(body: &Value) -> String {
9 let mut fields = Vec::new();
10 collect_fields(body, "", &mut fields);
11 if fields.is_empty() {
12 return format!("keys [{}]", top_level_keys(body));
13 }
14 fields.join(" ")
15 }
16
17 pub fn embedded_end(body: &Value) -> Option<CallEnd> {
18 let holder = find_code_holder(body)?;
19 Some(CallEnd {
20 code: holder["code"].as_i64()?,
21 sub_code: holder["subCode"].as_i64().unwrap_or_default(),
22 phrase: holder["phrase"].as_str().unwrap_or_default().to_owned(),
23 accepted_elsewhere_by: None,
24 })
25 }
26
27 pub fn failed_participant_count(body: &Value) -> usize {
28 body["participantInfos"].as_array().map_or(1, |infos| infos.len().max(1))
29 }
30
31 fn collect_fields(value: &Value, path: &str, fields: &mut Vec<String>) {
32 match value {
33 Value::Object(map) => {
34 for (key, child) in map {
35 if fields.len() >= MAX_FIELDS {
36 return;
37 }
38 let child_path = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
39 if OUTCOME_KEYS.contains(&key.as_str()) && !child.is_object() {
40 fields.push(format!("{child_path}={}", scalar_text(child)));
41 } else {
42 collect_fields(child, &child_path, fields);
43 }
44 }
45 }
46 Value::Array(items) => {
47 for (index, item) in items.iter().enumerate() {
48 collect_fields(item, &format!("{path}[{index}]"), fields);
49 }
50 }
51 _ => {}
52 }
53 }
54
55 fn scalar_text(value: &Value) -> String {
56 match value {
57 Value::String(text) => text.clone(),
58 other => other.to_string(),
59 }
60 }
61
62 fn top_level_keys(body: &Value) -> String {
63 body.as_object()
64 .map(|map| map.keys().cloned().collect::<Vec<_>>().join(","))
65 .unwrap_or_default()
66 }
67
68 fn find_code_holder(value: &Value) -> Option<&Value> {
69 match value {
70 Value::Object(map) => {
71 if map.get("code").is_some_and(Value::is_i64) {
72 return Some(value);
73 }
74 map.values().find_map(find_code_holder)
75 }
76 Value::Array(items) => items.iter().find_map(find_code_holder),
77 _ => None,
78 }
79 }
80
81 #[cfg(test)]
82 mod tests {
83 use serde_json::json;
84
85 use super::*;
86
87 #[test]
88 fn the_summary_keeps_codes_and_drops_names() {
89 let body = json!({"conversationEnd": {"reason": "noError", "code": 480, "subCode": 10037, "phrase": "No endpoint",
90 "participant": {"displayName": "Bea", "id": "8:orgid:bea"}}});
91 let summary = outcome_summary(&body);
92 assert!(summary.contains("conversationEnd.code=480"));
93 assert!(summary.contains("conversationEnd.subCode=10037"));
94 assert!(summary.contains("conversationEnd.phrase=No endpoint"));
95 assert!(!summary.contains("Bea") && !summary.contains("orgid"));
96 }
97
98 #[test]
99 fn failures_count_every_listed_participant() {
100 assert_eq!(failed_participant_count(&json!({"participantInfos": [{"id": "a"}, {"id": "b"}]})), 2);
101 assert_eq!(failed_participant_count(&json!({"participantInfos": []})), 1);
102 assert_eq!(failed_participant_count(&json!({})), 1);
103 }
104
105 #[test]
106 fn a_body_without_codes_lists_its_keys() {
107 assert_eq!(outcome_summary(&json!({"conversationEnd": {}, "links": {}})), "keys [conversationEnd,links]");
108 }
109
110 #[test]
111 fn the_first_nested_code_becomes_the_end() {
112 let body = json!({"participantInfos": [{"id": "x", "failure": {"code": 408, "subCode": 10408, "phrase": "timeout"}}]});
113 let end = embedded_end(&body).unwrap();
114 assert_eq!((end.code, end.sub_code, end.phrase.as_str()), (408, 10408, "timeout"));
115 assert!(embedded_end(&json!({"conversationEnd": {"reason": "x"}})).is_none());
116 }
117 }
@@ -0,0 +1,117 @@
1use serde_json::Value;
2
3use crate::trouter_events::CallEnd;
4
5const OUTCOME_KEYS: [&str; 6] = ["code", "subCode", "phrase", "reason", "resultCategories", "failureReason"];
6const MAX_FIELDS: usize = 12;
7
8pub fn outcome_summary(body: &Value) -> String {
9 let mut fields = Vec::new();
10 collect_fields(body, "", &mut fields);
11 if fields.is_empty() {
12 return format!("keys [{}]", top_level_keys(body));
13 }
14 fields.join(" ")
15}
16
17pub fn embedded_end(body: &Value) -> Option<CallEnd> {
18 let holder = find_code_holder(body)?;
19 Some(CallEnd {
20 code: holder["code"].as_i64()?,
21 sub_code: holder["subCode"].as_i64().unwrap_or_default(),
22 phrase: holder["phrase"].as_str().unwrap_or_default().to_owned(),
23 accepted_elsewhere_by: None,
24 })
25}
26
27pub fn failed_participant_count(body: &Value) -> usize {
28 body["participantInfos"].as_array().map_or(1, |infos| infos.len().max(1))
29}
30
31fn collect_fields(value: &Value, path: &str, fields: &mut Vec<String>) {
32 match value {
33 Value::Object(map) => {
34 for (key, child) in map {
35 if fields.len() >= MAX_FIELDS {
36 return;
37 }
38 let child_path = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
39 if OUTCOME_KEYS.contains(&key.as_str()) && !child.is_object() {
40 fields.push(format!("{child_path}={}", scalar_text(child)));
41 } else {
42 collect_fields(child, &child_path, fields);
43 }
44 }
45 }
46 Value::Array(items) => {
47 for (index, item) in items.iter().enumerate() {
48 collect_fields(item, &format!("{path}[{index}]"), fields);
49 }
50 }
51 _ => {}
52 }
53}
54
55fn scalar_text(value: &Value) -> String {
56 match value {
57 Value::String(text) => text.clone(),
58 other => other.to_string(),
59 }
60}
61
62fn top_level_keys(body: &Value) -> String {
63 body.as_object()
64 .map(|map| map.keys().cloned().collect::<Vec<_>>().join(","))
65 .unwrap_or_default()
66}
67
68fn find_code_holder(value: &Value) -> Option<&Value> {
69 match value {
70 Value::Object(map) => {
71 if map.get("code").is_some_and(Value::is_i64) {
72 return Some(value);
73 }
74 map.values().find_map(find_code_holder)
75 }
76 Value::Array(items) => items.iter().find_map(find_code_holder),
77 _ => None,
78 }
79}
80
81#[cfg(test)]
82mod tests {
83 use serde_json::json;
84
85 use super::*;
86
87 #[test]
88 fn the_summary_keeps_codes_and_drops_names() {
89 let body = json!({"conversationEnd": {"reason": "noError", "code": 480, "subCode": 10037, "phrase": "No endpoint",
90 "participant": {"displayName": "Bea", "id": "8:orgid:bea"}}});
91 let summary = outcome_summary(&body);
92 assert!(summary.contains("conversationEnd.code=480"));
93 assert!(summary.contains("conversationEnd.subCode=10037"));
94 assert!(summary.contains("conversationEnd.phrase=No endpoint"));
95 assert!(!summary.contains("Bea") && !summary.contains("orgid"));
96 }
97
98 #[test]
99 fn failures_count_every_listed_participant() {
100 assert_eq!(failed_participant_count(&json!({"participantInfos": [{"id": "a"}, {"id": "b"}]})), 2);
101 assert_eq!(failed_participant_count(&json!({"participantInfos": []})), 1);
102 assert_eq!(failed_participant_count(&json!({})), 1);
103 }
104
105 #[test]
106 fn a_body_without_codes_lists_its_keys() {
107 assert_eq!(outcome_summary(&json!({"conversationEnd": {}, "links": {}})), "keys [conversationEnd,links]");
108 }
109
110 #[test]
111 fn the_first_nested_code_becomes_the_end() {
112 let body = json!({"participantInfos": [{"id": "x", "failure": {"code": 408, "subCode": 10408, "phrase": "timeout"}}]});
113 let end = embedded_end(&body).unwrap();
114 assert_eq!((end.code, end.sub_code, end.phrase.as_str()), (408, 10408, "timeout"));
115 assert!(embedded_end(&json!({"conversationEnd": {"reason": "x"}})).is_none());
116 }
117}
crates/calling/src/renegotiation.rs +28 −0
@@ -104,12 +104,40 @@ impl MediaNegotiator {
104 104 pub fn escalation_failed(&mut self) {
105 105 self.own_offer_pending = false;
106 106 }
107
108 pub fn on_rejection(&mut self) -> RejectedOffer {
109 if std::mem::take(&mut self.same_peer_offer_pending) {
110 return RejectedOffer::SamePeer;
111 }
112 if std::mem::take(&mut self.own_offer_pending) {
113 return RejectedOffer::NewPeer;
114 }
115 RejectedOffer::None
116 }
117 }
118
119 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
120 pub enum RejectedOffer {
121 SamePeer,
122 NewPeer,
123 None,
107 124 }
108 125
109 126 #[cfg(test)]
110 127 mod tests {
111 128 use super::*;
112 129
130 #[test]
131 fn a_rejection_clears_the_pending_offer() {
132 let mut negotiator = MediaNegotiator::default();
133 assert_eq!(negotiator.on_acceptance(true, true), MediaAction::ApplyAnswerThenEscalate);
134 assert_eq!(negotiator.on_rejection(), RejectedOffer::NewPeer);
135 assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
136 assert!(negotiator.begin_same_peer_offer());
137 assert_eq!(negotiator.on_rejection(), RejectedOffer::SamePeer);
138 assert_eq!(negotiator.on_rejection(), RejectedOffer::None);
139 }
140
113 141 #[test]
114 142 fn the_first_answer_decides_the_path() {
115 143 let mut direct = MediaNegotiator::default();
@@ -104,12 +104,40 @@ impl MediaNegotiator {
104 pub fn escalation_failed(&mut self) {
104 pub fn escalation_failed(&mut self) {
105 self.own_offer_pending = false;
105 self.own_offer_pending = false;
106 }
106 }
107
108 pub fn on_rejection(&mut self) -> RejectedOffer {
109 if std::mem::take(&mut self.same_peer_offer_pending) {
110 return RejectedOffer::SamePeer;
111 }
112 if std::mem::take(&mut self.own_offer_pending) {
113 return RejectedOffer::NewPeer;
114 }
115 RejectedOffer::None
116 }
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum RejectedOffer {
121 SamePeer,
122 NewPeer,
123 None,
107}
124}
108
125
109#[cfg(test)]
126#[cfg(test)]
110mod tests {
127mod tests {
111 use super::*;
128 use super::*;
112
129
130 #[test]
131 fn a_rejection_clears_the_pending_offer() {
132 let mut negotiator = MediaNegotiator::default();
133 assert_eq!(negotiator.on_acceptance(true, true), MediaAction::ApplyAnswerThenEscalate);
134 assert_eq!(negotiator.on_rejection(), RejectedOffer::NewPeer);
135 assert_eq!(negotiator.on_media_answer(), MediaAction::Ignore);
136 assert!(negotiator.begin_same_peer_offer());
137 assert_eq!(negotiator.on_rejection(), RejectedOffer::SamePeer);
138 assert_eq!(negotiator.on_rejection(), RejectedOffer::None);
139 }
140
113 #[test]
141 #[test]
114 fn the_first_answer_decides_the_path() {
142 fn the_first_answer_decides_the_path() {
115 let mut direct = MediaNegotiator::default();
143 let mut direct = MediaNegotiator::default();
crates/calling/src/trouter_events.rs +23 −0
@@ -135,6 +135,8 @@ pub enum CallEvent {
135 135 ControlVideoStreaming(Value),
136 136 AddParticipantSuccess(Value),
137 137 AddParticipantFailure(Value),
138 ConversationEnd(Value),
139 Rejection(Value),
138 140 Reactions(Vec<ReactionEvent>),
139 141 LocalParticipantUpdate(Value),
140 142 Replacement(Value),
@@ -158,6 +160,8 @@ impl CallEvent {
158 160 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
159 161 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
160 162 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
163 CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(),
164 CallEvent::Rejection(_) => "call/rejection".into(),
161 165 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
162 166 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
163 167 CallEvent::Replacement(_) => "call/replacement".into(),
@@ -179,6 +183,8 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
179 183 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
180 184 ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
181 185 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
186 ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body),
187 ("call", "rejection") => CallEvent::Rejection(body),
182 188 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
183 189 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
184 190 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
@@ -204,6 +210,13 @@ pub fn callback_call_id(path: &str) -> Option<String> {
204 210 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
205 211 }
206 212
213 pub fn callback_reply_body(path: &str, links: &CallbackLinks) -> String {
214 match split_callback_path(path) {
215 Ok((_, scope, event)) if scope == "call" && event == "acceptance" => acceptance_acknowledgement(links).to_string(),
216 _ => String::new(),
217 }
218 }
219
207 220 fn split_callback_path(path: &str) -> Result<(String, String, String)> {
208 221 let rest = path
209 222 .strip_prefix(CALLBACK_ROOT)
@@ -556,4 +569,14 @@ mod tests {
556 569 assert_eq!(callback_call_id("unifiedPresenceService"), None);
557 570 assert_eq!(callback_call_id(""), None);
558 571 }
572
573 #[test]
574 fn only_the_acceptance_reply_carries_the_acknowledgement() {
575 let links = CallbackLinks::new("https://trouter.example/", "abc");
576 let acceptance = callback_reply_body("callAgent/abc/1/call/acceptance/", &links);
577 let parsed: Value = serde_json::from_str(&acceptance).unwrap();
578 assert!(parsed["callAcceptanceAcknowledgement"]["links"].is_object());
579 assert_eq!(callback_reply_body("callAgent/abc/1/call/mediaAnswer/", &links), "");
580 assert_eq!(callback_reply_body("callAgent/abc/1/conversation/rosterUpdate/", &links), "");
581 }
559 582 }
@@ -135,6 +135,8 @@ pub enum CallEvent {
135 ControlVideoStreaming(Value),
135 ControlVideoStreaming(Value),
136 AddParticipantSuccess(Value),
136 AddParticipantSuccess(Value),
137 AddParticipantFailure(Value),
137 AddParticipantFailure(Value),
138 ConversationEnd(Value),
139 Rejection(Value),
138 Reactions(Vec<ReactionEvent>),
140 Reactions(Vec<ReactionEvent>),
139 LocalParticipantUpdate(Value),
141 LocalParticipantUpdate(Value),
140 Replacement(Value),
142 Replacement(Value),
@@ -158,6 +160,8 @@ impl CallEvent {
158 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
160 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
159 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
161 CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
160 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
162 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
163 CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(),
164 CallEvent::Rejection(_) => "call/rejection".into(),
161 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
165 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
162 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
166 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
163 CallEvent::Replacement(_) => "call/replacement".into(),
167 CallEvent::Replacement(_) => "call/replacement".into(),
@@ -179,6 +183,8 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
179 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
183 ("conversation", "addParticipantSuccess") => CallEvent::AddParticipantSuccess(body),
180 ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
184 ("conversation", "receiveMessage") => CallEvent::Reactions(parse_reactions(&body)),
181 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
185 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
186 ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body),
187 ("call", "rejection") => CallEvent::Rejection(body),
182 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
188 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
183 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
189 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
184 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
190 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
@@ -204,6 +210,13 @@ pub fn callback_call_id(path: &str) -> Option<String> {
204 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
210 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
205}
211}
206
212
213pub fn callback_reply_body(path: &str, links: &CallbackLinks) -> String {
214 match split_callback_path(path) {
215 Ok((_, scope, event)) if scope == "call" && event == "acceptance" => acceptance_acknowledgement(links).to_string(),
216 _ => String::new(),
217 }
218}
219
207fn split_callback_path(path: &str) -> Result<(String, String, String)> {
220fn split_callback_path(path: &str) -> Result<(String, String, String)> {
208 let rest = path
221 let rest = path
209 .strip_prefix(CALLBACK_ROOT)
222 .strip_prefix(CALLBACK_ROOT)
@@ -556,4 +569,14 @@ mod tests {
556 assert_eq!(callback_call_id("unifiedPresenceService"), None);
569 assert_eq!(callback_call_id("unifiedPresenceService"), None);
557 assert_eq!(callback_call_id(""), None);
570 assert_eq!(callback_call_id(""), None);
558 }
571 }
572
573 #[test]
574 fn only_the_acceptance_reply_carries_the_acknowledgement() {
575 let links = CallbackLinks::new("https://trouter.example/", "abc");
576 let acceptance = callback_reply_body("callAgent/abc/1/call/acceptance/", &links);
577 let parsed: Value = serde_json::from_str(&acceptance).unwrap();
578 assert!(parsed["callAcceptanceAcknowledgement"]["links"].is_object());
579 assert_eq!(callback_reply_body("callAgent/abc/1/call/mediaAnswer/", &links), "");
580 assert_eq!(callback_reply_body("callAgent/abc/1/conversation/rosterUpdate/", &links), "");
581 }
559}
582}