| | |
| | | io::{BufRead, BufReader, Read, Write}, |
| | | net::{TcpListener, TcpStream}, |
| | | process::{Child, Command, Stdio}, |
| | | sync::{Arc, Mutex}, |
| | | sync::{Arc, Mutex, mpsc}, |
| | | thread, |
| | | time::{Duration, SystemTime, UNIX_EPOCH}, |
| | | }; |
| | |
| | | const DEFAULT_BIND_ADDR: &str = "127.0.0.1:18080"; |
| | | const HTTP_READ_LIMIT_BYTES: usize = 1024 * 1024; |
| | | const DEFAULT_START_READY_TIMEOUT_MS: u64 = 10_000; |
| | | const ANCHORED_CALLBACK_MAX_ATTEMPTS: u32 = 3; |
| | | const ANCHORED_CALLBACK_RETRY_DELAY: Duration = Duration::from_millis(50); |
| | | |
| | | pub fn service_mode_enabled() -> bool { |
| | | env::args().any(|arg| arg == "service" || arg == "--service") |
| | |
| | | trace_id, |
| | | ); |
| | | } |
| | | let child = match spawn_worker(&start_req, &profile, &state.config) { |
| | | let child = match spawn_worker(&start_req, &profile, &state.config, trace_id.as_deref()) { |
| | | Ok(value) => value, |
| | | Err(spawn_error) => { |
| | | warn!( |
| | |
| | | let runtime_session_id = format!("rt_{}", start_req.call_id); |
| | | let mut child = child; |
| | | let child_stdout = child.stdout.take(); |
| | | let event_callback_url = start_req |
| | | .event_callback |
| | | .as_ref() |
| | | .and_then(|value| value.url.clone()) |
| | | .filter(|value| !value.trim().is_empty()); |
| | | let event_callback_token = Some(profile.event_callback_token.clone()); |
| | | let event_callback_sender = if event_callback_url.is_some() { |
| | | let (sender, receiver) = mpsc::channel(); |
| | | spawn_event_callback_worker(receiver); |
| | | Some(sender) |
| | | } else { |
| | | None |
| | | }; |
| | | let session = HelperSession { |
| | | call_id: start_req.call_id.clone(), |
| | | trace_id: trace_id.clone(), |
| | | runtime_session_nonce: start_req.runtime_session_nonce.clone(), |
| | | runtime_session_id, |
| | | event_callback_url: start_req |
| | | .event_callback |
| | | .as_ref() |
| | | .and_then(|value| value.url.clone()) |
| | | .filter(|value| !value.trim().is_empty()), |
| | | event_callback_token: Some(profile.event_callback_token.clone()), |
| | | event_callback_url, |
| | | event_callback_token, |
| | | event_callback_sender, |
| | | status: "STARTING".to_string(), |
| | | bot_participant_joined: false, |
| | | bot_track_ready: false, |
| | |
| | | req: &SessionStartRequest, |
| | | profile: &AuthProfile, |
| | | config: &ServiceConfig, |
| | | trace_id: Option<&str>, |
| | | ) -> Result<Child> { |
| | | let exe = env::current_exe().context("failed to resolve helper executable")?; |
| | | let mut command = Command::new(exe); |
| | |
| | | .env("CV_CALL_ID", &req.call_id) |
| | | .env( |
| | | "CV_TRACE_ID", |
| | | req.trace_id |
| | | .clone() |
| | | trace_id |
| | | .map(str::to_string) |
| | | .unwrap_or_else(|| format!("trace_{}", req.call_id)), |
| | | ) |
| | | .env("CV_RUNTIME_CALL_ID", &req.call_id) |
| | | .env( |
| | | "CV_RUNTIME_TRACE_ID", |
| | | req.trace_id |
| | | .clone() |
| | | trace_id |
| | | .map(str::to_string) |
| | | .unwrap_or_else(|| format!("trace_{}", req.call_id)), |
| | | ) |
| | | .env("CV_RUNTIME_SESSION_NONCE", &req.runtime_session_nonce) |
| | |
| | | .and_then(Value::as_str) |
| | | .unwrap_or("worker_event"); |
| | | let result = value.get("result").and_then(Value::as_str).unwrap_or("ok"); |
| | | let callback = { |
| | | let queued_callback = { |
| | | let Ok(mut sessions) = state.sessions.lock() else { |
| | | return; |
| | | }; |
| | | let Some(session) = sessions.get_mut(call_id) else { |
| | | return; |
| | | }; |
| | | let turn_id = value.get("turnId").and_then(Value::as_str); |
| | | let terminal = matches!( |
| | | event_name, |
| | | "turn_completed" | "turn_failed" | "turn_cancelled" |
| | | ); |
| | | if event_name == "turn_bridge_requested" { |
| | | session.active_turn_id = turn_id.map(str::to_string); |
| | | } |
| | | session.last_event_type = Some(event_name.to_string()); |
| | | session.last_event_at = now_millis(); |
| | | let callback = build_event_callback_dispatch(session, value); |
| | | let callback = if is_anchored_callback(value) && !anchored_callback_bound(session, value) { |
| | | warn!( |
| | | call_id = %call_id, |
| | | trace_id = ?session.trace_id, |
| | | event_name = %event_name, |
| | | "helper rejected unbound anchored callback" |
| | | ); |
| | | None |
| | | } else { |
| | | build_event_callback_dispatch(session, value) |
| | | }; |
| | | let callback_sender = session.event_callback_sender.clone(); |
| | | if result != "ok" { |
| | | session.status = "FAILED".to_string(); |
| | | session.bot_participant_joined = false; |
| | |
| | | _ => {} |
| | | } |
| | | } |
| | | callback |
| | | if terminal && turn_id == session.active_turn_id.as_deref() { |
| | | session.active_turn_id = None; |
| | | } |
| | | callback.zip(callback_sender) |
| | | }; |
| | | if let Some(callback) = callback { |
| | | dispatch_event_callback(callback); |
| | | if let Some((callback, sender)) = queued_callback { |
| | | if sender.send(callback).is_err() { |
| | | warn!( |
| | | call_id = %call_id, |
| | | event_name = %event_name, |
| | | "helper event callback queue closed" |
| | | ); |
| | | } |
| | | } |
| | | } |
| | | |
| | |
| | | }) |
| | | } |
| | | |
| | | fn dispatch_event_callback(callback: EventCallbackDispatch) { |
| | | fn spawn_event_callback_worker(receiver: mpsc::Receiver<EventCallbackDispatch>) { |
| | | thread::spawn(move || { |
| | | run_event_callback_worker(receiver, deliver_event_callback); |
| | | }); |
| | | } |
| | | |
| | | fn run_event_callback_worker<F>(receiver: mpsc::Receiver<EventCallbackDispatch>, mut deliver: F) |
| | | where |
| | | F: FnMut(EventCallbackDispatch), |
| | | { |
| | | while let Ok(callback) = receiver.recv() { |
| | | deliver(callback); |
| | | } |
| | | } |
| | | |
| | | fn deliver_event_callback(callback: EventCallbackDispatch) { |
| | | deliver_event_callback_with(callback, post_event_callback); |
| | | } |
| | | |
| | | fn deliver_event_callback_with<F>(callback: EventCallbackDispatch, mut post: F) |
| | | where |
| | | F: FnMut(&EventCallbackDispatch) -> Result<u16>, |
| | | { |
| | | let event_name = callback |
| | | .payload |
| | | .get("eventName") |
| | | .and_then(Value::as_str) |
| | | .unwrap_or("worker_event") |
| | | .to_string(); |
| | | match post_event_callback(&callback) { |
| | | let max_attempts = if is_anchored_callback(&callback.payload) { |
| | | ANCHORED_CALLBACK_MAX_ATTEMPTS |
| | | } else { |
| | | 1 |
| | | }; |
| | | for attempt in 1..=max_attempts { |
| | | let result = post(&callback); |
| | | let retry = |
| | | attempt < max_attempts && !matches!(&result, Ok(status) if (200..300).contains(status)); |
| | | match result { |
| | | Ok(status) if (200..300).contains(&status) => { |
| | | info!( |
| | | call_id = %callback.call_id, |
| | | trace_id = ?callback.trace_id, |
| | | event_name = %event_name, |
| | | status = status, |
| | | attempt = attempt, |
| | | "helper event callback delivered" |
| | | ); |
| | | return; |
| | | } |
| | | Ok(status) => { |
| | | warn!( |
| | |
| | | trace_id = ?callback.trace_id, |
| | | event_name = %event_name, |
| | | status = status, |
| | | attempt = attempt, |
| | | "helper event callback rejected" |
| | | ); |
| | | } |
| | |
| | | call_id = %callback.call_id, |
| | | trace_id = ?callback.trace_id, |
| | | event_name = %event_name, |
| | | attempt = attempt, |
| | | error = %error, |
| | | "helper event callback failed" |
| | | ); |
| | | } |
| | | } |
| | | }); |
| | | if retry { |
| | | thread::sleep(ANCHORED_CALLBACK_RETRY_DELAY); |
| | | } |
| | | } |
| | | } |
| | | |
| | | fn is_anchored_callback(payload: &Value) -> bool { |
| | | matches!( |
| | | payload.get("eventName").and_then(Value::as_str), |
| | | Some("helper_first_reply_audio_chunk_received" | "bot_reply_first_audio_frame_written") |
| | | ) && payload.get("serverDeltaSource").and_then(Value::as_str) == Some("stream_anchor_monotonic") |
| | | } |
| | | |
| | | fn anchored_callback_bound(session: &HelperSession, payload: &Value) -> bool { |
| | | let extension = payload.get("extension"); |
| | | let anchor_id = extension |
| | | .and_then(|value| value.get("streamAnchorId")) |
| | | .and_then(Value::as_str); |
| | | let anchor_base = extension |
| | | .and_then(|value| value.get("streamAnchorServerDeltaMs")) |
| | | .and_then(Value::as_u64); |
| | | let elapsed = extension |
| | | .and_then(|value| value.get("anchorElapsedMs")) |
| | | .and_then(Value::as_u64); |
| | | let delta = payload.get("serverDeltaMs").and_then(Value::as_u64); |
| | | let expected_delta = |
| | | anchor_base.and_then(|base| elapsed.and_then(|value| base.checked_add(value))); |
| | | let expected_nonce_hash = crate::runtime_session_nonce_hash(&session.runtime_session_nonce); |
| | | payload.get("callId").and_then(Value::as_str) == Some(session.call_id.as_str()) |
| | | && payload.get("traceId").and_then(Value::as_str) == session.trace_id.as_deref() |
| | | && payload.get("turnId").and_then(Value::as_str) == session.active_turn_id.as_deref() |
| | | && extension |
| | | .and_then(|value| value.get("streamTimingVersion")) |
| | | .and_then(Value::as_u64) |
| | | == Some(1) |
| | | && anchor_id.is_some_and(|value| (16..=64).contains(&value.len()) && value.is_ascii()) |
| | | && extension |
| | | .and_then(|value| value.get("runtimeSessionNonceHash")) |
| | | .and_then(Value::as_str) |
| | | == Some(expected_nonce_hash.as_str()) |
| | | && extension |
| | | .and_then(|value| value.get("segmentSeq")) |
| | | .and_then(Value::as_u64) |
| | | == Some(1) |
| | | && extension |
| | | .and_then(|value| value.get("streamTimingValidation")) |
| | | .and_then(Value::as_str) |
| | | == Some("bound") |
| | | && elapsed.is_some_and(|value| value <= 5_000) |
| | | && delta == expected_delta |
| | | } |
| | | |
| | | fn post_event_callback(callback: &EventCallbackDispatch) -> Result<u16> { |
| | |
| | | runtime_session_id: String, |
| | | event_callback_url: Option<String>, |
| | | event_callback_token: Option<String>, |
| | | event_callback_sender: Option<mpsc::Sender<EventCallbackDispatch>>, |
| | | status: String, |
| | | bot_participant_joined: bool, |
| | | bot_track_ready: bool, |
| | |
| | | Err(_) => default_value, |
| | | } |
| | | } |
| | | |
| | | #[cfg(test)] |
| | | mod tests { |
| | | use super::{EventCallbackDispatch, deliver_event_callback_with, run_event_callback_worker}; |
| | | use anyhow::Result; |
| | | use serde_json::{Value, json}; |
| | | use std::{cell::RefCell, rc::Rc, sync::mpsc}; |
| | | |
| | | #[test] |
| | | fn same_session_callback_retries_m7_before_terminal() { |
| | | let (sender, receiver) = mpsc::channel(); |
| | | let dispatch = |payload| EventCallbackDispatch { |
| | | url: "http://callback.test/endpoint".to_string(), |
| | | token: "test-token".to_string(), |
| | | call_id: "call-1".to_string(), |
| | | trace_id: Some("trace-1".to_string()), |
| | | runtime_session_nonce: "test-nonce".to_string(), |
| | | payload, |
| | | }; |
| | | sender |
| | | .send(dispatch(json!({ |
| | | "eventName": "bot_reply_first_audio_frame_written", |
| | | "serverDeltaSource": "stream_anchor_monotonic" |
| | | }))) |
| | | .expect("queue m7"); |
| | | sender |
| | | .send(dispatch(json!({"eventName": "turn_completed"}))) |
| | | .expect("queue terminal"); |
| | | drop(sender); |
| | | |
| | | let observed = Rc::new(RefCell::new(Vec::new())); |
| | | let observed_for_worker = observed.clone(); |
| | | run_event_callback_worker(receiver, move |callback| { |
| | | let observed_for_post = observed_for_worker.clone(); |
| | | let mut m7_attempt = 0; |
| | | deliver_event_callback_with(callback, move |dispatch| -> Result<u16> { |
| | | let event_name = dispatch |
| | | .payload |
| | | .get("eventName") |
| | | .and_then(Value::as_str) |
| | | .expect("event name") |
| | | .to_string(); |
| | | observed_for_post.borrow_mut().push(event_name.clone()); |
| | | if event_name == "bot_reply_first_audio_frame_written" && m7_attempt == 0 { |
| | | m7_attempt += 1; |
| | | Ok(500) |
| | | } else { |
| | | Ok(200) |
| | | } |
| | | }); |
| | | }); |
| | | |
| | | assert_eq!( |
| | | vec![ |
| | | "bot_reply_first_audio_frame_written", |
| | | "bot_reply_first_audio_frame_written", |
| | | "turn_completed" |
| | | ], |
| | | *observed.borrow() |
| | | ); |
| | | } |
| | | } |