//! The swarm's speech-to-text service. //! //! It connects to the queue as its own OIDC client, hears every agent's //! request subject (`swarm_wire::stt`), and answers each audio file with its //! transcript. [`swarm_stt::Service`] does the work: the cache, the shared //! runs and the engine. This file only reads the settings and carries //! requests between the queue and the service. use std::collections::HashSet; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::{Context as _, Result, bail}; use futures_util::StreamExt as _; use metrics::{Metrics, Outcome}; use swarm_queue_client::{ClientSecret, QueueConfig}; use swarm_secret_client::stored_secret::StoredSecret; use swarm_stt::engine::Whisper; use swarm_stt::{Config, Engine, Error, Service, cache::Cache}; use swarm_wire::stt::{Response, subject_wildcard}; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; mod metrics; /// The cert-auth role this service logs in to the store as. `swarm-bao.nix` /// writes it, matching the leaf's subject. const CERT_ROLE: &str = "swarm-stt"; /// The environment prefix `swarm-stt.nix` sets. const PREFIX: &str = "SWARM_STT"; /// The queue group every instance joins, so a request reaches one of them. const QUEUE_GROUP: &str = "swarm-stt"; /// How often expired transcripts are removed. const PURGE_EVERY: Duration = Duration::from_hours(1); /// What turns a request away when its sender already has one running. const AGENT_BUSY: &str = "you already have a transcription running; wait for it"; /// What turns a request away when every place is taken. const SERVICE_BUSY: &str = "the transcription service is busy, try again shortly"; type Var<'a> = &'a dyn Fn(&str) -> Result; type Number<'a> = &'a dyn Fn(&str, u64) -> Result; type Lookup<'a> = &'a dyn Fn(&str) -> Result; /// The setting `name`, read as `SWARM_STT_` through `get`. fn env_var(get: Lookup<'_>, name: &str) -> Result { let full = format!("{PREFIX}_{name}"); get(&full).with_context(|| format!("{full} is unset")) } /// The number in setting `name`, or `default` when it is unset. fn env_number(get: Lookup<'_>, name: &str, default: u64) -> Result { let full = format!("{PREFIX}_{name}"); match get(&full) { Ok(v) => v.parse().with_context(|| format!("{full} is not a number")), Err(_) => Ok(default), } } /// The service and the limits around it, from the environment. struct Settings { service: Arc>, cache: Cache, waiting: Arc, } fn settings(var: Var<'_>, number: Number<'_>) -> Result { let state = PathBuf::from(var("STATE_DIR")?); let cache = Cache::new( state.join("cache"), Duration::from_secs(number("CACHE_TTL_SECS", 24 * 60 * 60)?), ); let engine_timeout_secs = number("RUN_TIMEOUT_SECS", 240)?; let engine = Whisper { ffmpeg: PathBuf::from(var("FFMPEG")?), whisper: PathBuf::from(var("WHISPER_CLI")?), model: PathBuf::from(var("MODEL")?), scratch: state.join("scratch"), max_secs: number("MAX_AUDIO_SECS", 300)?, timeout: Duration::from_secs(engine_timeout_secs), }; let max_bytes = usize::try_from(number("MAX_BYTES", 6 * 1024 * 1024)?) .context("SWARM_STT_MAX_BYTES does not fit in memory")?; let service = Arc::new(Service::new(engine, cache.clone(), Config { max_bytes })); // Requests held at once, running or waiting for the engine's one slot: // each holds its audio in memory, so past this the service says it is busy. let max_waiting = number("MAX_WAITING", 3)?; let worst_wait = Duration::from_secs(max_waiting.saturating_mul(engine_timeout_secs)); if worst_wait >= swarm_wire::stt::REPLY_DEADLINE { bail!( "SWARM_STT_MAX_WAITING ({max_waiting}) times SWARM_STT_RUN_TIMEOUT_SECS \ ({engine_timeout_secs}) must stay under the {}s reply deadline, or a queued \ request is answered after its sender has given up", swarm_wire::stt::REPLY_DEADLINE.as_secs() ); } let waiting = Arc::new(Semaphore::new( usize::try_from(max_waiting).context("SWARM_STT_MAX_WAITING is too large")?, )); Ok(Settings { service, cache, waiting, }) } /// The queue connection, as the service's own OIDC client. `None` when `stop` /// fired while the secret was still being waited for. async fn connect_queue( var: Var<'_>, stop: swarm_secret_client::Shutdown, ) -> Result> { let client_id = var("OIDC_CLIENT_ID")?; let Some(secret) = swarm_secret_client::read_with_startup_retry_or_stop( "reading the queue client secret", stop.clone(), || client_secret(&client_id), ) .await? else { return Ok(None); }; let reread_id = client_id.clone(); let secret = StoredSecret::new(client_id.clone(), secret, move || { let client_id = reread_id.clone(); async move { client_secret(&client_id).await.map_err(Into::into) } }); let queue = swarm_queue_client::connect(QueueConfig { url: var("NATS_URL")?, token_endpoint: var("OIDC_TOKEN_ENDPOINT")?, client_id, client_secret: ClientSecret::Stored(secret), ca_file: std::env::var(format!("{PREFIX}_OIDC_CA_FILE")) .ok() .map(PathBuf::from), }) .await?; Ok(Some(queue)) } /// Removes expired transcripts from `cache` every [`PURGE_EVERY`], for as long as /// the process runs. fn spawn_purge(cache: Cache) { tokio::spawn(async move { loop { let removed = cache.purge().await; if removed > 0 { tracing::info!(removed, "removed expired transcripts"); } tokio::time::sleep(PURGE_EVERY).await; } }); } #[tokio::main] async fn main() -> Result<()> { let stop = swarm_secret_client::shutdown_signal(); hive_log::init(); swarm_secret_client::install_crypto_provider(); let get = |name: &str| std::env::var(name); let var = |name: &str| env_var(&get, name); let number = |name: &str, default: u64| env_number(&get, name, default); let health = swarm_secret_client::health::Health::from_env( &format!("{PREFIX}_HEALTH_ADDR"), stop.clone(), ) .await?; let Settings { service, cache, waiting, } = settings(&var, &number)?; let per_agent: Arc>> = Arc::default(); let Some(queue) = connect_queue(&var, stop.clone()).await? else { return Ok(()); }; swarm_queue_client::ready_when_connected(&health, &queue); let metrics = Arc::new(Metrics::from_env()); spawn_purge(cache); let mut requests = health.beating( queue .queue_subscribe(subject_wildcard(), QUEUE_GROUP.to_owned()) .await .context("subscribing to the request subject")? .take_until(stop.clone()), ); tracing::info!( subject = subject_wildcard(), "swarm-stt: answering requests" ); while let Some(request) = requests.next().await { let (queue, service) = (queue.clone(), Arc::clone(&service)); let metrics = Arc::clone(&metrics); // Held at once overall, and one per asking agent, so one agent // cannot fill every slot. The agent is the subject's last token. let agent = request_agent(request.subject.as_str()).to_owned(); let admission = admit(&waiting, &per_agent, &agent); tokio::spawn(async move { let Some(reply) = request.reply.clone() else { tracing::warn!(subject = %request.subject, "a request with no reply subject"); return; }; let (response, outcome, took) = respond(&service, &metrics, admission, &request.payload).await; metrics.request(outcome, took); match serde_json::to_vec(&response) { Ok(body) => { if let Err(e) = queue.publish(reply, body.into()).await { tracing::warn!(error = %e, "publishing a reply failed"); } } Err(e) => tracing::error!(error = %e, "encoding a reply failed"), } }); } if stop.peek().is_none() { bail!("the request subscription ended"); } Ok(()) } /// One agent's place among the requests in flight; dropping it frees the place. struct Slot { agents: Arc>>, agent: String, } impl Drop for Slot { fn drop(&mut self) { self.agents .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .remove(&self.agent); } } /// `agent`'s place, or `None` when it already has a request in flight. fn take_slot(agents: &Arc>>, agent: &str) -> Option { let fresh = agents .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .insert(agent.to_owned()); fresh.then(|| Slot { agents: Arc::clone(agents), agent: agent.to_owned(), }) } /// The agent a request subject names: its last token. fn request_agent(subject: &str) -> &str { subject.rsplit('.').next().unwrap_or_default() } /// What a request holds while it runs: a place among all the requests held, and /// its agent's one place. type Admission = Result<(OwnedSemaphorePermit, Slot), &'static str>; /// Held at once overall, and one per asking agent, so one agent cannot fill /// every slot. The error is what the sender is told. fn admit( waiting: &Arc, per_agent: &Arc>>, agent: &str, ) -> Admission { match ( Arc::clone(waiting).try_acquire_owned(), take_slot(per_agent, agent), ) { (Ok(permit), Some(slot)) => Ok((permit, slot)), (Ok(_), None) => Err(AGENT_BUSY), (Err(_), _) => Err(SERVICE_BUSY), } } /// The answer to one request, what came of it for the metrics, and how long /// the work took (`None` for a request turned away before any). The places /// the request held are free again when this returns. async fn respond( service: &Service, metrics: &Metrics, admission: Admission, payload: &[u8], ) -> (Response, Outcome, Option) { match admission { Ok(held) => { let count = metrics.hold(); let started = Instant::now(); let (response, outcome) = answer(service, payload).await; let took = started.elapsed(); drop((held, count)); (response, outcome, Some(took)) } Err(message) => ( Response::Failed { message: message.to_owned(), }, Outcome::Busy, None, ), } } /// The wire answer to one request's audio, and what came of it. async fn answer(service: &Service, audio: &[u8]) -> (Response, Outcome) { match service.transcribe(audio).await { Ok(reply) => { let outcome = if reply.cached { Outcome::Cached } else { Outcome::Transcribed }; ( Response::Ok { text: reply.text, cached: reply.cached, }, outcome, ) } Err(Error::Engine(message)) => { tracing::warn!(%message, "a transcription failed"); (Response::Failed { message }, Outcome::Failed) } Err(e) => ( Response::Failed { message: e.to_string(), }, Outcome::Refused, ), } } async fn client_secret(client_id: &str) -> Result { use swarm_secret_client::builder::{ClientSecret, client_secret_path}; let path = client_secret_path(client_id)?; let store = swarm_secret_client::SecretStore::from_env(CERT_ROLE) .await .context("logging in to the secret store")?; let stored: Option = store .read_optional(&path) .await .with_context(|| format!("reading {path}"))?; stored_value(&path, stored.as_ref().map(|s| s.value.as_str())) } /// The secret `stored` holds, trimmed, or the reason there is none at `path`. fn stored_value(path: &str, stored: Option<&str>) -> Result { match stored { Some(value) if !value.trim().is_empty() => Ok(value.trim().to_owned()), _ => bail!( "nothing at {path}: authelia's mint, in its container, has not \ stored this service's client secret" ), } } #[cfg(test)] mod tests { use std::collections::{HashMap, HashSet}; use std::env::VarError; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use async_trait::async_trait; use swarm_stt::Reply; use swarm_wire::stt::request_subject; use super::*; /// The environment a unit would run with: `extra` over the four settings /// that have no default, all under the `SWARM_STT_` prefix. fn environment(state: &Path, extra: &[(&str, &str)]) -> HashMap { let mut env: HashMap = [ ("STATE_DIR", state.to_str().expect("a utf-8 path")), ("FFMPEG", "/bin/ffmpeg"), ("WHISPER_CLI", "/bin/whisper-cli"), ("MODEL", "/models/small.bin"), ] .into_iter() .chain(extra.iter().copied()) .map(|(k, v)| (format!("{PREFIX}_{k}"), v.to_owned())) .collect(); env.retain(|_, v| v.as_str() != ""); env } fn lookup(env: &HashMap) -> impl Fn(&str) -> Result + '_ { move |name| env.get(name).cloned().ok_or(VarError::NotPresent) } fn build(env: &HashMap) -> Result { let get = lookup(env); let var = |name: &str| env_var(&get, name); let number = |name: &str, default: u64| env_number(&get, name, default); settings(&var, &number) } /// The text of the error `build` fails with. fn refused(env: &HashMap) -> String { build(env) .err() .expect("the settings are refused") .to_string() } #[test] fn a_setting_is_read_under_the_prefix_and_named_in_full_when_unset() { let dir = tempfile::tempdir().unwrap(); let env = environment(dir.path(), &[]); let get = lookup(&env); assert_eq!(env_var(&get, "MODEL").unwrap(), "/models/small.bin"); assert_eq!( env_var(&get, "NATS_URL").unwrap_err().to_string(), "SWARM_STT_NATS_URL is unset" ); } #[test] fn a_number_is_parsed_defaulted_when_unset_and_named_when_it_is_not_one() { let dir = tempfile::tempdir().unwrap(); let env = environment( dir.path(), &[("MAX_BYTES", "4096"), ("MAX_WAITING", "three")], ); let get = lookup(&env); assert_eq!(env_number(&get, "MAX_BYTES", 7).unwrap(), 4096); assert_eq!(env_number(&get, "RUN_TIMEOUT_SECS", 240).unwrap(), 240); assert_eq!( env_number(&get, "MAX_WAITING", 3).unwrap_err().to_string(), "SWARM_STT_MAX_WAITING is not a number" ); let not_unicode = |_: &str| -> Result { Err(VarError::NotUnicode("\u{0}".into())) }; assert_eq!(env_number(¬_unicode, "MAX_BYTES", 7).unwrap(), 7); } #[tokio::test] async fn the_defaults_hold_three_requests_and_the_limits_are_wired_to_the_service() { let dir = tempfile::tempdir().unwrap(); let s = build(&environment(dir.path(), &[("MAX_BYTES", "4")])).expect("the defaults"); assert_eq!(s.waiting.available_permits(), 3); assert!(matches!(s.service.transcribe(b"").await, Err(Error::Empty))); assert!(matches!( s.service.transcribe(b"12345").await, Err(Error::TooLarge { size: 5, max: 4 }) )); } #[tokio::test] async fn the_cache_the_service_reads_is_the_one_under_the_state_directory() { let dir = tempfile::tempdir().unwrap(); let s = build(&environment(dir.path(), &[])).expect("the defaults"); s.cache .put(&swarm_stt::cache::key(b"memo"), "hello") .await .unwrap(); assert_eq!( s.service.transcribe(b"memo").await.unwrap(), Reply { text: "hello".to_owned(), cached: true } ); assert!(dir.path().join("cache").is_dir()); } #[test] fn the_places_held_at_once_come_from_max_waiting() { let dir = tempfile::tempdir().unwrap(); let env = environment( dir.path(), &[("MAX_WAITING", "5"), ("RUN_TIMEOUT_SECS", "100")], ); assert_eq!(build(&env).unwrap().waiting.available_permits(), 5); } #[test] fn a_setting_that_is_missing_or_not_a_number_is_refused_by_name() { let dir = tempfile::tempdir().unwrap(); for name in ["STATE_DIR", "FFMPEG", "WHISPER_CLI", "MODEL"] { let env = environment(dir.path(), &[(name, "")]); assert_eq!(refused(&env), format!("SWARM_STT_{name} is unset")); } for name in [ "CACHE_TTL_SECS", "RUN_TIMEOUT_SECS", "MAX_AUDIO_SECS", "MAX_BYTES", "MAX_WAITING", ] { let env = environment(dir.path(), &[(name, "soon")]); assert_eq!(refused(&env), format!("SWARM_STT_{name} is not a number")); } } #[test] fn a_queue_deeper_than_the_reply_deadline_allows_is_refused_at_the_line() { let dir = tempfile::tempdir().unwrap(); // 3 * 300 s is the 900 s reply deadline itself. let at = environment( dir.path(), &[("MAX_WAITING", "3"), ("RUN_TIMEOUT_SECS", "300")], ); let message = refused(&at); assert!( message.starts_with("SWARM_STT_MAX_WAITING (3) times SWARM_STT_RUN_TIMEOUT_SECS (300)"), "{message}" ); assert!( message.contains("under the 900s reply deadline"), "{message}" ); let under = environment( dir.path(), &[("MAX_WAITING", "3"), ("RUN_TIMEOUT_SECS", "299")], ); assert!(build(&under).is_ok()); } #[test] fn a_product_too_big_for_a_number_is_refused_not_wrapped() { let dir = tempfile::tempdir().unwrap(); // 2^60 * 240 is a multiple of 2^64: a wrapping product is 0 and passes. for waiting in [1_u64 << 60, u64::MAX] { let waiting = waiting.to_string(); let env = environment(dir.path(), &[("MAX_WAITING", &waiting)]); assert!(refused(&env).contains("reply deadline"), "{waiting}"); } } #[test] fn the_stored_secret_is_trimmed_and_nothing_or_blank_names_the_path() { assert_eq!(stored_value("kv/x", Some(" s3cret\n")).unwrap(), "s3cret"); for stored in [None, Some(""), Some(" \n\t")] { let message = stored_value("kv/x", stored).unwrap_err().to_string(); assert!(message.starts_with("nothing at kv/x: "), "{message}"); } } #[test] fn the_agent_is_the_last_token_of_the_subject() { assert_eq!(request_agent(&request_subject("iris")), "iris"); assert_eq!(request_agent("iris"), "iris"); } #[test] fn a_request_holds_a_place_and_its_agents_and_a_second_from_one_agent_is_turned_away() { let waiting = Arc::new(Semaphore::new(2)); let agents: Arc>> = Arc::default(); let first = admit(&waiting, &agents, "iris"); assert!(first.is_ok()); assert_eq!(waiting.available_permits(), 1); let again = admit(&waiting, &agents, "iris"); assert!(matches!(again, Err(m) if m == AGENT_BUSY)); // The place the turned-away request tried is not kept. assert_eq!(waiting.available_permits(), 1); let other = admit(&waiting, &agents, "argus"); assert!(other.is_ok()); assert_eq!(waiting.available_permits(), 0); drop(first); assert_eq!(waiting.available_permits(), 1); assert!(admit(&waiting, &agents, "iris").is_ok()); drop(other); } #[test] fn with_every_place_taken_a_new_agent_is_told_the_service_is_busy_and_keeps_no_slot() { let waiting = Arc::new(Semaphore::new(1)); let agents: Arc>> = Arc::default(); let _held = admit(&waiting, &agents, "iris"); assert!(matches!(admit(&waiting, &agents, "argus"), Err(m) if m == SERVICE_BUSY)); assert!( take_slot(&agents, "argus").is_some(), "argus was not left holding a slot" ); // Both limits hit at once: the service being full is what the sender hears. assert!(matches!(admit(&waiting, &agents, "iris"), Err(m) if m == SERVICE_BUSY)); } /// Answers `heard: `, or fails, counting its runs. struct Fake { runs: Arc, fail: bool, } #[async_trait] impl Engine for Fake { async fn transcribe(&self, audio: &[u8]) -> Result { self.runs.fetch_add(1, Ordering::SeqCst); if self.fail { Err("engine broke".to_owned()) } else { Ok(format!("heard: {}", String::from_utf8_lossy(audio))) } } } fn service(dir: &Path, fail: bool) -> (Service, Arc) { let runs = Arc::new(AtomicUsize::new(0)); let engine = Fake { runs: Arc::clone(&runs), fail, }; let cache = Cache::new(dir, Duration::from_hours(24)); (Service::new(engine, cache, Config { max_bytes: 16 }), runs) } fn failed(message: &str) -> Response { Response::Failed { message: message.to_owned(), } } #[tokio::test] async fn a_new_memo_is_transcribed_and_the_same_memo_again_is_cached() { let dir = tempfile::tempdir().unwrap(); let (service, runs) = service(dir.path(), false); let (first, outcome) = answer(&service, b"memo").await; assert_eq!( first, Response::Ok { text: "heard: memo".to_owned(), cached: false } ); assert_eq!(outcome, Outcome::Transcribed); let (second, outcome) = answer(&service, b"memo").await; assert_eq!( second, Response::Ok { text: "heard: memo".to_owned(), cached: true } ); assert_eq!(outcome, Outcome::Cached); assert_eq!(runs.load(Ordering::SeqCst), 1); } #[tokio::test] async fn empty_and_oversized_audio_are_refused_with_the_reason_and_never_reach_the_engine() { let dir = tempfile::tempdir().unwrap(); let (service, runs) = service(dir.path(), false); let (empty, outcome) = answer(&service, b"").await; assert_eq!( (empty, outcome), (failed("the audio is empty"), Outcome::Refused) ); let (big, outcome) = answer(&service, &[0; 17]).await; assert_eq!( (big, outcome), ( failed("the audio is 17 bytes, over the 16 byte limit"), Outcome::Refused ) ); assert_eq!(runs.load(Ordering::SeqCst), 0); } #[tokio::test] async fn an_engine_failure_is_a_failed_answer_with_its_message_not_a_refusal() { let dir = tempfile::tempdir().unwrap(); let (service, runs) = service(dir.path(), true); let (response, outcome) = answer(&service, b"memo").await; assert_eq!( (response, outcome), (failed("engine broke"), Outcome::Failed) ); assert_eq!(runs.load(Ordering::SeqCst), 1); } #[tokio::test] async fn an_admitted_request_is_answered_timed_and_frees_its_places() { let dir = tempfile::tempdir().unwrap(); let (service, _runs) = service(dir.path(), false); let waiting = Arc::new(Semaphore::new(1)); let agents: Arc>> = Arc::default(); let admission = admit(&waiting, &agents, "iris"); assert_eq!(waiting.available_permits(), 0); let (response, outcome, took) = respond(&service, &Metrics::from_env(), admission, b"memo").await; assert_eq!( response, Response::Ok { text: "heard: memo".to_owned(), cached: false } ); assert_eq!(outcome, Outcome::Transcribed); assert!(took.is_some()); assert_eq!(waiting.available_permits(), 1); assert!(take_slot(&agents, "iris").is_some()); } #[tokio::test] async fn a_request_turned_away_is_answered_busy_untimed_and_never_runs_the_engine() { let dir = tempfile::tempdir().unwrap(); let (service, runs) = service(dir.path(), false); let (response, outcome, took) = respond(&service, &Metrics::from_env(), Err(AGENT_BUSY), b"memo").await; assert_eq!(response, failed(AGENT_BUSY)); assert_eq!(outcome, Outcome::Busy); assert_eq!(took, None); assert_eq!(runs.load(Ordering::SeqCst), 0); } #[test] fn an_agent_holds_one_slot_at_a_time_and_dropping_it_frees_it() { let agents: Arc>> = Arc::default(); let first = take_slot(&agents, "iris").expect("a free agent gets a slot"); assert!( take_slot(&agents, "iris").is_none(), "a second request is turned away" ); assert!( take_slot(&agents, "argus").is_some(), "another agent is not" ); drop(first); assert!(take_slot(&agents, "iris").is_some()); } }