initial commit (backend) (pending TODOs, will amend)
This commit is contained in:
2
.codespellrc
Normal file
2
.codespellrc
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[codespell]
|
||||||
|
skip = ./target
|
||||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
target
|
||||||
|
node_modules
|
||||||
|
|
||||||
|
dist
|
||||||
|
|
||||||
|
/config.toml
|
||||||
2625
Cargo.lock
generated
Normal file
2625
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
65
Cargo.toml
Normal file
65
Cargo.toml
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
[package]
|
||||||
|
name = "aoc-srv"
|
||||||
|
description = "Server to display an advent of code leaderboard."
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license = "MIT"
|
||||||
|
repository = "https://git.etsiit-tech.club/javalsai/aoc-srv"
|
||||||
|
|
||||||
|
keywords = ["advent", "aoc", "server"]
|
||||||
|
categories = ["web-programming::http-server", "web-programming::websocket"]
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
codegen-units = 1
|
||||||
|
lto = true
|
||||||
|
opt-level = 3
|
||||||
|
panic = "abort"
|
||||||
|
strip = "symbols"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["native-tls"]
|
||||||
|
http2 = ["axum/http2"]
|
||||||
|
http2-req = ["reqwest/http2"]
|
||||||
|
# http3-req = ["reqwest/http3"] # experimental
|
||||||
|
compress = [
|
||||||
|
"tower-http/compression-br",
|
||||||
|
"tower-http/compression-gzip",
|
||||||
|
"tower-http/compression-zstd",
|
||||||
|
]
|
||||||
|
compress-req = [
|
||||||
|
"reqwest/brotli",
|
||||||
|
"reqwest/deflate",
|
||||||
|
"reqwest/gzip",
|
||||||
|
"reqwest/zstd",
|
||||||
|
]
|
||||||
|
native-tls = ["reqwest/native-tls"]
|
||||||
|
rustls = ["reqwest/rustls"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anstyle = "1"
|
||||||
|
anyhow = "1"
|
||||||
|
axum = { version = "0.8", default-features = false, features = ["ws", "http1", "tokio", "macros"] }
|
||||||
|
chrono = { version = "0.4", default-features = false, features = ["std", "now"] }
|
||||||
|
clap = { version = "4.6", features = ["derive"] }
|
||||||
|
humantime-serde = "1.1"
|
||||||
|
itertools = "0.15.0"
|
||||||
|
reqwest = { version = "0.13", default-features = false }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
socket_config = "0.1"
|
||||||
|
thiserror = "2.0"
|
||||||
|
tokio = { version = "1.54", features = ["time", "rt-multi-thread", "fs", "net"] }
|
||||||
|
toml = { version = "1.2", features = ["serde"] }
|
||||||
|
tower-http = { version = "0.7", features = ["fs"] }
|
||||||
|
|
||||||
|
[lints.clippy]
|
||||||
|
cargo = { level = "warn", priority = -1 }
|
||||||
|
multiple_crate_versions = { level = "allow" }
|
||||||
|
|
||||||
|
correctness = { level = "deny", priority = -1 }
|
||||||
|
nursery = { level = "deny", priority = -1 }
|
||||||
|
option_if_let_else = { level = "allow" }
|
||||||
|
|
||||||
|
pedantic = { level = "deny", priority = -1 }
|
||||||
|
perf = { level = "deny", priority = -1 }
|
||||||
|
style = { level = "deny", priority = -1 }
|
||||||
|
unwrap_used = "deny"
|
||||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 javalsai
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
12
data/example-config.toml
Normal file
12
data/example-config.toml
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
[advent]
|
||||||
|
# advent's year
|
||||||
|
year = YEAR_HERE
|
||||||
|
|
||||||
|
# leaderboard's ID
|
||||||
|
leaderboard = ID_HERE
|
||||||
|
|
||||||
|
# how long to retain successful leaderboard responses
|
||||||
|
# validity = "15 minutes"
|
||||||
|
|
||||||
|
# how long to retain a failed request for
|
||||||
|
# fail_validity = "30 seconds"
|
||||||
1
data/test/aoc-response.json
Normal file
1
data/test/aoc-response.json
Normal file
File diff suppressed because one or more lines are too long
5
data/test/srv-config.toml
Normal file
5
data/test/srv-config.toml
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
[advent]
|
||||||
|
year = 0
|
||||||
|
leaderboard = 0
|
||||||
|
validity = "5s"
|
||||||
|
fail_validity = "2s"
|
||||||
11
docs/README.md
Normal file
11
docs/README.md
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
# Testing
|
||||||
|
|
||||||
|
The server reads `$AOC_TEST_DATA` at compile time, if set, it will use the value of such variable instead of asking `adventofcode.com` for leaderboard data.
|
||||||
|
|
||||||
|
# Installation
|
||||||
|
|
||||||
|
You may wanna consider whether having http2/3, compression and even rustls/nativels support is worth it. This was made with an nginx proxy in mind where most of these features are not worth it. All of these are cargo features (most disabled by default) that can be tweaked.
|
||||||
|
|
||||||
|
# License
|
||||||
|
|
||||||
|
The project is licensed under the MIT license.
|
||||||
27
justfile
Normal file
27
justfile
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
hack *args:
|
||||||
|
cargo hack {{ args }} \
|
||||||
|
--feature-powerset \
|
||||||
|
--mutually-exclusive-features native-tls,rustls \
|
||||||
|
--at-least-one-of native-tls,rustls
|
||||||
|
|
||||||
|
pre-commit:
|
||||||
|
codespell
|
||||||
|
just hack check --quiet
|
||||||
|
cargo clippy
|
||||||
|
cargo fmt --check
|
||||||
|
|
||||||
|
[arg("data", short="d")]
|
||||||
|
[arg("config", short="c")]
|
||||||
|
preview data="data/test/aoc-response.json" \
|
||||||
|
config="data/test/srv-config.toml" \
|
||||||
|
port="8080":
|
||||||
|
AOC_TEST_DATA="$(cat '{{ data }}')" \
|
||||||
|
cargo run -- serve -c '{{ config }}' -l '[::]:{{ port }}'
|
||||||
|
|
||||||
|
release:
|
||||||
|
RUSTFLAGS="\
|
||||||
|
-Z fmt-debug=none \
|
||||||
|
-C link-arg=-fuse-ld=lld \
|
||||||
|
-C force-unwind-tables=no \
|
||||||
|
" \
|
||||||
|
cargo build --release
|
||||||
117
src/args.rs
Normal file
117
src/args.rs
Normal 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
77
src/config.rs
Normal 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
61
src/main.rs
Normal 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
174
src/server/api.rs
Normal 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
70
src/server/mod.rs
Normal 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(())
|
||||||
|
}
|
||||||
29
static/index.html
Normal file
29
static/index.html
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Test</title>
|
||||||
|
<!-- <link href="css/style.css" rel="stylesheet"> -->
|
||||||
|
<script>
|
||||||
|
window.onload = () => {
|
||||||
|
let lb = document.getElementById("leaderboard")
|
||||||
|
lb.textContent = ""
|
||||||
|
|
||||||
|
const sock = new WebSocket("/api-ws")
|
||||||
|
|
||||||
|
sock.addEventListener("open", event => {
|
||||||
|
// if loader, remove here
|
||||||
|
})
|
||||||
|
|
||||||
|
sock.addEventListener("message", event => {
|
||||||
|
lb.textContent = event.data
|
||||||
|
})
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>leaderboard:</h1>
|
||||||
|
<pre id="leaderboard">Please enable JavaScript</pre>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user