1use ringo_core::account::{Account, BackendOptions};
16use ringo_core::event::{AppEvent, InviteHeaders, MediaStats};
17use serde::{Deserialize, Serialize};
18use std::io::{self, Read, Write};
19
20pub(crate) const FRAME_CONTROL: u8 = 0;
29pub(crate) const FRAME_AUDIO: u8 = 1;
31
32const MAX_FRAME_LEN: usize = 16 * 1024 * 1024;
34
35pub(crate) fn write_frame<W: Write>(w: &mut W, kind: u8, payload: &[u8]) -> io::Result<()> {
37 if payload.len() > MAX_FRAME_LEN {
38 return Err(io::Error::new(
39 io::ErrorKind::InvalidInput,
40 "frame too large",
41 ));
42 }
43 w.write_all(&[kind])?;
44 w.write_all(&(payload.len() as u32).to_le_bytes())?;
45 w.write_all(payload)?;
46 w.flush()
47}
48
49pub(crate) fn read_frame<R: Read>(r: &mut R) -> io::Result<Option<(u8, Vec<u8>)>> {
53 let mut hdr = [0u8; 5];
54 let mut filled = 0;
57 while filled < hdr.len() {
58 match r.read(&mut hdr[filled..]) {
59 Ok(0) if filled == 0 => return Ok(None), Ok(0) => {
61 return Err(io::Error::new(
62 io::ErrorKind::UnexpectedEof,
63 "EOF in frame header",
64 ));
65 }
66 Ok(n) => filled += n,
67 Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
68 Err(e) => return Err(e),
69 }
70 }
71 let kind = hdr[0];
72 let len = u32::from_le_bytes([hdr[1], hdr[2], hdr[3], hdr[4]]) as usize;
73 if len > MAX_FRAME_LEN {
74 return Err(io::Error::new(
75 io::ErrorKind::InvalidData,
76 "frame too large",
77 ));
78 }
79 let mut payload = vec![0u8; len];
80 r.read_exact(&mut payload)?;
81 Ok(Some((kind, payload)))
82}
83
84pub(crate) fn pcm_to_bytes(samples: &[i16]) -> Vec<u8> {
86 let mut v = Vec::with_capacity(samples.len() * 2);
87 for &s in samples {
88 v.extend_from_slice(&s.to_le_bytes());
89 }
90 v
91}
92
93pub(crate) fn bytes_to_pcm(bytes: &[u8]) -> Vec<i16> {
95 bytes
96 .chunks_exact(2)
97 .map(|c| i16::from_le_bytes([c[0], c[1]]))
98 .collect()
99}
100
101pub(crate) const PROTO_VERSION: u32 = 1;
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
113pub(crate) struct Handshake {
114 pub proto_version: u32,
116 pub config: AgentConfig,
118}
119
120#[derive(Debug, Clone, Default, Serialize, Deserialize)]
127pub struct AgentConfig {
128 pub name: String,
130 pub account: Account,
132 pub options: BackendOptions,
134}
135
136#[derive(Debug, Clone, Serialize, Deserialize)]
140#[serde(tag = "cmd", rename_all = "snake_case")]
141pub enum Command {
142 Register {
143 aor: String,
144 regint: u32,
145 },
146 Dial {
147 number: String,
148 },
149 Hangup,
150 HangupAll,
151 Accept,
152 Hold,
153 Resume,
154 Mute,
155 Dtmf {
156 digit: char,
157 },
158 SwitchLine {
159 line: usize,
160 },
161 Transfer {
162 uri: String,
163 },
164 AttendedTransferStart {
165 uri: String,
166 },
167 AttendedTransferExec,
168 AttendedTransferAbort,
169 AddHeader {
170 key: String,
171 value: String,
172 },
173 RmHeader {
174 key: String,
175 },
176 SetAudioSource {
177 spec: String,
178 },
179 ArmInviteResponse {
180 scode: u16,
181 reason: String,
182 headers: Vec<String>,
183 },
184 DisarmInviteResponse,
185 StartTxAudio {
188 rate: u32,
189 },
190 StartRxAudio,
193 Shutdown,
195}
196
197#[derive(Debug, Clone, Serialize, Deserialize)]
199#[serde(tag = "query", rename_all = "snake_case")]
200pub enum Query {
201 MediaStats,
203 ReceivedDtmf,
205 SaveAudio { prefix: String },
208 CallCount,
210}
211
212#[derive(Debug, Clone, Serialize, Deserialize)]
214pub struct QueryEnvelope {
215 pub id: u64,
216 #[serde(flatten)]
217 pub query: Query,
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
224#[serde(untagged)]
225pub enum ToWorker {
226 Cmd(Command),
227 Query(QueryEnvelope),
228}
229
230#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
234pub struct WireMediaStats {
235 pub rtt_ms: f64,
236 pub jitter_ms: f64,
237 pub rx_lost: i32,
238 pub packet_loss_pct: f64,
239 pub mos: f64,
240}
241
242impl From<MediaStats> for WireMediaStats {
243 fn from(s: MediaStats) -> Self {
244 Self {
245 rtt_ms: s.rtt_ms,
246 jitter_ms: s.jitter_ms,
247 rx_lost: s.rx_lost,
248 packet_loss_pct: s.packet_loss_pct,
249 mos: s.mos,
250 }
251 }
252}
253
254impl From<WireMediaStats> for MediaStats {
255 fn from(s: WireMediaStats) -> Self {
256 Self {
257 rtt_ms: s.rtt_ms,
258 jitter_ms: s.jitter_ms,
259 rx_lost: s.rx_lost,
260 packet_loss_pct: s.packet_loss_pct,
261 mos: s.mos,
262 }
263 }
264}
265
266#[derive(Debug, Clone, Serialize, Deserialize)]
270#[serde(rename_all = "snake_case")]
271pub enum ReplyResult {
272 MediaStats(Option<WireMediaStats>),
273 Dtmf(String),
274 Saved(Vec<String>),
275 CallCount(u32),
276}
277
278#[derive(Debug, Clone, Serialize, Deserialize)]
281pub struct Reply {
282 pub reply: u64,
283 pub result: ReplyResult,
284}
285
286#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct Headers {
289 pub headers: InviteHeaders,
290}
291
292#[derive(Debug, Clone, Serialize, Deserialize)]
296pub struct Ready {
297 pub ready: bool,
298}
299
300#[derive(Debug, Clone, Serialize, Deserialize)]
303pub struct RxAudioStarted {
304 pub rx_audio_rate: u32,
305}
306
307#[derive(Debug, Clone, Serialize, Deserialize)]
312#[serde(untagged)]
313pub enum FromWorker {
314 Ready(Ready),
315 Event(WireEvent),
316 Reply(Reply),
317 Headers(Headers),
318 RxAudioStarted(RxAudioStarted),
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
324#[serde(tag = "event", rename_all = "snake_case")]
325pub enum WireEvent {
326 Registering {
327 account: String,
328 },
329 RegisterOk {
330 account: String,
331 },
332 RegisterFailed {
333 reason: String,
334 },
335 Unregistered {
336 account: String,
337 },
338 CallIncoming {
339 call_id: String,
340 number: String,
341 display_name: Option<String>,
342 },
343 CallOutgoing {
344 call_id: String,
345 number: String,
346 },
347 CallRinging {
348 call_id: String,
349 },
350 CallEstablished {
351 call_id: String,
352 },
353 CallClosed {
354 call_id: String,
355 reason: String,
356 error: bool,
357 },
358 VoicemailStatus {
359 waiting: bool,
360 new_count: u32,
361 },
362 Response {
363 ok: bool,
364 data: String,
365 },
366 Unknown {
367 class: String,
368 type_: String,
369 },
370 BackendConnectFailed {
371 reason: String,
372 },
373}
374
375impl From<&AppEvent> for WireEvent {
376 fn from(e: &AppEvent) -> Self {
377 match e {
378 AppEvent::Registering { account } => Self::Registering {
379 account: account.clone(),
380 },
381 AppEvent::RegisterOk { account } => Self::RegisterOk {
382 account: account.clone(),
383 },
384 AppEvent::RegisterFailed { reason } => Self::RegisterFailed {
385 reason: reason.clone(),
386 },
387 AppEvent::Unregistered { account } => Self::Unregistered {
388 account: account.clone(),
389 },
390 AppEvent::CallIncoming {
391 call_id,
392 number,
393 display_name,
394 } => Self::CallIncoming {
395 call_id: call_id.clone(),
396 number: number.clone(),
397 display_name: display_name.clone(),
398 },
399 AppEvent::CallOutgoing { call_id, number } => Self::CallOutgoing {
400 call_id: call_id.clone(),
401 number: number.clone(),
402 },
403 AppEvent::CallRinging { call_id } => Self::CallRinging {
404 call_id: call_id.clone(),
405 },
406 AppEvent::CallEstablished { call_id } => Self::CallEstablished {
407 call_id: call_id.clone(),
408 },
409 AppEvent::CallClosed {
410 call_id,
411 reason,
412 error,
413 } => Self::CallClosed {
414 call_id: call_id.clone(),
415 reason: reason.clone(),
416 error: *error,
417 },
418 AppEvent::VoicemailStatus { waiting, new_count } => Self::VoicemailStatus {
419 waiting: *waiting,
420 new_count: *new_count,
421 },
422 AppEvent::Response { ok, data } => Self::Response {
423 ok: *ok,
424 data: data.clone(),
425 },
426 AppEvent::Unknown { class, type_ } => Self::Unknown {
427 class: class.clone(),
428 type_: type_.clone(),
429 },
430 AppEvent::BackendConnectFailed { reason } => Self::BackendConnectFailed {
431 reason: reason.clone(),
432 },
433 }
434 }
435}
436
437impl From<WireEvent> for AppEvent {
438 fn from(w: WireEvent) -> Self {
439 match w {
440 WireEvent::Registering { account } => AppEvent::Registering { account },
441 WireEvent::RegisterOk { account } => AppEvent::RegisterOk { account },
442 WireEvent::RegisterFailed { reason } => AppEvent::RegisterFailed { reason },
443 WireEvent::Unregistered { account } => AppEvent::Unregistered { account },
444 WireEvent::CallIncoming {
445 call_id,
446 number,
447 display_name,
448 } => AppEvent::CallIncoming {
449 call_id,
450 number,
451 display_name,
452 },
453 WireEvent::CallOutgoing { call_id, number } => {
454 AppEvent::CallOutgoing { call_id, number }
455 }
456 WireEvent::CallRinging { call_id } => AppEvent::CallRinging { call_id },
457 WireEvent::CallEstablished { call_id } => AppEvent::CallEstablished { call_id },
458 WireEvent::CallClosed {
459 call_id,
460 reason,
461 error,
462 } => AppEvent::CallClosed {
463 call_id,
464 reason,
465 error,
466 },
467 WireEvent::VoicemailStatus { waiting, new_count } => {
468 AppEvent::VoicemailStatus { waiting, new_count }
469 }
470 WireEvent::Response { ok, data } => AppEvent::Response { ok, data },
471 WireEvent::Unknown { class, type_ } => AppEvent::Unknown { class, type_ },
472 WireEvent::BackendConnectFailed { reason } => AppEvent::BackendConnectFailed { reason },
473 }
474 }
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 #[test]
482 fn command_roundtrips_as_to_worker() {
483 let line = serde_json::to_string(&ToWorker::Cmd(Command::Dial {
484 number: "sip:1@example.com".into(),
485 }))
486 .unwrap();
487 assert_eq!(line, r#"{"cmd":"dial","number":"sip:1@example.com"}"#);
488 assert!(matches!(
489 serde_json::from_str::<ToWorker>(&line).unwrap(),
490 ToWorker::Cmd(Command::Dial { .. })
491 ));
492 }
493
494 #[test]
495 fn query_envelope_roundtrips_as_to_worker() {
496 let line = serde_json::to_string(&ToWorker::Query(QueryEnvelope {
497 id: 7,
498 query: Query::SaveAudio {
499 prefix: "rec".into(),
500 },
501 }))
502 .unwrap();
503 let back: ToWorker = serde_json::from_str(&line).unwrap();
504 match back {
505 ToWorker::Query(QueryEnvelope {
506 id,
507 query: Query::SaveAudio { prefix },
508 }) => {
509 assert_eq!((id, prefix.as_str()), (7, "rec"));
510 }
511 _ => panic!("expected save_audio query"),
512 }
513 }
514
515 #[test]
516 fn event_and_reply_disambiguate_as_from_worker() {
517 let ev = serde_json::to_string(&FromWorker::Event(WireEvent::RegisterOk {
518 account: "a".into(),
519 }))
520 .unwrap();
521 assert!(matches!(
522 serde_json::from_str::<FromWorker>(&ev).unwrap(),
523 FromWorker::Event(WireEvent::RegisterOk { .. })
524 ));
525
526 let rep = serde_json::to_string(&FromWorker::Reply(Reply {
527 reply: 7,
528 result: ReplyResult::CallCount(2),
529 }))
530 .unwrap();
531 match serde_json::from_str::<FromWorker>(&rep).unwrap() {
532 FromWorker::Reply(Reply {
533 reply,
534 result: ReplyResult::CallCount(n),
535 }) => {
536 assert_eq!((reply, n), (7, 2));
537 }
538 _ => panic!("expected call_count reply"),
539 }
540 }
541
542 #[test]
543 fn app_event_mirrors_both_ways() {
544 let ev = AppEvent::CallIncoming {
545 call_id: "abc".into(),
546 number: "sip:1@x".into(),
547 display_name: Some("Bob".into()),
548 };
549 let line = serde_json::to_string(&WireEvent::from(&ev)).unwrap();
550 let back: AppEvent = serde_json::from_str::<WireEvent>(&line).unwrap().into();
551 assert!(matches!(back, AppEvent::CallIncoming { .. }));
552 }
553
554 #[test]
555 fn ready_disambiguates_from_an_event() {
556 let ready = serde_json::to_string(&FromWorker::Ready(Ready { ready: true })).unwrap();
557 assert!(matches!(
558 serde_json::from_str::<FromWorker>(&ready).unwrap(),
559 FromWorker::Ready(Ready { ready: true })
560 ));
561 let ev = serde_json::to_string(&FromWorker::Event(WireEvent::RegisterOk {
563 account: "a".into(),
564 }))
565 .unwrap();
566 assert!(matches!(
567 serde_json::from_str::<FromWorker>(&ev).unwrap(),
568 FromWorker::Event(_)
569 ));
570 }
571
572 #[test]
573 fn handshake_carries_version_and_config() {
574 let mut cfg = AgentConfig {
575 name: "A".into(),
576 ..Default::default()
577 };
578 cfg.account.username = "alice".into();
579 let hs = Handshake {
580 proto_version: PROTO_VERSION,
581 config: cfg,
582 };
583 let line = serde_json::to_string(&hs).unwrap();
584 let back: Handshake = serde_json::from_str(&line).unwrap();
585 assert_eq!(back.proto_version, PROTO_VERSION);
586 assert_eq!(back.config.account.username, "alice");
587 }
588
589 #[test]
590 fn agent_config_roundtrips_with_embedded_account() {
591 let mut cfg = AgentConfig {
592 name: "A".into(),
593 ..Default::default()
594 };
595 cfg.account.username = "alice".into();
596 cfg.account.catchall = true;
597 cfg.options.audio_driver = Some("aubridge".into());
598 let line = serde_json::to_string(&cfg).unwrap();
599 let back: AgentConfig = serde_json::from_str(&line).unwrap();
600 assert_eq!(back.name, "A");
601 assert_eq!(back.account.username, "alice");
602 assert!(back.account.catchall);
603 assert_eq!(back.options.audio_driver.as_deref(), Some("aubridge"));
604 }
605
606 #[test]
607 fn frames_roundtrip_control_then_audio() {
608 let mut buf: Vec<u8> = Vec::new();
609 write_frame(&mut buf, FRAME_CONTROL, b"{\"cmd\":\"accept\"}").unwrap();
610 write_frame(&mut buf, FRAME_AUDIO, &pcm_to_bytes(&[1, -2, 3])).unwrap();
611 let mut r = &buf[..];
612 let (k1, p1) = read_frame(&mut r).unwrap().unwrap();
613 assert_eq!(k1, FRAME_CONTROL);
614 assert_eq!(p1, b"{\"cmd\":\"accept\"}");
615 let (k2, p2) = read_frame(&mut r).unwrap().unwrap();
616 assert_eq!(k2, FRAME_AUDIO);
617 assert_eq!(bytes_to_pcm(&p2), vec![1, -2, 3]);
618 assert!(read_frame(&mut r).unwrap().is_none()); }
620
621 #[test]
622 fn audio_frame_can_contain_newline_bytes() {
623 let samples = vec![0x0A0Ai16, 0x000A, -1];
625 let mut buf = Vec::new();
626 write_frame(&mut buf, FRAME_AUDIO, &pcm_to_bytes(&samples)).unwrap();
627 let (_k, p) = read_frame(&mut &buf[..]).unwrap().unwrap();
628 assert_eq!(bytes_to_pcm(&p), samples);
629 }
630
631 #[test]
632 fn rx_audio_started_disambiguates_from_event_and_reply() {
633 let started = serde_json::to_string(&FromWorker::RxAudioStarted(RxAudioStarted {
634 rx_audio_rate: 8000,
635 }))
636 .unwrap();
637 assert!(matches!(
638 serde_json::from_str::<FromWorker>(&started).unwrap(),
639 FromWorker::RxAudioStarted(RxAudioStarted {
640 rx_audio_rate: 8000
641 })
642 ));
643 let ev = serde_json::to_string(&FromWorker::Event(WireEvent::RegisterOk {
645 account: "a".into(),
646 }))
647 .unwrap();
648 let rep = serde_json::to_string(&FromWorker::Reply(Reply {
649 reply: 1,
650 result: ReplyResult::CallCount(0),
651 }))
652 .unwrap();
653 assert!(matches!(
654 serde_json::from_str::<FromWorker>(&ev).unwrap(),
655 FromWorker::Event(_)
656 ));
657 assert!(matches!(
658 serde_json::from_str::<FromWorker>(&rep).unwrap(),
659 FromWorker::Reply(_)
660 ));
661 }
662
663 #[test]
664 fn read_frame_distinguishes_clean_eof_from_torn_header() {
665 assert!(read_frame(&mut &b""[..]).unwrap().is_none());
667 let err = read_frame(&mut &[FRAME_CONTROL, 0x01][..]).unwrap_err();
669 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
670 }
671
672 #[test]
673 fn read_frame_rejects_oversized_length() {
674 let mut buf = vec![FRAME_AUDIO];
676 buf.extend_from_slice(&(MAX_FRAME_LEN as u32 + 1).to_le_bytes());
677 let err = read_frame(&mut &buf[..]).unwrap_err();
678 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
679 }
680
681 #[test]
682 fn read_frame_errors_on_truncated_payload() {
683 let mut buf = vec![FRAME_AUDIO];
685 buf.extend_from_slice(&4u32.to_le_bytes()); buf.extend_from_slice(&[1, 2]); let err = read_frame(&mut &buf[..]).unwrap_err();
688 assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof);
689 }
690
691 #[test]
692 fn audio_commands_disambiguate_as_to_worker_cmd() {
693 for cmd in [Command::StartRxAudio, Command::StartTxAudio { rate: 8000 }] {
695 let line = serde_json::to_string(&ToWorker::Cmd(cmd)).unwrap();
696 assert!(
697 matches!(
698 serde_json::from_str::<ToWorker>(&line).unwrap(),
699 ToWorker::Cmd(_)
700 ),
701 "expected Cmd for {line}"
702 );
703 }
704 }
705}