Split out socket config and switch back to toml crate

basic-toml does not support externally-tagged enum yet.

See: https://github.com/dtolnay/basic-toml/issues/8
This commit is contained in:
oxalica 2024-09-09 01:26:46 -04:00
parent 4f0f1405dc
commit c5263c607c
7 changed files with 92 additions and 48 deletions

View file

@ -1,7 +1,8 @@
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Context, Result};
use blahd::config::Config;
use blahd::config::{Config, ListenConfig};
use blahd::{AppState, Database};
/// Blah Chat Server
@ -29,7 +30,7 @@ fn main() -> Result<()> {
fn parse_config(path: &std::path::Path) -> Result<Config> {
let src = std::fs::read_to_string(path)?;
let config = basic_toml::from_str::<Config>(&src)?;
let config = toml::from_str::<Config>(&src)?;
config.validate()?;
Ok(config)
}
@ -38,12 +39,11 @@ fn main() -> Result<()> {
Cli::Serve { config } => {
let config = parse_config(&config)?;
let db = Database::open(&config.database).context("failed to open database")?;
let st = AppState::new(db, config.server);
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.context("failed to initialize tokio runtime")?
.block_on(st.serve())
.block_on(main_serve(db, config))
}
Cli::Validate { config } => {
parse_config(&config)?;
@ -51,3 +51,21 @@ fn main() -> Result<()> {
}
}
}
async fn main_serve(db: Database, config: Config) -> Result<()> {
let listener = match &config.listen {
ListenConfig::Address(addr) => tokio::net::TcpListener::bind(addr)
.await
.context("failed to listen on socket")?,
};
let st = AppState::new(db, config.server);
tracing::info!("listening on {:?}", config.listen);
let router = blahd::router(Arc::new(st));
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]);
axum::serve(listener, router)
.await
.context("failed to serve")?;
Ok(())
}

View file

@ -3,7 +3,7 @@ use std::path::PathBuf;
use std::time::Duration;
use anyhow::{ensure, Result};
use serde::{Deserialize, Deserializer};
use serde::{Deserialize, Deserializer, Serialize};
use serde_inline_default::serde_inline_default;
use url::Url;
@ -11,6 +11,7 @@ use url::Url;
#[serde(deny_unknown_fields)]
pub struct Config {
pub database: DatabaseConfig,
pub listen: ListenConfig,
pub server: ServerConfig,
}
@ -25,11 +26,17 @@ pub struct DatabaseConfig {
pub create: bool,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ListenConfig {
Address(String),
// TODO: Unix socket.
}
#[serde_inline_default]
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServerConfig {
pub listen: String,
pub base_url: Url,
#[serde_inline_default(1024.try_into().expect("not zero"))]
@ -71,7 +78,7 @@ mod tests {
#[test]
fn example_config() {
let src = std::fs::read_to_string("config.example.toml").unwrap();
let config = basic_toml::from_str::<Config>(&src).unwrap();
let config = toml::from_str::<Config>(&src).unwrap();
config.validate().unwrap();
}
}

View file

@ -2,7 +2,7 @@ use std::num::NonZeroUsize;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use anyhow::{Context, Result};
use anyhow::Result;
use axum::extract::ws;
use axum::extract::{Path, Query, State, WebSocketUpgrade};
use axum::http::{header, StatusCode};
@ -57,10 +57,6 @@ impl AppState {
}
}
pub async fn serve(self) -> Result<()> {
serve(Arc::new(self)).await
}
fn verify_signed_data<T: Serialize>(&self, data: &WithSig<T>) -> Result<(), ApiError> {
let Ok(()) = data.verify() else {
return Err(error_response!(
@ -94,20 +90,6 @@ impl AppState {
type ArcState = State<Arc<AppState>>;
async fn serve(st: Arc<AppState>) -> Result<()> {
let listener = tokio::net::TcpListener::bind(&st.config.listen)
.await
.context("failed to listen on socket")?;
tracing::info!("listening on {}", st.config.listen);
let router = router(st.clone());
let _ = sd_notify::notify(true, &[sd_notify::NotifyState::Ready]);
axum::serve(listener, router)
.await
.context("failed to serve")?;
Ok(())
}
pub fn router(st: Arc<AppState>) -> Router {
Router::new()
.route("/ws", get(handle_ws))