Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/realtime-webrtc/BUILD.bazel
Normal file
6
akode-rs/realtime-webrtc/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "realtime-webrtc",
|
||||
crate_name = "akode_realtime_webrtc",
|
||||
)
|
||||
30
akode-rs/realtime-webrtc/Cargo.toml
Normal file
30
akode-rs/realtime-webrtc/Cargo.toml
Normal file
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "akode-realtime-webrtc"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-build-info = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
akode-install-context = { workspace = true }
|
||||
akode-utils-pty = { workspace = true }
|
||||
futures = { workspace = true, features = ["std"] }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync", "time"] }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
akode-utils-cargo-bin = { workspace = true }
|
||||
ctor = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dev-dependencies]
|
||||
libc = { workspace = true }
|
||||
341
akode-rs/realtime-webrtc/src/client.rs
Normal file
341
akode-rs/realtime-webrtc/src/client.rs
Normal file
@@ -0,0 +1,341 @@
|
||||
//! Resolve only the installed helper and retain the existing owned-process cleanup guard.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::OsString;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_install_context::CodexPackageLayout;
|
||||
use akode_utils_pty::ProcessHandle;
|
||||
use akode_utils_pty::SpawnedProcess;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::AudioDevice;
|
||||
use crate::AudioDeviceKind;
|
||||
use crate::AudioDeviceSelection;
|
||||
use crate::HelperExitStage;
|
||||
use crate::Message;
|
||||
use crate::encode_frame;
|
||||
use crate::message_reader::MessageReader;
|
||||
|
||||
const DEADLINE: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
const RUNTIME_INITIALIZATION_DEADLINE: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
|
||||
/// Startup failures eligible for recovery remain distinct from all other failures.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ConnectionError {
|
||||
NegotiationTimedOut,
|
||||
Failed,
|
||||
HelperStartup,
|
||||
RuntimeInitialization,
|
||||
Transport,
|
||||
AudioDevices,
|
||||
AudioControls,
|
||||
AudioSession,
|
||||
Shutdown,
|
||||
}
|
||||
impl std::fmt::Display for ConnectionError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::NegotiationTimedOut => "voice negotiation timed out",
|
||||
Self::Failed => "voice connection failed",
|
||||
Self::HelperStartup => "voice helper could not start",
|
||||
Self::RuntimeInitialization => "voice audio runtime could not initialize",
|
||||
Self::Transport => "voice transport could not connect",
|
||||
Self::AudioDevices => {
|
||||
"voice audio devices could not open; check microphone and speaker setup"
|
||||
}
|
||||
Self::AudioControls => "voice audio controls failed",
|
||||
Self::AudioSession => "voice audio session stopped unexpectedly",
|
||||
Self::Shutdown => "voice helper could not shut down cleanly",
|
||||
})
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ConnectionError {}
|
||||
|
||||
/// Owns one helper. Dropping it terminates the process and leaves its waiter to reap it.
|
||||
/// A successful handshake establishes compatibility only, not an active audio session.
|
||||
pub struct VoiceHost {
|
||||
process: ProcessHandle,
|
||||
output: MessageReader,
|
||||
exit: oneshot::Receiver<i32>,
|
||||
observed_exit: Option<Option<i32>>,
|
||||
}
|
||||
|
||||
impl VoiceHost {
|
||||
/// Open local devices only after answer negotiation. They initially remain muted/suppressed.
|
||||
pub async fn open_devices(mut self, selection: AudioDeviceSelection) -> Result<Self> {
|
||||
self.exchange(
|
||||
Message::OpenDevices { selection },
|
||||
Message::DevicesOpened {},
|
||||
DEADLINE,
|
||||
)
|
||||
.await?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Enumerate local devices without opening streams.
|
||||
pub async fn list_devices(&mut self, kind: AudioDeviceKind) -> Result<Vec<AudioDevice>> {
|
||||
match self
|
||||
.request(Message::ListDevices { kind }, DEADLINE)
|
||||
.await?
|
||||
{
|
||||
Message::DeviceList { devices } => Ok(devices),
|
||||
_ => anyhow::bail!("unexpected voice helper response"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Acknowledgement follows invalidation of the helper's previous capture/render generations.
|
||||
pub async fn set_audio_controls(&mut self, controls: crate::AudioControls) -> Result<()> {
|
||||
self.exchange(
|
||||
Message::SetAudioControls { controls },
|
||||
Message::AudioControlsApplied {},
|
||||
DEADLINE,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Enqueue startup controls synchronously so the facade can order them with setters.
|
||||
/// The returned future owns only the acknowledgement wait, never the facade control lock.
|
||||
pub(crate) fn begin_audio_controls(
|
||||
&mut self,
|
||||
controls: crate::AudioControls,
|
||||
) -> Result<impl std::future::Future<Output = Result<()>> + '_> {
|
||||
self.process
|
||||
.writer_sender()
|
||||
.try_send(encode_frame(&Message::SetAudioControls { controls })?)
|
||||
.map_err(|_| anyhow::anyhow!("voice helper input unavailable"))?;
|
||||
let deadline = tokio::time::Instant::now() + DEADLINE;
|
||||
Ok(async move {
|
||||
let response = tokio::time::timeout_at(deadline, self.next_response()).await??;
|
||||
ensure!(
|
||||
response == Message::AudioControlsApplied {},
|
||||
"unexpected voice helper response"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Consume peaks and detect helper loss even when neither device is producing audio.
|
||||
pub async fn inspect_audio(&mut self) -> Result<crate::AudioState> {
|
||||
let response = self.request(Message::InspectAudio {}, DEADLINE).await?;
|
||||
let Message::AudioState { state } = response else {
|
||||
anyhow::bail!("unexpected voice helper response");
|
||||
};
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
/// Gather an offer in the helper. This establishes neither connectivity nor audio readiness.
|
||||
pub async fn start_transport(mut self) -> Result<(Self, crate::SessionDescription)> {
|
||||
let response = self
|
||||
.request(Message::StartTransport {}, Duration::from_secs(/*secs*/ 20))
|
||||
.await?;
|
||||
let Message::Offer { sdp } = response else {
|
||||
anyhow::bail!("unexpected voice helper response");
|
||||
};
|
||||
Ok((self, sdp))
|
||||
}
|
||||
|
||||
/// Return only when the peer's ordered event channel has opened.
|
||||
pub async fn apply_answer(mut self, sdp: crate::SessionDescription) -> Result<Self> {
|
||||
let response = self
|
||||
.request(
|
||||
Message::ApplyAnswer { sdp },
|
||||
Duration::from_secs(/*secs*/ 20),
|
||||
)
|
||||
.await?;
|
||||
if response == (Message::TransportTimedOut {}) {
|
||||
self.process.terminate();
|
||||
// A lost exit notification or failed cleanup is not retryable.
|
||||
timeout(DEADLINE, &mut self.exit).await??;
|
||||
return Err(ConnectionError::NegotiationTimedOut.into());
|
||||
}
|
||||
ensure!(
|
||||
response == Message::TransportReady {},
|
||||
"unexpected voice helper response"
|
||||
);
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Initialize the packaged native runtime without opening devices or starting a session.
|
||||
pub async fn initialize_runtime(mut self) -> Result<Self> {
|
||||
self.exchange(
|
||||
Message::InitializeRuntime {},
|
||||
Message::RuntimeReady {},
|
||||
RUNTIME_INITIALIZATION_DEADLINE,
|
||||
)
|
||||
.await?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub async fn connect(package: &CodexPackageLayout, build_commit: &str) -> Result<Self> {
|
||||
let root = package.package_dir.as_path().canonicalize()?;
|
||||
let name = if cfg!(windows) {
|
||||
"akode-voice-host.exe"
|
||||
} else {
|
||||
"akode-voice-host"
|
||||
};
|
||||
let path = root.join("akode-resources/voice/bin").join(name);
|
||||
ensure!(
|
||||
path.canonicalize()? == path,
|
||||
"voice helper must be inside the physical package"
|
||||
);
|
||||
let environment = child_environment(std::env::vars_os());
|
||||
#[cfg(target_os = "linux")]
|
||||
let environment = {
|
||||
let mut environment = environment;
|
||||
if let Some(directory) =
|
||||
crate::linux_alsa::plugin_directory(crate::linux_alsa::PLUGIN_DIRECTORIES)
|
||||
{
|
||||
environment.insert("ALSA_PLUGIN_DIR".to_owned(), directory.to_owned());
|
||||
}
|
||||
environment
|
||||
};
|
||||
let SpawnedProcess {
|
||||
session,
|
||||
stdout_rx,
|
||||
stderr_rx,
|
||||
exit_rx,
|
||||
} = akode_utils_pty::spawn_pipe_process(
|
||||
&path,
|
||||
&[],
|
||||
&root,
|
||||
&environment,
|
||||
/*arg0*/ &None,
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
drop(stderr_rx); // Drain and discard diagnostics rather than logging untyped child output.
|
||||
let mut host = Self {
|
||||
process: session,
|
||||
output: MessageReader::new(stdout_rx),
|
||||
exit: exit_rx,
|
||||
observed_exit: None,
|
||||
};
|
||||
host.exchange(
|
||||
Message::Hello {
|
||||
protocol: 1,
|
||||
build_commit: build_commit.to_owned(),
|
||||
},
|
||||
Message::Ready {},
|
||||
// Startup-linked native libraries load before the helper can acknowledge Hello.
|
||||
RUNTIME_INITIALIZATION_DEADLINE,
|
||||
)
|
||||
.await?;
|
||||
Ok(host)
|
||||
}
|
||||
|
||||
pub async fn close(mut self) -> Result<()> {
|
||||
let result = self
|
||||
.exchange(Message::Close {}, Message::Closed {}, DEADLINE)
|
||||
.await;
|
||||
if result.is_err() {
|
||||
self.process.terminate();
|
||||
}
|
||||
let code = match self.observed_exit {
|
||||
Some(Some(code)) => code,
|
||||
Some(None) => anyhow::bail!("voice helper exit status unavailable"),
|
||||
None => timeout(DEADLINE, &mut self.exit).await??,
|
||||
};
|
||||
result?;
|
||||
ensure!(code == 0, "voice helper failed during shutdown");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn exchange(
|
||||
&mut self,
|
||||
request: Message,
|
||||
expected: Message,
|
||||
deadline: Duration,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
self.request(request, deadline).await? == expected,
|
||||
"unexpected voice helper response"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn request(&mut self, request: Message, deadline: Duration) -> Result<Message> {
|
||||
timeout(deadline, async {
|
||||
self.process
|
||||
.writer_sender()
|
||||
.send(encode_frame(&request)?)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("voice helper input closed"))?;
|
||||
self.next_response().await
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
async fn next_response(&mut self) -> Result<Message> {
|
||||
match self.output.next().await {
|
||||
Ok(response) => Ok(response),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => {
|
||||
// The helper can exit just after closing stdout. Wait briefly for its
|
||||
// status; never log its untyped stderr, SDP, or native error text.
|
||||
let exit_code = match self.observed_exit {
|
||||
Some(status) => status,
|
||||
None => {
|
||||
match timeout(Duration::from_millis(/*millis*/ 250), &mut self.exit).await {
|
||||
Ok(status) => {
|
||||
let status = status.ok();
|
||||
self.observed_exit = Some(status);
|
||||
status
|
||||
}
|
||||
Err(_) => None,
|
||||
}
|
||||
}
|
||||
};
|
||||
let phase = exit_code.and_then(HelperExitStage::from_code);
|
||||
tracing::warn!(?phase, ?exit_code, "voice helper output closed");
|
||||
Err(error.into())
|
||||
}
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn child_environment(vars: impl Iterator<Item = (OsString, OsString)>) -> HashMap<String, String> {
|
||||
vars.filter_map(|(key, value)| {
|
||||
let key = key.into_string().ok()?;
|
||||
matches!(
|
||||
key.to_ascii_uppercase().as_str(),
|
||||
"SYSTEMROOT"
|
||||
| "WINDIR"
|
||||
| "HOME"
|
||||
| "USERPROFILE"
|
||||
| "LOCALAPPDATA"
|
||||
| "APPDATA"
|
||||
| "TEMP"
|
||||
| "TMP"
|
||||
| "TMPDIR"
|
||||
| "XDG_RUNTIME_DIR"
|
||||
| "PULSE_SERVER"
|
||||
| "PULSE_COOKIE"
|
||||
| "PIPEWIRE_REMOTE"
|
||||
| "DBUS_SESSION_BUS_ADDRESS"
|
||||
| "HTTP_PROXY"
|
||||
| "HTTPS_PROXY"
|
||||
| "ALL_PROXY"
|
||||
| "NO_PROXY"
|
||||
| "SSL_CERT_FILE"
|
||||
| "SSL_CERT_DIR"
|
||||
| "REQUESTS_CA_BUNDLE"
|
||||
| "CURL_CA_BUNDLE"
|
||||
)
|
||||
.then(|| Some((key, value.into_string().ok()?)))
|
||||
.flatten()
|
||||
})
|
||||
.chain(
|
||||
crate::RUNTIME_ENVIRONMENT
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.to_owned(), value.to_owned())),
|
||||
)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "client_tests.rs"]
|
||||
mod tests;
|
||||
144
akode-rs/realtime-webrtc/src/client_tests.rs
Normal file
144
akode-rs/realtime-webrtc/src/client_tests.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
//! Child environment admission excludes loader hooks, plugin search paths, and app credentials.
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::child_environment;
|
||||
|
||||
#[test]
|
||||
fn forwards_only_explicit_device_network_and_os_inputs() {
|
||||
let input = [
|
||||
("SystemRoot", "C:\\Windows"),
|
||||
("https_proxy", "http://proxy"),
|
||||
("HOME", "/home/user"),
|
||||
("LD_PRELOAD", "loader"),
|
||||
("DYLD_INSERT_LIBRARIES", "loader"),
|
||||
("PATH", "project"),
|
||||
("GST_PLUGIN_PATH", "plugins"),
|
||||
("ALSA_PLUGIN_DIR", "untrusted-alsa-plugins"),
|
||||
("GST_REGISTRY", "untrusted-registry"),
|
||||
("GST_REGISTRY_FORK", "yes"),
|
||||
("OPENAI_API_KEY", "secret"),
|
||||
];
|
||||
assert_eq!(
|
||||
child_environment(
|
||||
input
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.into(), value.into()))
|
||||
),
|
||||
input[..3]
|
||||
.iter()
|
||||
.map(|(key, value)| (key.to_string(), value.to_string()))
|
||||
.chain(crate::RUNTIME_ENVIRONMENT.map(|(key, value)| (key.into(), value.into())))
|
||||
.collect()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn cancelling_initialization_terminates_the_owned_helper() -> anyhow::Result<()> {
|
||||
let spawned = akode_utils_pty::spawn_pipe_process(
|
||||
std::path::Path::new("/bin/sleep"),
|
||||
&["30".to_owned()],
|
||||
std::path::Path::new("/"),
|
||||
&child_environment(std::iter::empty()),
|
||||
/*arg0*/ &None,
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
drop(spawned.stderr_rx);
|
||||
let (_, unused_exit) = tokio::sync::oneshot::channel();
|
||||
let host = super::VoiceHost {
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(spawned.stdout_rx),
|
||||
exit: unused_exit,
|
||||
observed_exit: None,
|
||||
};
|
||||
let mut initialization = Box::pin(host.initialize_runtime());
|
||||
std::future::poll_fn(|context| {
|
||||
assert!(std::future::Future::poll(initialization.as_mut(), context).is_pending());
|
||||
std::task::Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
drop(initialization);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 1), spawned.exit_rx).await??;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn negotiation_timeout_waits_for_helper_exit_before_allowing_retry() -> anyhow::Result<()> {
|
||||
let spawned = akode_utils_pty::spawn_pipe_process(
|
||||
std::path::Path::new("/bin/sleep"),
|
||||
&["30".to_owned()],
|
||||
std::path::Path::new("/"),
|
||||
&child_environment(std::iter::empty()),
|
||||
/*arg0*/ &None,
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
let (output, receiver) = tokio::sync::mpsc::channel(/*buffer*/ 1);
|
||||
output
|
||||
.send(crate::encode_frame(&crate::Message::TransportTimedOut {})?)
|
||||
.await?;
|
||||
let (reaped, exit) = tokio::sync::oneshot::channel();
|
||||
let host = super::VoiceHost {
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(receiver),
|
||||
exit,
|
||||
observed_exit: None,
|
||||
};
|
||||
let answer = crate::SessionDescription::try_from("synthetic-answer".to_owned()).unwrap();
|
||||
let mut connection = Box::pin(host.apply_answer(answer));
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(std::future::Future::poll(connection.as_mut(), cx).is_pending());
|
||||
std::task::Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
let code =
|
||||
tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 1), spawned.exit_rx).await??;
|
||||
// The process has exited, but the explicit reaping acknowledgement is still required.
|
||||
std::future::poll_fn(|cx| {
|
||||
assert!(std::future::Future::poll(connection.as_mut(), cx).is_pending());
|
||||
std::task::Poll::Ready(())
|
||||
})
|
||||
.await;
|
||||
reaped.send(code).unwrap();
|
||||
let error = connection
|
||||
.await
|
||||
.err()
|
||||
.expect("timeout must not return a connected helper");
|
||||
assert_eq!(
|
||||
error.downcast_ref::<crate::ConnectionError>(),
|
||||
Some(&crate::ConnectionError::NegotiationTimedOut)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn close_after_output_eof_reuses_observed_exit() -> anyhow::Result<()> {
|
||||
let spawned = akode_utils_pty::spawn_pipe_process(
|
||||
std::path::Path::new("/bin/sleep"),
|
||||
&["30".to_owned()],
|
||||
std::path::Path::new("/"),
|
||||
&child_environment(std::iter::empty()),
|
||||
/*arg0*/ &None,
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
let (output, receiver) = tokio::sync::mpsc::channel(/*buffer*/ 1);
|
||||
drop(output);
|
||||
let (reaped, exit) = tokio::sync::oneshot::channel();
|
||||
let exit_code = crate::HelperExitStage::AudioService.code();
|
||||
reaped.send(exit_code).unwrap();
|
||||
let mut host = super::VoiceHost {
|
||||
process: spawned.session,
|
||||
output: crate::message_reader::MessageReader::new(receiver),
|
||||
exit,
|
||||
observed_exit: None,
|
||||
};
|
||||
assert!(host.next_response().await.is_err());
|
||||
assert_eq!(host.observed_exit, Some(Some(exit_code)));
|
||||
assert!(host.close().await.is_err());
|
||||
Ok(())
|
||||
}
|
||||
55
akode-rs/realtime-webrtc/src/helper_exit.rs
Normal file
55
akode-rs/realtime-webrtc/src/helper_exit.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
//! Fixed helper exit phases for safe diagnostics when its framed output closes.
|
||||
//! The same-build handshake keeps these codes aligned between parent and helper.
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[repr(i32)]
|
||||
pub enum HelperExitStage {
|
||||
ControlRead = 20,
|
||||
ControlQueue = 21,
|
||||
ParentGone = 22,
|
||||
Runtime = 23,
|
||||
Transport = 24,
|
||||
OpenDevices = 25,
|
||||
AudioIngress = 26,
|
||||
AudioService = 27,
|
||||
InspectAudio = 28,
|
||||
AudioControls = 29,
|
||||
Reply = 30,
|
||||
Shutdown = 31,
|
||||
ControlSequence = 32,
|
||||
Playout = 33,
|
||||
Render = 35,
|
||||
Capture = 36,
|
||||
Device = 37,
|
||||
Send = 39,
|
||||
}
|
||||
|
||||
impl HelperExitStage {
|
||||
pub fn code(self) -> i32 {
|
||||
self as i32
|
||||
}
|
||||
|
||||
pub fn from_code(code: i32) -> Option<Self> {
|
||||
Some(match code {
|
||||
20 => Self::ControlRead,
|
||||
21 => Self::ControlQueue,
|
||||
22 => Self::ParentGone,
|
||||
23 => Self::Runtime,
|
||||
24 => Self::Transport,
|
||||
25 => Self::OpenDevices,
|
||||
26 => Self::AudioIngress,
|
||||
27 => Self::AudioService,
|
||||
28 => Self::InspectAudio,
|
||||
29 => Self::AudioControls,
|
||||
30 => Self::Reply,
|
||||
31 => Self::Shutdown,
|
||||
32 => Self::ControlSequence,
|
||||
33 => Self::Playout,
|
||||
35 => Self::Render,
|
||||
36 => Self::Capture,
|
||||
37 => Self::Device,
|
||||
39 => Self::Send,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
26
akode-rs/realtime-webrtc/src/lib.rs
Normal file
26
akode-rs/realtime-webrtc/src/lib.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
mod client;
|
||||
mod helper_exit;
|
||||
#[cfg(any(target_os = "linux", test))]
|
||||
mod linux_alsa;
|
||||
mod message_reader;
|
||||
mod protocol;
|
||||
mod session;
|
||||
|
||||
pub use client::ConnectionError;
|
||||
pub use client::VoiceHost;
|
||||
pub use helper_exit::HelperExitStage;
|
||||
pub use protocol::AudioControls;
|
||||
pub use protocol::AudioDevice;
|
||||
pub use protocol::AudioDeviceKind;
|
||||
pub use protocol::AudioDeviceSelection;
|
||||
pub use protocol::AudioState;
|
||||
pub use protocol::MAX_FRAME_BYTES;
|
||||
pub use protocol::Message;
|
||||
pub use protocol::RUNTIME_ENVIRONMENT;
|
||||
pub use protocol::SessionDescription;
|
||||
pub use protocol::decode_frame;
|
||||
pub use protocol::encode_frame;
|
||||
pub use protocol::read_message;
|
||||
pub use session::RealtimeWebrtcSession;
|
||||
pub use session::RealtimeWebrtcSessionHandle;
|
||||
pub use session::StartedRealtimeWebrtcSession;
|
||||
28
akode-rs/realtime-webrtc/src/linux_alsa.rs
Normal file
28
akode-rs/realtime-webrtc/src/linux_alsa.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Locate system ALSA plugins for the statically linked Linux voice helper.
|
||||
//!
|
||||
//! Bazel's ALSA defaults to /usr/lib/alsa-lib. Distribution plugins may instead
|
||||
//! live in a multiarch or lib64 directory. Only fixed system paths are admitted;
|
||||
//! caller-provided plugin directories and loader search paths remain excluded.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) const PLUGIN_DIRECTORIES: &[&str] = &[
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
"/usr/lib/x86_64-linux-gnu/alsa-lib",
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
"/usr/lib/aarch64-linux-gnu/alsa-lib",
|
||||
"/usr/lib64/alsa-lib",
|
||||
"/usr/lib/alsa-lib",
|
||||
];
|
||||
|
||||
pub(crate) fn plugin_directory<'a>(candidates: &[&'a str]) -> Option<&'a str> {
|
||||
candidates
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|path| Path::new(path).is_dir())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "linux_alsa_tests.rs"]
|
||||
mod tests;
|
||||
38
akode-rs/realtime-webrtc/src/linux_alsa_tests.rs
Normal file
38
akode-rs/realtime-webrtc/src/linux_alsa_tests.rs
Normal file
@@ -0,0 +1,38 @@
|
||||
//! Verify fallback among installed layouts while ignoring non-directory entries.
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::plugin_directory;
|
||||
|
||||
#[test]
|
||||
fn discovers_available_layout_without_selecting_a_file() -> std::io::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"codex-alsa-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
));
|
||||
std::fs::create_dir(&root)?;
|
||||
let multiarch = root.join("multiarch");
|
||||
let lib64 = root.join("lib64");
|
||||
let generic = root.join("generic");
|
||||
let candidates = [
|
||||
multiarch.to_str().unwrap(),
|
||||
lib64.to_str().unwrap(),
|
||||
generic.to_str().unwrap(),
|
||||
];
|
||||
|
||||
assert_eq!(plugin_directory(&candidates), None);
|
||||
std::fs::create_dir(&generic)?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[2]));
|
||||
std::fs::write(&lib64, "not a directory")?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[2]));
|
||||
std::fs::remove_file(&lib64)?;
|
||||
std::fs::create_dir(&lib64)?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[1]));
|
||||
std::fs::create_dir(&multiarch)?;
|
||||
assert_eq!(plugin_directory(&candidates), Some(candidates[0]));
|
||||
std::fs::remove_dir_all(root)
|
||||
}
|
||||
61
akode-rs/realtime-webrtc/src/message_reader.rs
Normal file
61
akode-rs/realtime-webrtc/src/message_reader.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
//! Read bounded helper frames independently of pipe chunks; cancellation retains partial input.
|
||||
|
||||
use std::io;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::Message;
|
||||
use crate::decode_frame;
|
||||
|
||||
// Matches the maximum read in akode_utils_pty's pipe output reader. Retain at most
|
||||
// one such chunk and one bounded partial frame, never a queue of decoded messages.
|
||||
const MAX_CHUNK_BYTES: usize = 8_192;
|
||||
|
||||
pub(crate) struct MessageReader {
|
||||
output: mpsc::Receiver<Vec<u8>>,
|
||||
pending: std::vec::IntoIter<u8>,
|
||||
frame: Vec<u8>,
|
||||
}
|
||||
|
||||
impl MessageReader {
|
||||
pub(crate) fn new(output: mpsc::Receiver<Vec<u8>>) -> Self {
|
||||
Self {
|
||||
output,
|
||||
pending: Vec::new().into_iter(),
|
||||
frame: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn next(&mut self) -> io::Result<Message> {
|
||||
loop {
|
||||
let target = if let [a, b, c, d, ..] = self.frame.as_slice() {
|
||||
// Validate the header before consuming or allocating its payload.
|
||||
decode_frame(&self.frame)?;
|
||||
u32::from_be_bytes([*a, *b, *c, *d]) as usize + 4
|
||||
} else {
|
||||
4
|
||||
};
|
||||
while self.frame.len() < target {
|
||||
if self.pending.len() == 0 {
|
||||
let chunk = self.output.recv().await.ok_or_else(|| {
|
||||
io::Error::new(io::ErrorKind::UnexpectedEof, "voice helper output closed")
|
||||
})?;
|
||||
if chunk.is_empty() || chunk.len() > MAX_CHUNK_BYTES {
|
||||
return Err(io::Error::other("invalid voice helper output chunk"));
|
||||
}
|
||||
self.pending = chunk.into_iter();
|
||||
}
|
||||
self.frame
|
||||
.extend(self.pending.by_ref().take(target - self.frame.len()));
|
||||
}
|
||||
if let Some(message) = decode_frame(&self.frame)? {
|
||||
self.frame.clear();
|
||||
return Ok(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "message_reader_tests.rs"]
|
||||
mod tests;
|
||||
144
akode-rs/realtime-webrtc/src/message_reader_tests.rs
Normal file
144
akode-rs/realtime-webrtc/src/message_reader_tests.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
//! Exercise real frame decoding across pipe boundaries, cancellation, and invalid input.
|
||||
|
||||
use std::future::Future;
|
||||
use std::io;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::task::Waker;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::MAX_CHUNK_BYTES;
|
||||
use super::MessageReader;
|
||||
use crate::MAX_FRAME_BYTES;
|
||||
use crate::Message;
|
||||
use crate::encode_frame;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_fragmented_and_coalesced_messages() -> io::Result<()> {
|
||||
let expected = [
|
||||
Message::Hello {
|
||||
protocol: 1,
|
||||
build_commit: "test-build".into(),
|
||||
},
|
||||
Message::Ready {},
|
||||
Message::Close {},
|
||||
Message::Closed {},
|
||||
];
|
||||
let frames = expected
|
||||
.iter()
|
||||
.map(encode_frame)
|
||||
.collect::<io::Result<Vec<_>>>()?
|
||||
.concat();
|
||||
// Every split exercises both a partial frame and multiple messages in a chunk.
|
||||
for split in 1..frames.len() {
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 2);
|
||||
sender.try_send(frames[..split].to_vec()).unwrap();
|
||||
sender.try_send(frames[split..].to_vec()).unwrap();
|
||||
drop(sender);
|
||||
let mut reader = MessageReader::new(receiver);
|
||||
let mut actual = Vec::new();
|
||||
for _ in &expected {
|
||||
actual.push(reader.next().await?);
|
||||
}
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(
|
||||
reader.next().await.unwrap_err().kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_read_preserves_each_partial_header_and_payload() -> io::Result<()> {
|
||||
let expected = Message::Hello {
|
||||
protocol: 1,
|
||||
build_commit: "test-build".into(),
|
||||
};
|
||||
let frame = encode_frame(&expected)?;
|
||||
for split in 1..frame.len() {
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 1);
|
||||
sender.try_send(frame[..split].to_vec()).unwrap();
|
||||
let mut reader = MessageReader::new(receiver);
|
||||
{
|
||||
let mut read = std::pin::pin!(reader.next());
|
||||
assert!(matches!(
|
||||
read.as_mut().poll(&mut Context::from_waker(Waker::noop())),
|
||||
Poll::Pending
|
||||
));
|
||||
}
|
||||
sender.try_send(frame[split..].to_vec()).unwrap();
|
||||
assert_eq!(reader.next().await?, expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_oversized_headers_without_waiting_for_payload() {
|
||||
for length in [MAX_FRAME_BYTES as u32 + 1, u32::MAX] {
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 1);
|
||||
sender.try_send(length.to_be_bytes().to_vec()).unwrap();
|
||||
let mut reader = MessageReader::new(receiver);
|
||||
let mut read = std::pin::pin!(reader.next());
|
||||
assert!(matches!(
|
||||
read.as_mut().poll(&mut Context::from_waker(Waker::noop())),
|
||||
Poll::Ready(Err(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_truncation_at_every_byte_boundary() -> io::Result<()> {
|
||||
let frame = encode_frame(&Message::Ready {})?;
|
||||
for end in 0..frame.len() {
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 1);
|
||||
if end > 0 {
|
||||
sender.try_send(frame[..end].to_vec()).unwrap();
|
||||
}
|
||||
drop(sender);
|
||||
assert_eq!(
|
||||
MessageReader::new(receiver)
|
||||
.next()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
io::ErrorKind::UnexpectedEof
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_malformed_input_without_echoing_payload() {
|
||||
let secret = b"sensitive-invalid-json";
|
||||
let mut invalid = (secret.len() as u32).to_be_bytes().to_vec();
|
||||
invalid.extend(secret);
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 1);
|
||||
sender.try_send(invalid).unwrap();
|
||||
assert_eq!(
|
||||
MessageReader::new(receiver)
|
||||
.next()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"invalid voice frame"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_chunks_outside_the_pipe_read_bound() {
|
||||
for chunk in [vec![], vec![0; MAX_CHUNK_BYTES + 1]] {
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 1);
|
||||
sender.try_send(chunk).unwrap();
|
||||
assert_eq!(
|
||||
MessageReader::new(receiver)
|
||||
.next()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"invalid voice helper output chunk"
|
||||
);
|
||||
}
|
||||
}
|
||||
165
akode-rs/realtime-webrtc/src/protocol.rs
Normal file
165
akode-rs/realtime-webrtc/src/protocol.rs
Normal file
@@ -0,0 +1,165 @@
|
||||
//! Bounded same-build controls and redacted signaling; audio never crosses this pipe.
|
||||
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
pub const MAX_FRAME_BYTES: usize = 128 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AudioControls {
|
||||
pub microphone_muted: bool,
|
||||
pub speaker_suppressed: bool,
|
||||
}
|
||||
|
||||
/// Peaks contain levels only, never retained audio or backend messages.
|
||||
#[derive(Debug, Default, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AudioState {
|
||||
pub microphone_peak: u16,
|
||||
pub speaker_peak: u16,
|
||||
}
|
||||
|
||||
/// Direction of a local audio device, shared by enumeration and capture/playback selection.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum AudioDeviceKind {
|
||||
Input,
|
||||
Output,
|
||||
}
|
||||
|
||||
/// Local device preferences fixed for the lifetime of a voice conversation.
|
||||
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AudioDeviceSelection {
|
||||
pub microphone: Option<String>,
|
||||
pub speaker: Option<String>,
|
||||
pub channel: Option<Vec<std::num::NonZeroU16>>,
|
||||
}
|
||||
|
||||
/// Local device metadata; enumeration never opens streams.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct AudioDevice {
|
||||
pub name: String,
|
||||
pub channels: u16,
|
||||
pub is_default: bool,
|
||||
}
|
||||
|
||||
/// SDP contains ICE credentials. Bound it at construction and never expose it in diagnostics.
|
||||
#[derive(Deserialize, PartialEq, Serialize)]
|
||||
#[serde(try_from = "String")]
|
||||
pub struct SessionDescription(String);
|
||||
|
||||
impl TryFrom<String> for SessionDescription {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: String) -> Result<Self, Self::Error> {
|
||||
if value.is_empty() || value.len() > 64 * 1024 {
|
||||
return Err("invalid voice session description length");
|
||||
}
|
||||
Ok(Self(value))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for SessionDescription {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("SessionDescription([REDACTED])")
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionDescription {
|
||||
pub fn into_sdp(self) -> String {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed child settings prevent native initialization from scanning system plugins or caches.
|
||||
pub const RUNTIME_ENVIRONMENT: [(&str, &str); 7] = [
|
||||
("GST_PLUGIN_PATH", ""),
|
||||
("GST_PLUGIN_PATH_1_0", ""),
|
||||
("GST_PLUGIN_SYSTEM_PATH", ""),
|
||||
("GST_PLUGIN_SYSTEM_PATH_1_0", ""),
|
||||
(
|
||||
"GST_REGISTRY",
|
||||
if cfg!(windows) { "NUL" } else { "/dev/null" },
|
||||
),
|
||||
("GST_REGISTRY_UPDATE", "no"),
|
||||
("GST_REGISTRY_FORK", "no"),
|
||||
];
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(
|
||||
tag = "type",
|
||||
rename_all = "camelCase",
|
||||
rename_all_fields = "camelCase",
|
||||
deny_unknown_fields
|
||||
)]
|
||||
pub enum Message {
|
||||
Hello { protocol: u32, build_commit: String },
|
||||
Ready {},
|
||||
InitializeRuntime {},
|
||||
RuntimeReady {},
|
||||
StartTransport {},
|
||||
Offer { sdp: SessionDescription },
|
||||
ApplyAnswer { sdp: SessionDescription },
|
||||
TransportReady {},
|
||||
TransportTimedOut {},
|
||||
ListDevices { kind: AudioDeviceKind },
|
||||
DeviceList { devices: Vec<AudioDevice> },
|
||||
OpenDevices { selection: AudioDeviceSelection },
|
||||
DevicesOpened {},
|
||||
SetAudioControls { controls: AudioControls },
|
||||
AudioControlsApplied {},
|
||||
InspectAudio {},
|
||||
AudioState { state: AudioState },
|
||||
Close {},
|
||||
Closed {},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "protocol_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
pub fn encode_frame(message: &Message) -> io::Result<Vec<u8>> {
|
||||
let payload = serde_json::to_vec(message)?;
|
||||
if payload.len() > MAX_FRAME_BYTES {
|
||||
return Err(io::Error::other("voice frame exceeds limit"));
|
||||
}
|
||||
let mut frame = (payload.len() as u32).to_be_bytes().to_vec();
|
||||
frame.extend(payload);
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
pub fn decode_frame(frame: &[u8]) -> io::Result<Option<Message>> {
|
||||
let [a, b, c, d, ..] = frame else {
|
||||
return Ok(None);
|
||||
};
|
||||
let length = u32::from_be_bytes([*a, *b, *c, *d]) as usize;
|
||||
if length > MAX_FRAME_BYTES || frame.len() > length + 4 {
|
||||
return Err(io::Error::other("invalid voice frame length"));
|
||||
}
|
||||
frame
|
||||
.get(4..length + 4)
|
||||
.map(serde_json::from_slice)
|
||||
.transpose()
|
||||
.map_err(|_| io::Error::other("invalid voice frame"))
|
||||
}
|
||||
|
||||
pub fn read_message(reader: &mut impl Read) -> io::Result<Option<Message>> {
|
||||
let mut header = [0; 4];
|
||||
match reader.read_exact(&mut header[..1]) {
|
||||
Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
|
||||
result => result?,
|
||||
}
|
||||
reader.read_exact(&mut header[1..])?;
|
||||
decode_frame(&header)?;
|
||||
let length = u32::from_be_bytes(header) as usize;
|
||||
let mut frame = header.to_vec();
|
||||
frame.resize(length + 4, /*value*/ 0);
|
||||
reader.read_exact(&mut frame[4..])?;
|
||||
decode_frame(&frame)
|
||||
}
|
||||
28
akode-rs/realtime-webrtc/src/protocol_tests.rs
Normal file
28
akode-rs/realtime-webrtc/src/protocol_tests.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn signaling_roundtrips_without_diagnostic_secrets() {
|
||||
let secret = "a=ice-pwd:synthetic-secret";
|
||||
let message = Message::ApplyAnswer {
|
||||
sdp: secret.to_owned().try_into().unwrap(),
|
||||
};
|
||||
let debug = format!("{message:?}");
|
||||
assert!(!debug.contains(secret));
|
||||
assert!(debug.contains("REDACTED"));
|
||||
assert_eq!(
|
||||
decode_frame(&encode_frame(&message).unwrap()).unwrap(),
|
||||
Some(message)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signaling_bounds_apply_to_untrusted_wire_input() {
|
||||
for sdp in [String::new(), "x".repeat(64 * 1024 + 1)] {
|
||||
let json = serde_json::json!({"type": "applyAnswer", "sdp": sdp}).to_string();
|
||||
let mut frame = (json.len() as u32).to_be_bytes().to_vec();
|
||||
frame.extend(json.as_bytes());
|
||||
let error = decode_frame(&frame).unwrap_err();
|
||||
assert_eq!(error.to_string(), "invalid voice frame");
|
||||
}
|
||||
}
|
||||
380
akode-rs/realtime-webrtc/src/session.rs
Normal file
380
akode-rs/realtime-webrtc/src/session.rs
Normal file
@@ -0,0 +1,380 @@
|
||||
//! Synchronous UI handles for one helper-owning actor. Closing any handle or dropping the last
|
||||
//! owner cancels pending I/O; bounded, ordered commands preserve every mute transition.
|
||||
//! A shared process-lifetime runtime keeps child reapers alive after an actor stops.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::AtomicU16;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::mpsc as blocking;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use futures::future::AbortHandle;
|
||||
use futures::future::AbortRegistration;
|
||||
use futures::future::Abortable;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::AudioControls;
|
||||
use crate::AudioDeviceSelection;
|
||||
use crate::ConnectionError;
|
||||
use crate::SessionDescription;
|
||||
use crate::VoiceHost;
|
||||
|
||||
// Handshake (5s), runtime initialization (30s), offer gathering (20s), plus overhead.
|
||||
const STARTUP_WAIT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
// An in-flight request (5s), answer (20s), devices (5s), controls (5s), plus overhead.
|
||||
const ANSWER_WAIT: Duration = Duration::from_secs(/*secs*/ 40);
|
||||
static RUNTIME: Mutex<Option<Arc<tokio::runtime::Runtime>>> = Mutex::new(None);
|
||||
|
||||
enum Command {
|
||||
Answer(
|
||||
SessionDescription,
|
||||
blocking::SyncSender<std::result::Result<(), crate::ConnectionError>>,
|
||||
),
|
||||
Controls(AudioControls),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
microphone: AtomicU16,
|
||||
speaker: AtomicU16,
|
||||
error: Mutex<Option<(ConnectionError, String)>>,
|
||||
}
|
||||
|
||||
struct Owner {
|
||||
sender: mpsc::Sender<Command>,
|
||||
stop: AbortHandle,
|
||||
state: Arc<State>,
|
||||
controls: Arc<Mutex<AudioControls>>,
|
||||
}
|
||||
|
||||
impl Drop for Owner {
|
||||
fn drop(&mut self) {
|
||||
self.stop.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/// A cloned handle shares ownership; native media remains entirely inside the child process.
|
||||
#[derive(Clone)]
|
||||
pub struct RealtimeWebrtcSessionHandle(Arc<Owner>);
|
||||
|
||||
impl std::fmt::Debug for RealtimeWebrtcSessionHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("RealtimeWebrtcSessionHandle")
|
||||
}
|
||||
}
|
||||
|
||||
/// An offer is not proof of connectivity or working devices.
|
||||
pub struct StartedRealtimeWebrtcSession {
|
||||
pub offer_sdp: String,
|
||||
pub handle: RealtimeWebrtcSessionHandle,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for StartedRealtimeWebrtcSession {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str("StartedRealtimeWebrtcSession { offer_sdp: [REDACTED] }")
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RealtimeWebrtcSession;
|
||||
|
||||
impl RealtimeWebrtcSession {
|
||||
/// Check package availability without loading native code or touching any audio device.
|
||||
/// Linux packages may pair a musl application with a GNU helper; startup checks host loading.
|
||||
pub fn is_supported() -> bool {
|
||||
cfg!(any(
|
||||
target_os = "macos",
|
||||
target_os = "linux",
|
||||
all(windows, target_env = "msvc")
|
||||
)) && akode_install_context::InstallContext::current()
|
||||
.package_layout
|
||||
.as_ref()
|
||||
.is_some_and(|package| package_has_runtime(package.package_dir.as_path()))
|
||||
}
|
||||
|
||||
/// Called off the UI thread. Cancellation also owns startup before a handle is returned.
|
||||
pub fn start(
|
||||
abort: AbortRegistration,
|
||||
selection: AudioDeviceSelection,
|
||||
) -> Result<StartedRealtimeWebrtcSession> {
|
||||
let package = akode_install_context::InstallContext::current()
|
||||
.package_layout
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("voice package unavailable"))?;
|
||||
let build_commit = akode_build_info::BuildInfo::get().build_commit().to_owned();
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 8);
|
||||
let (offer, result) = blocking::sync_channel(/*bound*/ 1);
|
||||
let (stop, stopped) = AbortHandle::new_pair();
|
||||
let state = Arc::new(State::default());
|
||||
let controls = Arc::new(Mutex::new(AudioControls {
|
||||
microphone_muted: false,
|
||||
speaker_suppressed: false,
|
||||
}));
|
||||
let handle = RealtimeWebrtcSessionHandle(Arc::new(Owner {
|
||||
sender,
|
||||
stop,
|
||||
state: state.clone(),
|
||||
controls: controls.clone(),
|
||||
}));
|
||||
let runtime = {
|
||||
let mut runtime = RUNTIME
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(runtime) = runtime.as_ref() {
|
||||
runtime.clone()
|
||||
} else {
|
||||
let shared = Arc::new(
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(/*val*/ 1)
|
||||
.enable_all()
|
||||
.build()?,
|
||||
);
|
||||
*runtime = Some(shared.clone());
|
||||
shared
|
||||
}
|
||||
};
|
||||
std::thread::Builder::new()
|
||||
.name("voice-session".into())
|
||||
.spawn(move || {
|
||||
let mut receiver = receiver;
|
||||
let task = async {
|
||||
let host = report_failure(
|
||||
ConnectionError::HelperStartup,
|
||||
VoiceHost::connect(&package, &build_commit).await,
|
||||
)?;
|
||||
let host = report_failure(
|
||||
ConnectionError::RuntimeInitialization,
|
||||
host.initialize_runtime().await,
|
||||
)?;
|
||||
let (host, sdp) =
|
||||
report_failure(ConnectionError::Transport, host.start_transport().await)?;
|
||||
offer
|
||||
.send(Ok(sdp.into_sdp()))
|
||||
.map_err(|_| anyhow::anyhow!("voice startup cancelled"))?;
|
||||
run(host, &mut receiver, &state, &controls, selection).await
|
||||
};
|
||||
let result = runtime.block_on(Abortable::new(Abortable::new(task, abort), stopped));
|
||||
if let Ok(Ok(Err(error))) = result {
|
||||
let failure = error
|
||||
.downcast_ref::<ConnectionError>()
|
||||
.copied()
|
||||
.unwrap_or(ConnectionError::Failed);
|
||||
let _ = offer.try_send(Err(failure));
|
||||
*state
|
||||
.error
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) =
|
||||
Some((failure, failure.to_string()));
|
||||
}
|
||||
})?;
|
||||
let offer_sdp = result
|
||||
.recv_timeout(STARTUP_WAIT)
|
||||
.map_err(|_| anyhow::anyhow!("voice startup failed"))??;
|
||||
Ok(StartedRealtimeWebrtcSession { offer_sdp, handle })
|
||||
}
|
||||
}
|
||||
|
||||
// Availability is not proof of runtime integrity, device access, or session connectivity.
|
||||
fn package_has_runtime(package: &std::path::Path) -> bool {
|
||||
let voice = package.join("akode-resources/voice");
|
||||
let (helper, runtime) = if cfg!(target_os = "macos") {
|
||||
("bin/akode-voice-host", "lib/libgstreamer-1.0.0.dylib")
|
||||
} else if cfg!(windows) {
|
||||
("bin/akode-voice-host.exe", "bin/gstreamer-1.0-0.dll")
|
||||
} else {
|
||||
("bin/akode-voice-host", "lib/libgstreamer-1.0.so.0")
|
||||
};
|
||||
voice.join(helper).is_file() && voice.join(runtime).is_file()
|
||||
}
|
||||
|
||||
impl RealtimeWebrtcSessionHandle {
|
||||
pub fn close(&self) {
|
||||
self.0.stop.abort();
|
||||
}
|
||||
|
||||
/// Queue an ordered privacy transition; saturation terminates the session instead of dropping it.
|
||||
pub fn set_microphone_muted(&self, muted: bool) -> Result<()> {
|
||||
let mut controls = self
|
||||
.0
|
||||
.controls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
controls.microphone_muted = muted;
|
||||
self.send(Command::Controls(*controls))
|
||||
}
|
||||
|
||||
pub fn set_speaker_suppressed(&self, suppressed: bool) {
|
||||
let mut controls = self
|
||||
.0
|
||||
.controls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
controls.speaker_suppressed = suppressed;
|
||||
let _ = self.send(Command::Controls(*controls));
|
||||
}
|
||||
|
||||
/// Called off the UI thread; return only after negotiation, device startup and restored controls.
|
||||
pub fn apply_answer_sdp(
|
||||
&self,
|
||||
answer: String,
|
||||
) -> std::result::Result<(), crate::ConnectionError> {
|
||||
let sdp =
|
||||
SessionDescription::try_from(answer).map_err(|_| crate::ConnectionError::Failed)?;
|
||||
let (complete, result) = blocking::sync_channel(/*bound*/ 1);
|
||||
self.send(Command::Answer(sdp, complete))
|
||||
.map_err(|_| crate::ConnectionError::Failed)?;
|
||||
match result.recv_timeout(ANSWER_WAIT) {
|
||||
Ok(result) => result,
|
||||
Err(_) => {
|
||||
self.close();
|
||||
Err(crate::ConnectionError::Failed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_error(&self) -> Option<(ConnectionError, String)> {
|
||||
self.0
|
||||
.state
|
||||
.error
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.take()
|
||||
}
|
||||
|
||||
pub fn take_microphone_peak(&self) -> u16 {
|
||||
self.0.state.microphone.swap(/*val*/ 0, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
pub fn take_speaker_peak(&self) -> u16 {
|
||||
self.0.state.speaker.swap(/*val*/ 0, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
fn send(&self, command: Command) -> Result<()> {
|
||||
if self.0.sender.try_send(command).is_err() {
|
||||
let mut error = self
|
||||
.0
|
||||
.state
|
||||
.error
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if error.is_none() {
|
||||
*error = Some((
|
||||
ConnectionError::Failed,
|
||||
"Voice control channel unavailable.".into(),
|
||||
));
|
||||
}
|
||||
self.close();
|
||||
anyhow::bail!("voice control channel unavailable");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(
|
||||
mut host: VoiceHost,
|
||||
commands: &mut mpsc::Receiver<Command>,
|
||||
state: &State,
|
||||
controls: &Mutex<AudioControls>,
|
||||
selection: AudioDeviceSelection,
|
||||
) -> Result<()> {
|
||||
let mut connected = false;
|
||||
let mut poll = tokio::time::interval(Duration::from_millis(/*millis*/ 50));
|
||||
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
command = commands.recv() => match command {
|
||||
Some(Command::Answer(sdp, complete)) if !connected => {
|
||||
let startup = async {
|
||||
let mut host = report_failure(ConnectionError::Transport, host.apply_answer(sdp).await)?;
|
||||
host = report_failure(ConnectionError::AudioDevices, host.open_devices(selection.clone()).await)?;
|
||||
let applied = startup_controls(commands, controls, |initial| {
|
||||
host.begin_audio_controls(initial)
|
||||
});
|
||||
let applied = report_failure(ConnectionError::AudioControls, applied)?;
|
||||
report_failure(ConnectionError::AudioControls, applied.await)?;
|
||||
Ok::<_, anyhow::Error>(host)
|
||||
}.await;
|
||||
host = match startup {
|
||||
Ok(host) => host,
|
||||
Err(error) => {
|
||||
let failure = error.downcast_ref::<ConnectionError>()
|
||||
.copied().unwrap_or(ConnectionError::Failed);
|
||||
let _ = complete.send(Err(failure));
|
||||
// This failure is delivered by the startup completion only.
|
||||
return std::future::pending().await;
|
||||
}
|
||||
};
|
||||
connected = true;
|
||||
let _ = complete.send(Ok(()));
|
||||
}
|
||||
Some(Command::Controls(next)) => {
|
||||
if connected {
|
||||
report_failure(ConnectionError::AudioControls, host.set_audio_controls(next).await)?;
|
||||
}
|
||||
}
|
||||
Some(Command::Answer(..)) => anyhow::bail!("voice answer already applied"),
|
||||
None => return report_failure(ConnectionError::Shutdown, host.close().await),
|
||||
},
|
||||
_ = poll.tick() => {
|
||||
let audio = report_failure(ConnectionError::AudioSession, host.inspect_audio().await)?;
|
||||
state.microphone.fetch_max(audio.microphone_peak, Ordering::Release);
|
||||
state.speaker.fetch_max(audio.speaker_peak, Ordering::Release);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep diagnostics bounded and independent of untyped native, SDP, or device error text.
|
||||
fn report_failure<T>(stage: ConnectionError, result: Result<T>) -> Result<T> {
|
||||
result.map_err(|error| {
|
||||
let kind = if error.is::<tokio::time::error::Elapsed>() {
|
||||
"timeout"
|
||||
} else if let Some(error) = error.downcast_ref::<std::io::Error>() {
|
||||
match error.kind() {
|
||||
std::io::ErrorKind::UnexpectedEof
|
||||
| std::io::ErrorKind::BrokenPipe
|
||||
| std::io::ErrorKind::ConnectionReset => "closed",
|
||||
std::io::ErrorKind::InvalidData => "protocol",
|
||||
_ => "io",
|
||||
}
|
||||
} else {
|
||||
"other"
|
||||
};
|
||||
tracing::warn!(?stage, kind, "voice session operation failed");
|
||||
let failure = error
|
||||
.downcast_ref::<ConnectionError>()
|
||||
.copied()
|
||||
.unwrap_or(stage);
|
||||
// Replace the original error instead of retaining a potentially sensitive source chain.
|
||||
anyhow::Error::new(failure)
|
||||
})
|
||||
}
|
||||
|
||||
// Devices are still disabled. The snapshot and request enqueue share the setters' lock;
|
||||
// later setters remain ordered after this request without waiting for its acknowledgement.
|
||||
fn startup_controls<T>(
|
||||
commands: &mut mpsc::Receiver<Command>,
|
||||
controls: &Mutex<AudioControls>,
|
||||
dispatch: impl FnOnce(AudioControls) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let controls = controls
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
for _ in 0..commands.max_capacity() {
|
||||
match commands.try_recv() {
|
||||
Ok(Command::Controls(_)) => {}
|
||||
Err(mpsc::error::TryRecvError::Empty) => return dispatch(*controls),
|
||||
Ok(Command::Answer(..)) | Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||
anyhow::bail!("voice startup control sequence invalid");
|
||||
}
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(commands.is_empty(), "voice startup controls overloaded");
|
||||
dispatch(*controls)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "session_tests.rs"]
|
||||
mod tests;
|
||||
248
akode-rs/realtime-webrtc/src/session_tests.rs
Normal file
248
akode-rs/realtime-webrtc/src/session_tests.rs
Normal file
@@ -0,0 +1,248 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn handles() -> (
|
||||
RealtimeWebrtcSessionHandle,
|
||||
mpsc::Receiver<Command>,
|
||||
AbortRegistration,
|
||||
) {
|
||||
let (sender, receiver) = mpsc::channel(/*buffer*/ 8);
|
||||
let (stop, stopped) = AbortHandle::new_pair();
|
||||
let handle = RealtimeWebrtcSessionHandle(Arc::new(Owner {
|
||||
sender,
|
||||
stop,
|
||||
state: Arc::new(State::default()),
|
||||
controls: Arc::new(Mutex::new(AudioControls {
|
||||
microphone_muted: false,
|
||||
speaker_suppressed: false,
|
||||
})),
|
||||
}));
|
||||
(handle, receiver, stopped)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controls_preserve_order_and_independent_settings_and_overflow_closes() {
|
||||
let (handle, mut commands, _) = handles();
|
||||
handle.set_microphone_muted(/*muted*/ true).unwrap();
|
||||
handle.set_speaker_suppressed(/*suppressed*/ true);
|
||||
handle.set_microphone_muted(/*muted*/ false).unwrap();
|
||||
for expected in [(true, false), (true, true), (false, true)] {
|
||||
let Command::Controls(controls) = commands.try_recv().unwrap() else {
|
||||
panic!("wrong command")
|
||||
};
|
||||
assert_eq!(
|
||||
controls,
|
||||
AudioControls {
|
||||
microphone_muted: expected.0,
|
||||
speaker_suppressed: expected.1
|
||||
}
|
||||
);
|
||||
}
|
||||
for _ in 0..8 {
|
||||
handle.set_microphone_muted(/*muted*/ true).unwrap();
|
||||
}
|
||||
assert!(handle.set_microphone_muted(/*muted*/ false).is_err());
|
||||
assert!(handle.0.stop.is_aborted());
|
||||
assert_eq!(
|
||||
handle.take_error(),
|
||||
Some((
|
||||
ConnectionError::Failed,
|
||||
"Voice control channel unavailable.".into()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_control_send_preserves_existing_error() {
|
||||
let (handle, commands, _) = handles();
|
||||
*handle.0.state.error.lock().unwrap() = Some((
|
||||
ConnectionError::AudioSession,
|
||||
"voice audio session stopped unexpectedly".into(),
|
||||
));
|
||||
drop(commands);
|
||||
|
||||
assert!(handle.set_microphone_muted(/*muted*/ true).is_err());
|
||||
assert_eq!(
|
||||
handle.take_error(),
|
||||
Some((
|
||||
ConnectionError::AudioSession,
|
||||
"voice audio session stopped unexpectedly".into()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_final_owner_drop_cancels_and_explicit_close_cancels_all_clones() {
|
||||
let (handle, _commands, stopped) = handles();
|
||||
let clone = handle.clone();
|
||||
drop(handle);
|
||||
assert!(!clone.0.stop.is_aborted());
|
||||
drop(clone);
|
||||
assert!(
|
||||
Abortable::new(std::future::pending::<()>(), stopped)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let (handle, _commands, stopped) = handles();
|
||||
let clone = handle.clone();
|
||||
handle.close();
|
||||
assert!(clone.0.stop.is_aborted());
|
||||
assert!(
|
||||
Abortable::new(std::future::pending::<()>(), stopped)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offer_debug_redacts_credentials_and_peaks_are_consumed() {
|
||||
let (handle, _commands, _) = handles();
|
||||
handle.0.state.microphone.store(123, Ordering::Release);
|
||||
handle.0.state.speaker.store(456, Ordering::Release);
|
||||
assert_eq!(
|
||||
(handle.take_microphone_peak(), handle.take_speaker_peak()),
|
||||
(123, 456)
|
||||
);
|
||||
assert_eq!(
|
||||
(handle.take_microphone_peak(), handle.take_speaker_peak()),
|
||||
(0, 0)
|
||||
);
|
||||
let started = StartedRealtimeWebrtcSession {
|
||||
offer_sdp: "synthetic-secret".into(),
|
||||
handle,
|
||||
};
|
||||
assert!(!format!("{started:?}").contains("synthetic-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn controls_queued_during_negotiation_precede_first_device_enable() {
|
||||
let (handle, mut commands, _) = handles();
|
||||
// The actor has consumed Answer and is waiting for negotiation/device startup.
|
||||
handle.set_microphone_muted(/*muted*/ true).unwrap();
|
||||
handle.set_speaker_suppressed(/*suppressed*/ true);
|
||||
let controls = startup_controls(&mut commands, &handle.0.controls, Ok).unwrap();
|
||||
assert_eq!(
|
||||
controls,
|
||||
AudioControls {
|
||||
microphone_muted: true,
|
||||
speaker_suppressed: true
|
||||
}
|
||||
);
|
||||
assert!(commands.is_empty());
|
||||
let (complete, _) = blocking::sync_channel(/*bound*/ 1);
|
||||
handle
|
||||
.send(Command::Answer(
|
||||
"synthetic-answer".to_owned().try_into().unwrap(),
|
||||
complete,
|
||||
))
|
||||
.unwrap();
|
||||
assert!(startup_controls(&mut commands, &handle.0.controls, Ok).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn package_availability_requires_helper_and_native_runtime() {
|
||||
let unique = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let root = std::env::temp_dir().join(format!("voice-package-{}-{unique}", std::process::id()));
|
||||
let voice = root.join("akode-resources/voice");
|
||||
std::fs::create_dir_all(voice.join("bin")).unwrap();
|
||||
std::fs::create_dir_all(voice.join("lib")).unwrap();
|
||||
assert!(!package_has_runtime(&root));
|
||||
let helper = voice.join(if cfg!(windows) {
|
||||
"bin/akode-voice-host.exe"
|
||||
} else {
|
||||
"bin/akode-voice-host"
|
||||
});
|
||||
std::fs::write(&helper, b"synthetic helper").unwrap();
|
||||
assert!(!package_has_runtime(&root));
|
||||
let runtime = voice.join(if cfg!(target_os = "macos") {
|
||||
"lib/libgstreamer-1.0.0.dylib"
|
||||
} else if cfg!(windows) {
|
||||
"bin/gstreamer-1.0-0.dll"
|
||||
} else {
|
||||
"lib/libgstreamer-1.0.so.0"
|
||||
});
|
||||
std::fs::write(&runtime, b"synthetic runtime").unwrap();
|
||||
assert!(package_has_runtime(&root));
|
||||
std::fs::remove_file(helper).unwrap();
|
||||
assert!(!package_has_runtime(&root));
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_dispatch_is_ordered_but_acknowledgement_does_not_block_setters() {
|
||||
let (handle, mut commands, _) = handles();
|
||||
let applied = startup_controls(&mut commands, &handle.0.controls, |initial| {
|
||||
// This is the request enqueue boundary. A setter cannot commit a newer
|
||||
// snapshot until the initial request is already ordered before it.
|
||||
assert!(matches!(
|
||||
handle.0.controls.try_lock(),
|
||||
Err(std::sync::TryLockError::WouldBlock)
|
||||
));
|
||||
assert_eq!(
|
||||
initial,
|
||||
AudioControls {
|
||||
microphone_muted: false,
|
||||
speaker_suppressed: false,
|
||||
}
|
||||
);
|
||||
Ok(std::future::pending::<()>())
|
||||
})
|
||||
.unwrap();
|
||||
// The acknowledgement future has not completed or even been polled.
|
||||
handle.set_microphone_muted(/*muted*/ true).unwrap();
|
||||
let Command::Controls(next) = commands.try_recv().unwrap() else {
|
||||
panic!("expected queued mute")
|
||||
};
|
||||
assert_eq!(
|
||||
next,
|
||||
AudioControls {
|
||||
microphone_muted: true,
|
||||
speaker_suppressed: false,
|
||||
}
|
||||
);
|
||||
drop(applied);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_completion_preserves_classified_failure() {
|
||||
for failure in [
|
||||
crate::ConnectionError::NegotiationTimedOut,
|
||||
crate::ConnectionError::Failed,
|
||||
] {
|
||||
let (handle, mut commands, _) = handles();
|
||||
let caller = handle.clone();
|
||||
let thread = std::thread::spawn(move || caller.apply_answer_sdp("synthetic-answer".into()));
|
||||
let Some(Command::Answer(_, complete)) = commands.recv().await else {
|
||||
panic!("answer expected")
|
||||
};
|
||||
complete.send(Err(failure)).unwrap();
|
||||
assert_eq!(thread.join().unwrap(), Err(failure));
|
||||
assert_eq!(handle.take_error(), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classified_errors_discard_sensitive_sources_but_preserve_retry_classification() {
|
||||
let error = report_failure::<()>(
|
||||
ConnectionError::AudioDevices,
|
||||
Err(anyhow::anyhow!("synthetic-secret-sdp-device-path")),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
format!("{error:#}"),
|
||||
ConnectionError::AudioDevices.to_string()
|
||||
);
|
||||
assert!(!format!("{error:?}").contains("synthetic-secret"));
|
||||
let error = report_failure::<()>(
|
||||
ConnectionError::Transport,
|
||||
Err(ConnectionError::NegotiationTimedOut.into()),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<ConnectionError>(),
|
||||
Some(&ConnectionError::NegotiationTimedOut)
|
||||
);
|
||||
}
|
||||
243
akode-rs/realtime-webrtc/tests/common/mod.rs
Normal file
243
akode-rs/realtime-webrtc/tests/common/mod.rs
Normal file
@@ -0,0 +1,243 @@
|
||||
//! Copies this test executable into a private package and dispatches its fake helper before libtest.
|
||||
//! The fixture validates protocol order; it never loads native libraries or opens audio devices.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use akode_realtime_webrtc::AudioState;
|
||||
use akode_realtime_webrtc::Message;
|
||||
use akode_realtime_webrtc::encode_frame;
|
||||
use akode_realtime_webrtc::read_message;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::process::Stdio;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use std::time::SystemTime;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
pub const BUILD_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
|
||||
pub const WAIT: Duration = Duration::from_secs(/*secs*/ 10);
|
||||
const APP: &str = if cfg!(windows) { "akode.exe" } else { "codex" };
|
||||
const HELPER: &str = if cfg!(windows) {
|
||||
"akode-voice-host.exe"
|
||||
} else {
|
||||
"akode-voice-host"
|
||||
};
|
||||
|
||||
pub fn wait_for(mut ready: impl FnMut() -> bool) -> Result<()> {
|
||||
let deadline = Instant::now() + WAIT;
|
||||
while !ready() {
|
||||
ensure!(Instant::now() < deadline, "fixture deadline expired");
|
||||
thread::sleep(Duration::from_millis(/*millis*/ 5));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn wait_for_helper_reaped(root: &std::path::Path) -> Result<()> {
|
||||
let pid: libc::pid_t = fs::read_to_string(root.join("helper-pid"))?.parse()?;
|
||||
wait_for(|| {
|
||||
// SAFETY: Signal zero checks process existence without delivering a signal.
|
||||
let result = unsafe {
|
||||
libc::kill(pid, /*sig*/ 0)
|
||||
};
|
||||
result == -1 && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH)
|
||||
})
|
||||
}
|
||||
|
||||
struct Package(PathBuf);
|
||||
impl Drop for Package {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
// The child discovers its installation through current_exe, exactly as the public facade does.
|
||||
pub fn package(test: &str) -> Result<Option<PathBuf>> {
|
||||
let source = std::env::current_exe()?;
|
||||
if source.file_name().is_some_and(|name| name == APP) {
|
||||
akode_build_info::BuildInfo::initialize(BUILD_COMMIT);
|
||||
return Ok(Some(
|
||||
source
|
||||
.parent()
|
||||
.context("bin")?
|
||||
.parent()
|
||||
.context("package")?
|
||||
.to_owned(),
|
||||
));
|
||||
}
|
||||
let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
|
||||
let package =
|
||||
Package(std::env::temp_dir().join(format!("voice-actor-{}-{nonce}", std::process::id())));
|
||||
let root = &package.0;
|
||||
fs::create_dir_all(root.join("bin"))?;
|
||||
fs::create_dir_all(root.join("akode-resources/voice/bin"))?;
|
||||
fs::write(root.join("akode-package.json"), "{}")?;
|
||||
akode_utils_cargo_bin::copy_executable(&source, &root.join("bin").join(APP))?;
|
||||
akode_utils_cargo_bin::copy_executable(
|
||||
&source,
|
||||
&root.join("akode-resources/voice/bin").join(HELPER),
|
||||
)?;
|
||||
let mut child = Command::new(root.join("bin").join(APP))
|
||||
.args(["--exact", test, "--nocapture"])
|
||||
.current_dir(root)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let deadline = Instant::now() + WAIT * 3;
|
||||
while child.try_wait()?.is_none() {
|
||||
if Instant::now() >= deadline {
|
||||
child.kill()?;
|
||||
child.wait()?;
|
||||
anyhow::bail!("packaged test timed out");
|
||||
}
|
||||
thread::sleep(Duration::from_millis(/*millis*/ 10));
|
||||
}
|
||||
let output = child.wait_with_output()?;
|
||||
ensure!(
|
||||
output.status.success(),
|
||||
"packaged test failed: {}\n{}\nfixture: {}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
fs::read_to_string(root.join("fixture-error")).unwrap_or_default()
|
||||
);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
#[ctor::ctor]
|
||||
fn dispatch_helper() {
|
||||
if std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|path| path.file_name().map(std::ffi::OsStr::to_owned))
|
||||
.is_some_and(|name| name == HELPER)
|
||||
{
|
||||
if let Err(error) = helper() {
|
||||
let _ = fs::write("fixture-error", format!("{error:#}"));
|
||||
std::process::exit(1);
|
||||
}
|
||||
std::process::exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum Stage {
|
||||
Hello,
|
||||
Initialize,
|
||||
Offer,
|
||||
Answer,
|
||||
Devices,
|
||||
Controls,
|
||||
Running,
|
||||
}
|
||||
|
||||
fn helper() -> Result<()> {
|
||||
let root = std::env::current_dir()?;
|
||||
fs::write(root.join("helper-pid"), std::process::id().to_string())?;
|
||||
let mut input = std::io::stdin().lock();
|
||||
let mut output = std::io::stdout().lock();
|
||||
let mut stage = Stage::Hello;
|
||||
let mut controls_history = Vec::new();
|
||||
while let Some(request) = read_message(&mut input)? {
|
||||
let response = match request {
|
||||
Message::Hello {
|
||||
protocol: 1,
|
||||
build_commit,
|
||||
} if stage == Stage::Hello => {
|
||||
ensure!(build_commit == BUILD_COMMIT, "wrong executable build stamp");
|
||||
stage = Stage::Initialize;
|
||||
Message::Ready {}
|
||||
}
|
||||
Message::ListDevices { kind } if stage == Stage::Initialize => Message::DeviceList {
|
||||
devices: vec![akode_realtime_webrtc::AudioDevice {
|
||||
name: match kind {
|
||||
akode_realtime_webrtc::AudioDeviceKind::Input => "Interface",
|
||||
akode_realtime_webrtc::AudioDeviceKind::Output => "Headphones",
|
||||
}
|
||||
.into(),
|
||||
channels: 16,
|
||||
is_default: true,
|
||||
}],
|
||||
},
|
||||
Message::InitializeRuntime {} if stage == Stage::Initialize => {
|
||||
fs::write(root.join("initializing"), [])?;
|
||||
if root.join("hold-initialization").exists() {
|
||||
wait_for(|| root.join("release").exists())?;
|
||||
}
|
||||
if root.join("fail-initialization").exists() {
|
||||
anyhow::bail!("synthetic private runtime diagnostic");
|
||||
}
|
||||
stage = Stage::Offer;
|
||||
Message::RuntimeReady {}
|
||||
}
|
||||
Message::StartTransport {} if stage == Stage::Offer => {
|
||||
stage = Stage::Answer;
|
||||
Message::Offer {
|
||||
sdp: "synthetic-offer"
|
||||
.to_owned()
|
||||
.try_into()
|
||||
.map_err(anyhow::Error::msg)?,
|
||||
}
|
||||
}
|
||||
Message::ApplyAnswer { sdp } if stage == Stage::Answer => {
|
||||
ensure!(
|
||||
sdp.into_sdp() == "synthetic-answer",
|
||||
"unexpected fixture answer"
|
||||
);
|
||||
fs::write(root.join("answer"), [])?;
|
||||
wait_for(|| root.join("release").exists())?;
|
||||
stage = Stage::Devices;
|
||||
Message::TransportReady {}
|
||||
}
|
||||
Message::OpenDevices { selection } if stage == Stage::Devices => {
|
||||
fs::write(
|
||||
root.join("input-selection"),
|
||||
serde_json::to_vec(&selection)?,
|
||||
)?;
|
||||
if root.join("fail-devices").exists() {
|
||||
anyhow::bail!("synthetic private device diagnostic");
|
||||
}
|
||||
stage = Stage::Controls;
|
||||
Message::DevicesOpened {}
|
||||
}
|
||||
Message::SetAudioControls { controls }
|
||||
if stage == Stage::Controls || stage == Stage::Running =>
|
||||
{
|
||||
controls_history.push(controls);
|
||||
fs::write(
|
||||
root.join("controls"),
|
||||
serde_json::to_vec(&controls_history)?,
|
||||
)?;
|
||||
stage = Stage::Running;
|
||||
Message::AudioControlsApplied {}
|
||||
}
|
||||
Message::InspectAudio {} if stage == Stage::Answer || stage == Stage::Running => {
|
||||
if root.join("exit").exists() {
|
||||
return Ok(());
|
||||
}
|
||||
Message::AudioState {
|
||||
state: if stage == Stage::Running {
|
||||
AudioState {
|
||||
microphone_peak: 123,
|
||||
speaker_peak: 456,
|
||||
}
|
||||
} else {
|
||||
AudioState::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
Message::Close {} => {
|
||||
output.write_all(&encode_frame(&Message::Closed {})?)?;
|
||||
output.flush()?;
|
||||
return Ok(());
|
||||
}
|
||||
_ => anyhow::bail!("unexpected fixture protocol sequence"),
|
||||
};
|
||||
output.write_all(&encode_frame(&response)?)?;
|
||||
output.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
204
akode-rs/realtime-webrtc/tests/session_actor.rs
Normal file
204
akode-rs/realtime-webrtc/tests/session_actor.rs
Normal file
@@ -0,0 +1,204 @@
|
||||
//! Exercises the public session actor against a separate framed-IPC helper, without native audio.
|
||||
|
||||
mod common;
|
||||
|
||||
use anyhow::Result;
|
||||
use akode_realtime_webrtc::AudioControls;
|
||||
use akode_realtime_webrtc::AudioDeviceKind;
|
||||
use akode_realtime_webrtc::AudioDeviceSelection;
|
||||
use akode_realtime_webrtc::RealtimeWebrtcSession;
|
||||
use futures::future::AbortHandle;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::thread;
|
||||
|
||||
#[test]
|
||||
fn startup_controls_meters_and_helper_loss() -> Result<()> {
|
||||
let Some(root) = common::package("startup_controls_meters_and_helper_loss")? else {
|
||||
return Ok(());
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
assert!(!RealtimeWebrtcSession::is_supported());
|
||||
let libraries = root.join("akode-resources/voice/lib");
|
||||
fs::create_dir_all(&libraries)?;
|
||||
fs::write(libraries.join("libgstreamer-1.0.so.0"), b"fixture runtime")?;
|
||||
assert!(RealtimeWebrtcSession::is_supported());
|
||||
}
|
||||
let (_abort, registration) = AbortHandle::new_pair();
|
||||
let started = RealtimeWebrtcSession::start(
|
||||
registration,
|
||||
AudioDeviceSelection {
|
||||
microphone: Some("Zen Go Synergy Core Playback".into()),
|
||||
speaker: Some("Headphones".into()),
|
||||
channel: Some(vec![
|
||||
std::num::NonZeroU16::new(/*n*/ 1).unwrap(),
|
||||
std::num::NonZeroU16::new(/*n*/ 2).unwrap(),
|
||||
]),
|
||||
},
|
||||
)?;
|
||||
assert_eq!(started.offer_sdp, "synthetic-offer");
|
||||
let handle = started.handle;
|
||||
handle.set_microphone_muted(/*muted*/ true)?;
|
||||
let answer_handle = handle.clone();
|
||||
let answer = thread::spawn(move || answer_handle.apply_answer_sdp("synthetic-answer".into()));
|
||||
common::wait_for(|| root.join("answer").exists())?;
|
||||
handle.set_speaker_suppressed(/*suppressed*/ true);
|
||||
fs::write(root.join("release"), [])?;
|
||||
answer.join().expect("answer thread")?;
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&fs::read(root.join("input-selection"))?)?,
|
||||
serde_json::json!({"microphone": "Zen Go Synergy Core Playback", "speaker": "Headphones", "channel": [1, 2]})
|
||||
);
|
||||
let initial: Vec<AudioControls> = serde_json::from_slice(&fs::read(root.join("controls"))?)?;
|
||||
assert_eq!(
|
||||
initial,
|
||||
vec![AudioControls {
|
||||
microphone_muted: true,
|
||||
speaker_suppressed: true
|
||||
}]
|
||||
);
|
||||
handle.set_microphone_muted(/*muted*/ false)?;
|
||||
handle.set_speaker_suppressed(/*suppressed*/ false);
|
||||
let expected = serde_json::to_vec(&vec![
|
||||
AudioControls {
|
||||
microphone_muted: true,
|
||||
speaker_suppressed: true,
|
||||
},
|
||||
AudioControls {
|
||||
microphone_muted: false,
|
||||
speaker_suppressed: true,
|
||||
},
|
||||
AudioControls {
|
||||
microphone_muted: false,
|
||||
speaker_suppressed: false,
|
||||
},
|
||||
])?;
|
||||
common::wait_for(|| fs::read(root.join("controls")).is_ok_and(|data| data == expected))?;
|
||||
common::wait_for(|| handle.take_microphone_peak() == 123)?;
|
||||
common::wait_for(|| handle.take_speaker_peak() == 456)?;
|
||||
fs::write(root.join("exit"), [])?;
|
||||
let mut error = None;
|
||||
common::wait_for(|| {
|
||||
error = handle.take_error();
|
||||
error.is_some()
|
||||
})?;
|
||||
assert_eq!(
|
||||
error,
|
||||
Some((
|
||||
akode_realtime_webrtc::ConnectionError::AudioSession,
|
||||
"voice audio session stopped unexpectedly".into()
|
||||
))
|
||||
);
|
||||
assert_eq!(handle.take_error(), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_cancellation_interrupts_startup() -> Result<()> {
|
||||
let Some(root) = common::package("external_cancellation_interrupts_startup")? else {
|
||||
return Ok(());
|
||||
};
|
||||
fs::write(root.join("hold-initialization"), [])?;
|
||||
let (abort, registration) = AbortHandle::new_pair();
|
||||
let (result, received) = std::sync::mpsc::sync_channel(/*bound*/ 1);
|
||||
let startup = thread::spawn(move || {
|
||||
let _ = result.send(RealtimeWebrtcSession::start(
|
||||
registration,
|
||||
AudioDeviceSelection::default(),
|
||||
));
|
||||
});
|
||||
common::wait_for(|| root.join("initializing").exists())?;
|
||||
abort.abort();
|
||||
assert!(
|
||||
received
|
||||
.recv_timeout(std::time::Duration::from_secs(/*secs*/ 2))?
|
||||
.is_err()
|
||||
);
|
||||
startup.join().expect("startup thread");
|
||||
#[cfg(unix)]
|
||||
common::wait_for_helper_reaped(&root)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn last_owner_drop_reaps_helper() -> Result<()> {
|
||||
let Some(root) = common::package("last_owner_drop_reaps_helper")? else {
|
||||
return Ok(());
|
||||
};
|
||||
let (_abort, registration) = AbortHandle::new_pair();
|
||||
let started = RealtimeWebrtcSession::start(registration, AudioDeviceSelection::default())?;
|
||||
drop(started);
|
||||
common::wait_for_helper_reaped(&root)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_failure_reaches_startup_completion_without_duplicate_error() -> Result<()> {
|
||||
let Some(root) =
|
||||
common::package("device_failure_reaches_startup_completion_without_duplicate_error")?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
fs::write(root.join("fail-devices"), [])?;
|
||||
fs::write(root.join("release"), [])?;
|
||||
let (_abort, registration) = AbortHandle::new_pair();
|
||||
let started = RealtimeWebrtcSession::start(registration, AudioDeviceSelection::default())?;
|
||||
assert_eq!(
|
||||
started.handle.apply_answer_sdp("synthetic-answer".into()),
|
||||
Err(akode_realtime_webrtc::ConnectionError::AudioDevices)
|
||||
);
|
||||
started.handle.set_microphone_muted(/*muted*/ true)?;
|
||||
assert_eq!(started.handle.take_error(), None);
|
||||
started.handle.close();
|
||||
#[cfg(unix)]
|
||||
common::wait_for_helper_reaped(&root)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_failure_reaches_offer_caller_without_native_error_text() -> Result<()> {
|
||||
let Some(root) =
|
||||
common::package("runtime_failure_reaches_offer_caller_without_native_error_text")?
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
fs::write(root.join("fail-initialization"), [])?;
|
||||
let (_abort, registration) = AbortHandle::new_pair();
|
||||
let error =
|
||||
RealtimeWebrtcSession::start(registration, AudioDeviceSelection::default()).unwrap_err();
|
||||
assert_eq!(
|
||||
error.downcast_ref::<akode_realtime_webrtc::ConnectionError>(),
|
||||
Some(&akode_realtime_webrtc::ConnectionError::RuntimeInitialization)
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{error:#}"),
|
||||
"voice audio runtime could not initialize"
|
||||
);
|
||||
#[cfg(unix)]
|
||||
common::wait_for_helper_reaped(&root)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn device_discovery_does_not_start_capture() -> Result<()> {
|
||||
let Some(root) = common::package("device_discovery_does_not_start_capture")? else {
|
||||
return Ok(());
|
||||
};
|
||||
let package = akode_install_context::InstallContext::current()
|
||||
.package_layout
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
let mut host = akode_realtime_webrtc::VoiceHost::connect(package, common::BUILD_COMMIT).await?;
|
||||
assert_eq!(
|
||||
host.list_devices(AudioDeviceKind::Input).await?,
|
||||
vec![akode_realtime_webrtc::AudioDevice {
|
||||
name: "Interface".into(),
|
||||
channels: 16,
|
||||
is_default: true,
|
||||
}]
|
||||
);
|
||||
host.close().await?;
|
||||
assert!(!root.join("initializing").exists());
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user