initial commit (backend) (pending TODOs, will amend)

This commit is contained in:
2026-11-20 17:14:43 +01:00
commit 0ba7767045
16 changed files with 3303 additions and 0 deletions

117
src/args.rs Normal file
View File

@@ -0,0 +1,117 @@
use std::path::PathBuf;
pub mod typ {
use std::{fmt, net::SocketAddr, path::PathBuf, str::FromStr};
use socket_config::SocketAddr as ConfigSocketAddr;
#[derive(Debug, Clone)]
pub enum TcpOrUnixListener {
Tcp(SocketAddr),
#[cfg(target_family = "unix")]
UnixDomainSocket(PathBuf),
}
impl fmt::Display for TcpOrUnixListener {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Tcp(socket_addr) => <_ as fmt::Display>::fmt(socket_addr, f),
Self::UnixDomainSocket(path_buf) => {
<_ as fmt::Display>::fmt(&path_buf.display(), f)
}
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ListenerParseError {
#[cfg_attr(target_family = "unix", error("Address is not of IP or unix domain"))]
#[cfg_attr(not(target_family = "unix"), error("Address is not of IP"))]
NotValid,
#[error(transparent)]
ParseError(#[from] socket_config::errors::InvalidSocketAddrError),
}
impl FromStr for TcpOrUnixListener {
type Err = ListenerParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let addr = ConfigSocketAddr::from_str(s)?;
Ok(match addr {
ConfigSocketAddr::Ip { addr, port, .. } => {
Self::Tcp(SocketAddr::new(addr, port.unwrap_or(8080)))
}
#[cfg(target_family = "unix")]
ConfigSocketAddr::Unix { path, .. } => Self::UnixDomainSocket(path),
_ => return Err(Self::Err::NotValid),
})
}
}
}
/// Http server to serve information about an advent of code leaderboard.
#[derive(clap::Parser, Debug)]
#[command(version, about, long_about = None)]
#[command(styles = styles())]
pub struct Args {
/// Command
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, clap::Subcommand)]
pub enum Command {
/// Serves the website
Serve {
/// Path to the config
#[arg(short, long = "config", default_value = "config.toml")]
config_path: PathBuf,
/// Addresses to bind to
#[arg(short, long, default_values = ["0.0.0.0", "[::]:0"])]
listen: Vec<typ::TcpOrUnixListener>,
},
/// Prints an template configuration.
TemplateConfig,
/// Prints feature information
Features,
}
const fn styles() -> clap::builder::Styles {
clap::builder::Styles::styled()
.usage(
anstyle::Style::new()
.bold()
.underline()
.fg_color(Some(anstyle::Color::Ansi256(anstyle::Ansi256Color(208)))),
)
.header(
anstyle::Style::new()
.bold()
.underline()
.fg_color(Some(anstyle::Color::Ansi256(anstyle::Ansi256Color(208)))),
)
.literal(
anstyle::Style::new().fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Yellow))),
)
.invalid(
anstyle::Style::new()
.bold()
.fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Red))),
)
.error(
anstyle::Style::new()
.bold()
.fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Red))),
)
.valid(
anstyle::Style::new()
.bold()
.underline()
.fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Yellow))),
)
.placeholder(
anstyle::Style::new().fg_color(Some(anstyle::Color::Ansi(anstyle::AnsiColor::Blue))),
)
}

77
src/config.rs Normal file
View File

@@ -0,0 +1,77 @@
use std::{
fs::File,
io::{self, Read as _},
path::Path,
time::Duration,
};
#[derive(serde::Deserialize, Debug, Clone, Copy)]
#[serde(deny_unknown_fields)]
pub struct AdventConfig {
pub year: u16,
pub leaderboard: u32,
#[serde(with = "humantime_serde")]
#[serde(default = "AdventConfig::default_validity")]
pub validity: Duration,
#[serde(with = "humantime_serde")]
#[serde(default = "AdventConfig::default_fail_validity")]
pub fail_validity: Duration,
}
impl AdventConfig {
const fn default_validity() -> Duration {
Duration::from_mins(15)
}
const fn default_fail_validity() -> Duration {
Duration::from_secs(30)
}
pub async fn fetch(&self) -> reqwest::Result<String> {
if let Some(data) = option_env!("AOC_TEST_DATA") {
Ok(data.to_string())
} else {
// TODO: we are missing session cookies for aoc to reply
let res = reqwest::get(format!(
"https://adventofcode.com/{YEAR}/leaderboard/private/view/{ID}.json",
YEAR = self.year,
ID = self.leaderboard
))
.await?;
let res = res.error_for_status()?;
res.text().await
}
}
}
#[derive(serde::Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub advent: AdventConfig,
}
#[derive(Debug, thiserror::Error)]
pub enum OpenConfigError {
#[error("opening: {0}")]
Open(io::Error),
#[error("reading: {0}")]
Read(io::Error),
#[error("parsing: {0}")]
Parse(toml::de::Error),
}
impl Config {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self, OpenConfigError> {
use OpenConfigError as E;
let mut file = File::open(path).map_err(E::Open)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents).map_err(E::Read)?;
toml::from_slice(&contents).map_err(E::Parse)
}
}

61
src/main.rs Normal file
View File

@@ -0,0 +1,61 @@
use clap::Parser as _;
mod args;
mod config;
mod server;
mod consts {
pub static TEMPLATE_CFG: &str = include_str!("../data/example-config.toml");
}
fn main() -> anyhow::Result<()> {
let args = args::Args::parse();
match args.command {
args::Command::Serve {
config_path,
listen,
} => {
use server::{ServeArgs, run_server};
let config = config::Config::open(config_path)?;
println!("{config:#?}");
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
rt.block_on(async { run_server(ServeArgs { listen }, config).await })?;
}
args::Command::Features => {
let http2 = cfg!(feature = "http2");
let compress = cfg!(feature = "compress");
let http2_req = cfg!(feature = "http2-req");
let compress_req = cfg!(feature = "compress-req");
let native_tls = cfg!(feature = "native-tls");
let rustls = cfg!(feature = "rustls");
println!(
"Server Features:\
\n http2 enabled: {http2}\
\n compress enabled: {compress}\
\n\
\nRequest Features:\
\n http2-req enabled: {http2_req}\
\n compress-req enabled: {compress_req}\
\n\
\n TLS Features:\
\n native-tls enabled = {native_tls}\
\n rustls enabled = {rustls}"
);
}
args::Command::TemplateConfig => {
println!("{}", consts::TEMPLATE_CFG);
}
}
Ok(())
}

174
src/server/api.rs Normal file
View File

@@ -0,0 +1,174 @@
use std::sync::Arc;
use axum::{
extract::{State, WebSocketUpgrade, ws::Message},
response::IntoResponse,
};
use chrono::{DateTime, Utc};
use tokio::{
sync::{Notify, watch},
task::JoinHandle,
time::Instant,
};
pub struct LeaderboardWatchedInfo {
expiry: DateTime<Utc>,
message: Result<String, String>,
}
pub struct LeaderboardState {
info: watch::Sender<LeaderboardWatchedInfo>,
listener_attach: Arc<Notify>,
handle: JoinHandle<()>,
}
impl LeaderboardState {
/// Censors an error so that it is fine to send it over the network without private information
/// risk. It also takes the time to log the original error itself.
fn censor_error(err: &reqwest::Error) -> String {
eprintln!("Leaderboard fetch failed: {err:?}");
let kind = if err.is_decode() {
"decode"
} else if err.is_timeout() {
"timeout"
} else if err.is_connect() {
"connect"
} else if err.is_redirect() {
"redirect"
} else if err.is_builder() {
"builder"
} else if err.is_body() {
"body"
} else if err.is_status() {
"http"
} else if err.is_request() {
"request"
} else {
"unknown"
};
match err.status() {
Some(status) => format!("{kind} {}", status.as_u16()),
None => kind.to_owned(),
}
}
/// Fetches the leaderboard and returns the instant when the cached response expires. Failures
/// are also cached for their own amount of time.
async fn fetch_params(
params: crate::config::AdventConfig,
) -> (Instant, LeaderboardWatchedInfo) {
match params.fetch().await {
Ok(data) => (
Instant::now() + params.validity,
LeaderboardWatchedInfo {
expiry: Utc::now() + params.validity,
message: Ok(data),
},
),
Err(err) => (
Instant::now() + params.fail_validity,
LeaderboardWatchedInfo {
expiry: Utc::now() + params.fail_validity,
message: Err(Self::censor_error(&err)),
},
),
}
}
pub async fn new(params: crate::config::AdventConfig) -> Self {
let (init_expiry, info) = Self::fetch_params(params).await;
let info = watch::Sender::new(info);
let listener_attach = Arc::new(Notify::new());
let sender = info.clone();
let listener_attach_spawned = listener_attach.clone();
let handle = tokio::spawn(async move {
let mut next_expiry = init_expiry;
loop {
tokio::time::sleep_until(next_expiry).await;
while sender.receiver_count() == 0 {
eprintln!("trace: receiver count is 0, idling...");
listener_attach_spawned.notified().await;
}
eprintln!("trace: updating cached object");
let (new_expiry, new_params) = Self::fetch_params(params).await;
next_expiry = new_expiry;
_ = sender.send_replace(new_params); // returns previous
}
});
Self {
info,
listener_attach,
handle,
}
}
pub fn subscribe(&self) -> watch::Receiver<LeaderboardWatchedInfo> {
let subscription = self.info.subscribe();
self.listener_attach.notify_one();
subscription
}
}
impl Drop for LeaderboardState {
fn drop(&mut self) {
self.handle.abort();
}
}
pub async fn websocket(
State(state): State<Arc<super::AppState>>,
ws: WebSocketUpgrade,
) -> impl IntoResponse {
ws.on_upgrade(async move |mut socket| {
let mut subscription = state.leaderboard.subscribe();
loop {
let payload = {
let LeaderboardWatchedInfo {
ref expiry,
ref message,
} = *subscription.borrow_and_update();
match message {
Ok(data) => format!("{}\tok\t{data}", expiry.to_rfc3339()),
Err(err) => format!("{}\terr\t{err}", expiry.to_rfc3339()),
}
};
if let Err(err) = socket.send(Message::Text(payload.into())).await {
eprintln!("ws error: {err}");
break;
}
// so that a close message cancels the subscription about immediately
tokio::select! {
result = subscription.changed() => {
if let Err(err) = result {
panic!("leaderboard sender is closed while a request arrived ({err})");
}
},
message = socket.recv() => {
match message {
Some(Ok(Message::Close(_))) | None => break,
Some(Ok(Message::Ping(_) | Message::Pong(_))) => {},
Some(Ok(Message::Text(_) | Message::Binary(_))) => {
eprintln!("received ws data, not our protocol");
break;
},
Some(Err(err)) => {
eprintln!("ws receive error: {err}");
break;
}
}
},
}
}
})
}

70
src/server/mod.rs Normal file
View File

@@ -0,0 +1,70 @@
use std::sync::Arc;
use axum::{Router, routing};
use itertools::Itertools;
use tokio::task::JoinSet;
use tower_http::services::ServeDir;
use crate::{args, config};
mod api;
pub struct AppState {
leaderboard: api::LeaderboardState,
}
pub struct ServeArgs {
pub listen: Vec<args::typ::TcpOrUnixListener>,
}
pub async fn run_server(mut args: ServeArgs, config: config::Config) -> anyhow::Result<()> {
let app = Router::new()
.route("/api-ws", routing::get(api::websocket))
.fallback_service({
let dir_serve = ServeDir::new("static").append_index_html_on_directories(true);
#[cfg(feature = "compress")]
let dir_serve = dir_serve
.precompressed_gzip()
.precompressed_br()
.precompressed_zstd();
dir_serve
})
.with_state(Arc::new(AppState {
leaderboard: api::LeaderboardState::new(config.advent).await,
}));
#[cfg(feature = "compress")]
let app = app.layer(tower_http::compression::CompressionLayer::new());
let mut serves = JoinSet::new();
for addr in &mut args.listen {
use args::typ::TcpOrUnixListener::{Tcp, UnixDomainSocket};
use tokio::net;
match addr {
Tcp(socket_addr) => {
let tcp_listener = net::TcpListener::bind(&*socket_addr).await?;
*socket_addr = tcp_listener.local_addr()?; // if dyn port requested
let serve = axum::serve(tcp_listener, app.clone());
serves.spawn(async move { serve.await });
}
#[cfg(target_family = "unix")]
UnixDomainSocket(path_buf) => {
let uds_listener = net::UnixListener::bind(path_buf)?;
let serve = axum::serve(uds_listener, app.clone());
serves.spawn(async move { serve.await });
}
}
}
println!("listening on: {}", args.listen.iter().format(", "));
match serves.join_next().await {
Some(res) => res??,
None => anyhow::bail!("not listening in any addresses"),
}
Ok(())
}