185 lines
5.8 KiB
Rust
185 lines
5.8 KiB
Rust
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,
|
|
};
|
|
|
|
use crate::log::macros::{error, trace};
|
|
|
|
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 {
|
|
error!("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(¶ms).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 {
|
|
trace!("receiver count is 0, idling");
|
|
listener_attach_spawned.notified().await;
|
|
}
|
|
|
|
trace!("updating cached object");
|
|
let (new_expiry, new_params) = Self::fetch_params(¶ms).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();
|
|
|
|
// let mut first = true;
|
|
loop {
|
|
let payload = {
|
|
let LeaderboardWatchedInfo {
|
|
ref expiry,
|
|
ref message,
|
|
} = *subscription.borrow_and_update();
|
|
|
|
// for testing the error message:
|
|
// if first {
|
|
// first = false;
|
|
// format!("{}\tok\t{data}", expiry.to_rfc3339())
|
|
// } else {
|
|
// format!("{}\terr\terrormessage", expiry.to_rfc3339())
|
|
// }
|
|
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 {
|
|
error!("web-socket 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(_))) => {
|
|
error!("received web-socket data, not our protocol");
|
|
break;
|
|
},
|
|
Some(Err(err)) => {
|
|
error!("web-socket receive error: {err}");
|
|
break;
|
|
}
|
|
}
|
|
},
|
|
}
|
|
}
|
|
})
|
|
}
|