| | |
| | | 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) |
| | |
| | | if let Some(value) = &runtime.asr_stream_url { |
| | | command.env("CV_RUNTIME_ASR_STREAM_URL", value); |
| | | } |
| | | if let Some(value) = runtime.asr_realtime_enabled { |
| | | command.env("CV_RUNTIME_ASR_REALTIME_ENABLED", value.to_string()); |
| | | } |
| | | if let Some(value) = &runtime.asr_realtime_url { |
| | | command.env("CV_RUNTIME_ASR_REALTIME_URL", value); |
| | | } |
| | | if let Some(value) = runtime.asr_realtime_chunk_duration_ms { |
| | | command.env( |
| | | "CV_RUNTIME_ASR_REALTIME_CHUNK_DURATION_MS", |
| | | value.to_string(), |
| | | ); |
| | | } |
| | | if let Some(true) = runtime.audio_debug_dump_enabled { |
| | | if let Some(value) = &config.audio_debug_dump_dir { |
| | | command.env("CV_AUDIO_DEBUG_DUMP_DIR", value); |
| | |
| | | continue; |
| | | }; |
| | | println!("{line}"); |
| | | if let Ok(value) = serde_json::from_str::<Value>(&line) { |
| | | if let Some(value) = project_worker_stdout_event(&call_id, &line) { |
| | | apply_worker_event(&call_id, &state, &value); |
| | | } |
| | | } |
| | | }); |
| | | } |
| | | |
| | | fn project_worker_stdout_event(call_id: &str, line: &str) -> Option<Value> { |
| | | let value = serde_json::from_str::<Value>(line).ok()?; |
| | | (value.get("type").and_then(Value::as_str) == Some("cv_activity") |
| | | && value.get("callId").and_then(Value::as_str) == Some(call_id) |
| | | && value.get("eventName").and_then(Value::as_str).is_some()) |
| | | .then_some(value) |
| | | } |
| | | |
| | | fn apply_worker_event(call_id: &str, state: &Arc<ServiceState>, value: &Value) { |
| | |
| | | .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 || { |
| | | let event_name = callback |
| | | .payload |
| | | .get("eventName") |
| | | .and_then(Value::as_str) |
| | | .unwrap_or("worker_event") |
| | | .to_string(); |
| | | match post_event_callback(&callback) { |
| | | 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(); |
| | | 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, |
| | |
| | | audio_debug_dump_enabled: Option<bool>, |
| | | asr_streaming_enabled: Option<bool>, |
| | | asr_stream_url: Option<String>, |
| | | asr_realtime_enabled: Option<bool>, |
| | | asr_realtime_url: Option<String>, |
| | | asr_realtime_chunk_duration_ms: Option<u64>, |
| | | } |
| | | |
| | | #[derive(Default, Deserialize)] |
| | |
| | | Err(_) => default_value, |
| | | } |
| | | } |
| | | |
| | | #[cfg(test)] |
| | | mod tests { |
| | | use super::{ |
| | | EventCallbackDispatch, deliver_event_callback_with, project_worker_stdout_event, |
| | | run_event_callback_worker, |
| | | }; |
| | | use crate::{ |
| | | CONTROLLED_FIXTURE_GENERATION, CONTROLLED_FIXTURE_PROBE_TTL, |
| | | ControlledFixtureVisibilityEvidence, PendingControlledFixtureProbe, |
| | | controlled_fixture_probe_event, controlled_fixture_visibility_event, |
| | | }; |
| | | use anyhow::Result; |
| | | use serde_json::{Value, json}; |
| | | use std::{cell::RefCell, rc::Rc, sync::mpsc}; |
| | | |
| | | #[test] |
| | | fn controlled_fixture_activity_requires_production_stdout_envelope() { |
| | | let call_id = "runtime-call"; |
| | | let runtime_trace_id = "runtime-trace"; |
| | | let trace_hash = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; |
| | | let valid = controlled_fixture_probe_event( |
| | | call_id, |
| | | runtime_trace_id, |
| | | "ack_publish_completed", |
| | | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", |
| | | trace_hash, |
| | | 1, |
| | | "fixture-01", |
| | | false, |
| | | Some("rejected"), |
| | | Some("wrong_source"), |
| | | ); |
| | | let projected = project_worker_stdout_event(call_id, &valid.to_string()) |
| | | .expect("valid activity must enter the production stdout projection"); |
| | | assert_eq!(projected["eventName"], "controlled_fixture_attribute_probe"); |
| | | assert_eq!(projected["extension"]["trace_id_hash"], trace_hash); |
| | | assert_eq!(projected["extension"]["reject_reason"], "wrong_source"); |
| | | |
| | | for invalid in [ |
| | | json!({ |
| | | "event": "controlled_fixture_attribute_probe", |
| | | "stage": "ack_publish_completed", |
| | | "observed": false, |
| | | "ack_result": "rejected", |
| | | "reject_reason": "wrong_source", |
| | | "call_id_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", |
| | | "trace_id_hash": trace_hash, |
| | | "generation": 1, |
| | | "sequence_hash": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" |
| | | }), |
| | | json!({"type": "not_activity", "callId": call_id, "eventName": "controlled_fixture_attribute_probe"}), |
| | | json!({"type": "cv_activity", "callId": call_id}), |
| | | json!({"type": "cv_activity", "callId": "wrong-call", "eventName": "controlled_fixture_attribute_probe"}), |
| | | ] { |
| | | assert!(project_worker_stdout_event(call_id, &invalid.to_string()).is_none()); |
| | | } |
| | | |
| | | let received_at = std::time::Instant::now(); |
| | | let visibility = controlled_fixture_visibility_event( |
| | | call_id, |
| | | runtime_trace_id, |
| | | &PendingControlledFixtureProbe { |
| | | sender: livekit::prelude::ParticipantIdentity("user-1".to_string()), |
| | | call_id_hash: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" |
| | | .to_string(), |
| | | call_trace_id_hash: trace_hash.to_string(), |
| | | generation: CONTROLLED_FIXTURE_GENERATION, |
| | | sequence: "fixture-01".to_string(), |
| | | received_at, |
| | | expires_at: received_at + CONTROLLED_FIXTURE_PROBE_TTL, |
| | | }, |
| | | &ControlledFixtureVisibilityEvidence { |
| | | first_visible_bucket: "250_500ms", |
| | | visibility_source: "participant_attributes_poll", |
| | | visibility_result: "held_visible", |
| | | binding_matched: true, |
| | | }, |
| | | ); |
| | | let projected = project_worker_stdout_event(call_id, &visibility.to_string()) |
| | | .expect("post-expiry evidence must enter the production stdout projection"); |
| | | assert_eq!(projected["extension"]["first_visible_bucket"], "250_500ms"); |
| | | assert_eq!(projected["extension"]["binding_matched"], true); |
| | | assert_eq!(projected["extension"]["visibility_result"], "held_visible"); |
| | | } |
| | | |
| | | #[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() |
| | | ); |
| | | } |
| | | } |