Watch
0
0
Fork
You've already forked hyperhive
0

swarm-stt: move the settings and request handling out of main and test it

main read the environment through closures built inline and held the
per-request admission and answer inside the receive loop, so none of it
could run in a test. Each is now a function:

- env_var and env_number read through a lookup closure in place of
  std::env, and main wraps std::env::var.
- request_agent, admit and respond hold the admission and the answer of
  one request; answer takes any Engine instead of Whisper.
- stored_value holds the check on the stored client secret.

Tests run settings, admission and answers against a fake engine.

Closes #6811
This commit is contained in:
maia 2026-11-23 20:48:20 +01:00 • committed by mara
commit bceaf31f36

View file

@ -18,9 +18,9 @@ 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, Error, Service, cache::Cache};
use swarm_stt::{Config, Engine, Error, Service, cache::Cache};
use swarm_wire::stt::{Response, subject_wildcard};
use tokio::sync::Semaphore;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
mod metrics;
@ -37,8 +37,30 @@ 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<String>;
type Number<'a> = &'a dyn Fn(&str, u64) -> Result<u64>;
type Lookup<'a> = &'a dyn Fn(&str) -> Result<String, std::env::VarError>;
/// The setting `name`, read as `SWARM_STT_<name>` through `get`.
fn env_var(get: Lookup<'_>, name: &str) -> Result<String> {
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<u64> {
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 {
@ -140,17 +162,9 @@ async fn main() -> Result<()> {
let stop = swarm_secret_client::shutdown_signal();
hive_log::init();
swarm_secret_client::install_crypto_provider();
let var = |name: &str| {
let full = format!("{PREFIX}_{name}");
std::env::var(&full).with_context(|| format!("{full} is unset"))
};
let number = |name: &str, default: u64| -> Result<u64> {
let full = format!("{PREFIX}_{name}");
match std::env::var(&full) {
Ok(v) => v.parse().with_context(|| format!("{full} is not a number")),
Err(_) => Ok(default),
}
};
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(),
@ -187,42 +201,16 @@ async fn main() -> Result<()> {
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
.subject
.as_str()
.rsplit('.')
.next()
.unwrap_or_default()
.to_owned();
let turned_away = match (
Arc::clone(&waiting).try_acquire_owned(),
take_slot(&per_agent, &agent),
) {
(Ok(permit), Some(slot)) => Ok((permit, slot)),
(Ok(_), None) => Err("you already have a transcription running; wait for it"),
(Err(_), _) => Err("the transcription service is busy, try again shortly"),
};
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 = match turned_away {
Ok(held) => {
let count = metrics.hold();
let started = Instant::now();
let (response, outcome) = answer(&service, &request.payload).await;
metrics.request(outcome, Some(started.elapsed()));
drop((held, count));
response
}
Err(message) => {
metrics.request(Outcome::Busy, None);
Response::Failed {
message: message.to_owned(),
}
}
};
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 {
@ -266,8 +254,62 @@ fn take_slot(agents: &Arc<Mutex<HashSet<String>>>, agent: &str) -> Option<Slot>
})
}
/// 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<Semaphore>,
per_agent: &Arc<Mutex<HashSet<String>>>,
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<E: Engine>(
service: &Service<E>,
metrics: &Metrics,
admission: Admission,
payload: &[u8],
) -> (Response, Outcome, Option<Duration>) {
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<Whisper>, audio: &[u8]) -> (Response, Outcome) {
async fn answer<E: Engine>(service: &Service<E>, audio: &[u8]) -> (Response, Outcome) {
match service.transcribe(audio).await {
Ok(reply) => {
let outcome = if reply.cached {
@ -307,8 +349,13 @@ async fn client_secret(client_id: &str) -> Result<String> {
.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<String> {
match stored {
Some(s) if !s.value.trim().is_empty() => Ok(s.value.trim().to_owned()),
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"
@ -318,10 +365,353 @@ async fn client_secret(client_id: &str) -> Result<String> {
#[cfg(test)]
mod tests {
use std::collections::HashSet;
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 super::take_slot;
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<String, String> {
let mut env: HashMap<String, String> = [
("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() != "<unset>");
env
}
fn lookup(env: &HashMap<String, String>) -> impl Fn(&str) -> Result<String, VarError> + '_ {
move |name| env.get(name).cloned().ok_or(VarError::NotPresent)
}
fn build(env: &HashMap<String, String>) -> Result<Settings> {
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, String>) -> 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<String, VarError> { Err(VarError::NotUnicode("\u{0}".into())) };
assert_eq!(env_number(&not_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, "<unset>")]);
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<Mutex<HashSet<String>>> = 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<Mutex<HashSet<String>>> = 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: <bytes>`, or fails, counting its runs.
struct Fake {
runs: Arc<AtomicUsize>,
fail: bool,
}
#[async_trait]
impl Engine for Fake {
async fn transcribe(&self, audio: &[u8]) -> Result<String, String> {
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<Fake>, Arc<AtomicUsize>) {
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<Mutex<HashSet<String>>> = 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() {