pub mod api;
pub mod auth;
mod error;
pub mod fs;
pub mod listen;
pub mod policy;
mod serve;
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
pub use listen::{Acknowledgements, Listen};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
Config(String),
#[error("token: {0}")]
Token(String),
#[error("{0}")]
Io(String),
#[error(transparent)]
Engine(#[from] loqui::Error),
}
#[derive(Debug, Clone, Default)]
pub struct ServerConfig {
pub listen: Listen,
pub acknowledgements: Acknowledgements,
pub token_file: Option<PathBuf>,
pub require_token_on_unix: bool,
pub allowed_hosts: Vec<String>,
pub public_health: bool,
pub tls_cert: Option<PathBuf>,
pub tls_key: Option<PathBuf>,
pub max_queue: Option<usize>,
pub max_connections: Option<usize>,
pub request_timeout: Option<Duration>,
}
pub struct Server {
bound: serve::Bound,
router: axum::Router,
tls: serve::Tls,
max_connections: usize,
token_source: auth::TokenSource,
listen: Listen,
}
impl Server {
pub async fn bind(config: ServerConfig, engine: loqui::Engine) -> Result<Self, Error> {
let tls_requested = config.tls_cert.is_some() || config.tls_key.is_some();
config.listen.check(config.acknowledgements, tls_requested)?;
let tls = tls_from(&config)?;
let env_token = std::env::var("LOQUI_TOKEN").ok().filter(|t| !t.is_empty()).map(zeroize::Zeroizing::new);
let generated = fs::default_token_path()
.ok_or_else(|| Error::Config("cannot find a config directory for the token; set HOME or pass --token-file".into()))?;
let tokens = auth::Tokens::resolve(config.token_file.as_deref(), env_token, &generated)?;
let token_source = tokens.source().clone();
let state = Arc::new(api::AppState {
engine,
tts_gate: api::Gate::new(config.max_queue.unwrap_or(8)),
stt_gate: api::Gate::new(config.max_queue.unwrap_or(8)),
request_timeout: config.request_timeout.unwrap_or(Duration::from_secs(120)),
});
let policy = Arc::new(policy::Policy {
tokens,
listen: config.listen.clone(),
require_token_on_unix: config.require_token_on_unix,
allowed_hosts: config.allowed_hosts.clone(),
public_health: config.public_health,
});
let router = api::router(state).layer(axum::middleware::from_fn_with_state(policy, policy::enforce));
let bound = serve::bind(&config.listen).await?;
Ok(Self { bound, router, tls, max_connections: config.max_connections.unwrap_or(64), token_source, listen: config.listen })
}
pub fn address(&self) -> String {
self.bound.describe()
}
pub fn token_source(&self) -> &auth::TokenSource {
&self.token_source
}
pub fn listen(&self) -> &Listen {
&self.listen
}
pub async fn run(self, shutdown: impl Future<Output = ()>) -> Result<(), Error> {
serve::run(self.bound, self.router, self.tls, self.max_connections, shutdown).await
}
}
#[cfg(feature = "tls")]
fn tls_from(config: &ServerConfig) -> Result<serve::Tls, Error> {
match (&config.tls_cert, &config.tls_key) {
(Some(cert), Some(key)) => Ok(Some(serve::tls_acceptor(cert, key)?)),
(None, None) => Ok(None),
_ => Err(Error::Config("--tls-cert and --tls-key go together".into())),
}
}
#[cfg(not(feature = "tls"))]
fn tls_from(config: &ServerConfig) -> Result<serve::Tls, Error> {
if config.tls_cert.is_some() || config.tls_key.is_some() {
return Err(Error::Config("TLS was requested but loqui-server was built without the `tls` feature".into()));
}
Ok(None)
}