mod backend;
pub(crate) mod fake;
#[cfg(feature = "steam")]
pub(crate) mod real;
#[cfg(test)]
mod tests;
pub use crate::names::{is_valid_leaderboard_name, MAX_LEADERBOARD_NAME_BYTES};
pub use backend::{LeaderboardBackend, LeaderboardDisplay, LeaderboardEntry, LeaderboardSort, ScoreRange, UploadMethod, MAX_LEADERBOARD_DETAILS};
pub use fake::FakeLeaderboardFailure;
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::Duration;
use bevy_app::{App, AppExit, First, Last, Update};
use bevy_ecs::message::{MessageCursor, Messages};
use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemParam;
use bevy_time::{Real, Time};
use tracing::{info, warn};
use crate::{BackendEvent, PumpedEvents, SteamBackendRes, SteamKitSystems};
const MAX_ROWS_LIMIT: u32 = i32::MAX as u32;
#[derive(Resource, Clone, Debug)]
pub struct LeaderboardSettings {
pub timeout: Duration,
pub uploads_per_window: u32,
pub upload_window: Duration,
pub max_queued_uploads: usize,
pub max_download_rows: u32,
}
impl Default for LeaderboardSettings {
fn default() -> Self {
Self {
timeout: Duration::from_secs(30),
uploads_per_window: 10,
upload_window: Duration::from_secs(600),
max_queued_uploads: 64,
max_download_rows: 500,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LeaderboardRequestId(pub u64);
impl LeaderboardRequestId {
pub const FIRST_MANUAL: u64 = 1 << 63;
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LeaderboardInfo {
pub name: String,
pub handle: u64,
pub sort: Option<LeaderboardSort>,
pub display: Option<LeaderboardDisplay>,
pub entry_count: i32,
}
#[derive(Clone, Debug, PartialEq)]
struct UploadJob {
id: LeaderboardRequestId,
board: String,
score: i32,
details: Vec<i32>,
method: UploadMethod,
}
#[derive(Clone, Debug, PartialEq)]
struct DownloadJob {
id: LeaderboardRequestId,
board: String,
range: ScoreRange,
max_details: usize,
}
#[derive(Clone, Debug, PartialEq)]
enum Job {
Upload(UploadJob),
Download(DownloadJob),
}
impl Job {
fn id(&self) -> LeaderboardRequestId {
match self {
Job::Upload(j) => j.id,
Job::Download(j) => j.id,
}
}
fn board(&self) -> &str {
match self {
Job::Upload(j) => &j.board,
Job::Download(j) => &j.board,
}
}
}
#[derive(Debug)]
enum Op {
Find { name: String, create: bool, waiters: Vec<LeaderboardRequestId>, jobs: Vec<Job>, started: Option<Duration> },
Upload { job: UploadJob, started: Option<Duration> },
Download { job: DownloadJob, started: Option<Duration> },
}
impl Op {
fn started(&self) -> Option<Duration> {
match self {
Op::Find { started, .. } | Op::Upload { started, .. } | Op::Download { started, .. } => *started,
}
}
fn started_mut(&mut self) -> &mut Option<Duration> {
match self {
Op::Find { started, .. } | Op::Upload { started, .. } | Op::Download { started, .. } => started,
}
}
fn waiting(self) -> Vec<(LeaderboardRequestId, String)> {
match self {
Op::Find { name, waiters, jobs, .. } => waiters.into_iter().chain(jobs.iter().map(Job::id)).map(|id| (id, name.clone())).collect(),
Op::Upload { job, .. } => vec![(job.id, job.board)],
Op::Download { job, .. } => vec![(job.id, job.board)],
}
}
}
#[derive(Resource, Debug, Default)]
pub struct SteamLeaderboards {
boards: HashMap<String, LeaderboardInfo>,
next_op: u64,
ops: HashMap<u64, Op>,
ready_jobs: Vec<Job>,
upload_queue: VecDeque<UploadJob>,
upload_in_flight: Option<u64>,
upload_starts: VecDeque<Duration>,
pending: HashSet<LeaderboardRequestId>,
last_issued: u64,
cursor: MessageCursor<LeaderboardRequest>,
}
impl SteamLeaderboards {
pub fn board(&self, name: &str) -> Option<&LeaderboardInfo> {
self.boards.get(name)
}
pub fn is_pending(&self, id: LeaderboardRequestId) -> bool {
self.pending.contains(&id)
}
pub fn uploads_queued(&self) -> usize {
self.upload_queue.len()
}
pub fn upload_in_flight(&self) -> bool {
self.upload_in_flight.is_some()
}
pub fn next_id(&mut self) -> LeaderboardRequestId {
loop {
self.last_issued = if self.last_issued + 1 >= LeaderboardRequestId::FIRST_MANUAL { 1 } else { self.last_issued + 1 };
let id = LeaderboardRequestId(self.last_issued);
if !self.pending.contains(&id) {
return id;
}
}
}
fn op(&mut self) -> u64 {
self.next_op = self.next_op.wrapping_add(1);
self.next_op
}
fn has_work(&self) -> bool {
!self.ops.is_empty() || !self.ready_jobs.is_empty() || !self.upload_queue.is_empty()
}
}
#[derive(Message, Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum LeaderboardRequest {
Find {
id: LeaderboardRequestId,
name: String,
},
FindOrCreate {
id: LeaderboardRequestId,
name: String,
sort: LeaderboardSort,
display: LeaderboardDisplay,
},
UploadScore {
id: LeaderboardRequestId,
board: String,
score: i32,
details: Vec<i32>,
method: UploadMethod,
},
DownloadScores {
id: LeaderboardRequestId,
board: String,
range: ScoreRange,
max_details: usize,
},
}
impl LeaderboardRequest {
pub fn find(id: LeaderboardRequestId, name: impl Into<String>) -> Self {
Self::Find { id, name: name.into() }
}
pub fn find_or_create(id: LeaderboardRequestId, name: impl Into<String>, sort: LeaderboardSort, display: LeaderboardDisplay) -> Self {
Self::FindOrCreate { id, name: name.into(), sort, display }
}
pub fn upload(id: LeaderboardRequestId, board: impl Into<String>, score: i32, method: UploadMethod) -> Self {
Self::UploadScore { id, board: board.into(), score, details: Vec::new(), method }
}
pub fn download(id: LeaderboardRequestId, board: impl Into<String>, range: ScoreRange) -> Self {
Self::DownloadScores { id, board: board.into(), range, max_details: 0 }
}
pub fn id(&self) -> LeaderboardRequestId {
match self {
Self::Find { id, .. } | Self::FindOrCreate { id, .. } | Self::UploadScore { id, .. } | Self::DownloadScores { id, .. } => *id,
}
}
pub fn board(&self) -> &str {
match self {
Self::Find { name, .. } | Self::FindOrCreate { name, .. } => name,
Self::UploadScore { board, .. } | Self::DownloadScores { board, .. } => board,
}
}
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LeaderboardFound {
pub id: LeaderboardRequestId,
pub info: LeaderboardInfo,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScoreUploaded {
pub id: LeaderboardRequestId,
pub board: String,
pub score: i32,
pub changed: bool,
pub rank_new: i32,
pub rank_previous: i32,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ScoresDownloaded {
pub id: LeaderboardRequestId,
pub board: String,
pub range: ScoreRange,
pub entries: Vec<LeaderboardEntry>,
pub entry_count: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LeaderboardErrorKind {
NoBackend,
InvalidName,
TooManyDetails,
InvalidRange,
DuplicateId,
NotFound,
UploadRejected,
IoFailure,
TimedOut,
QueueFull,
Refused,
Exiting,
}
#[derive(Message, Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LeaderboardError {
pub id: LeaderboardRequestId,
pub board: String,
pub kind: LeaderboardErrorKind,
pub message: String,
}
pub(crate) fn build(app: &mut App, settings: &LeaderboardSettings) {
app.insert_resource(settings.clone())
.init_resource::<SteamLeaderboards>()
.add_message::<LeaderboardRequest>()
.add_message::<LeaderboardFound>()
.add_message::<ScoreUploaded>()
.add_message::<ScoresDownloaded>()
.add_message::<LeaderboardError>()
.add_systems(First, apply_leaderboard_events.in_set(SteamKitSystems::Callbacks))
.add_systems(Update, handle_leaderboard_requests.in_set(SteamKitSystems::Requests))
.add_systems(Last, answer_on_exit.in_set(SteamKitSystems::Requests));
}
#[derive(SystemParam)]
struct BoardsOut<'w> {
found: MessageWriter<'w, LeaderboardFound>,
uploaded: MessageWriter<'w, ScoreUploaded>,
downloaded: MessageWriter<'w, ScoresDownloaded>,
error: MessageWriter<'w, LeaderboardError>,
}
impl BoardsOut<'_> {
fn fail(&mut self, state: &mut SteamLeaderboards, id: LeaderboardRequestId, board: &str, kind: LeaderboardErrorKind, message: impl Into<String>) {
let message = message.into();
state.pending.remove(&id);
warn!(">>> STEAM: leaderboard {board:?} request {}: {kind:?} ({message})", id.0);
self.error.write(LeaderboardError { id, board: board.to_string(), kind, message });
}
}
fn fail_all(state: &mut SteamLeaderboards, out: &mut BoardsOut, kind: LeaderboardErrorKind, message: &str) {
let mut waiting: Vec<(LeaderboardRequestId, String)> = Vec::new();
for (_, op) in std::mem::take(&mut state.ops) {
waiting.extend(op.waiting());
}
waiting.extend(std::mem::take(&mut state.ready_jobs).into_iter().map(|j| (j.id(), j.board().to_string())));
waiting.extend(std::mem::take(&mut state.upload_queue).into_iter().map(|j| (j.id, j.board)));
state.upload_in_flight = None;
for (id, board) in waiting {
out.fail(state, id, &board, kind, message);
}
state.pending.clear();
}
fn info_of(api: &dyn LeaderboardBackend, name: &str, handle: u64) -> LeaderboardInfo {
LeaderboardInfo {
name: name.to_string(),
handle,
sort: api.leaderboard_sort(handle),
display: api.leaderboard_display(handle),
entry_count: api.leaderboard_entry_count(handle),
}
}
fn is_leaderboard_event(ev: &BackendEvent) -> bool {
matches!(
ev,
BackendEvent::LeaderboardFound { .. }
| BackendEvent::LeaderboardNotFound { .. }
| BackendEvent::LeaderboardScoreUploaded { .. }
| BackendEvent::LeaderboardUploadRejected { .. }
| BackendEvent::LeaderboardScoresDownloaded { .. }
| BackendEvent::LeaderboardIoFailure { .. }
)
}
fn apply_leaderboard_events(backend: Option<Res<SteamBackendRes>>, pumped: Res<PumpedEvents>, mut state: ResMut<SteamLeaderboards>, mut out: BoardsOut) {
let Some(api) = backend.as_ref().and_then(|b| b.0.leaderboards()) else {
let lost = pumped.0.iter().filter(|e| is_leaderboard_event(e)).count();
if lost > 0 && backend.is_none() {
warn!(">>> STEAM: backend removed before {lost} pumped leaderboard event(s) were applied - dropped");
}
return;
};
for ev in &pumped.0 {
match ev {
&BackendEvent::LeaderboardFound { op, board } => match state.ops.remove(&op) {
Some(Op::Find { name, waiters, jobs, .. }) => {
let info = info_of(api, &name, board);
info!(">>> STEAM: leaderboard {name:?} found ({} entries)", info.entry_count);
state.boards.insert(name.clone(), info.clone());
for id in waiters {
state.pending.remove(&id);
out.found.write(LeaderboardFound { id, info: info.clone() });
}
state.ready_jobs.extend(jobs);
}
other => late(&mut state, op, other),
},
&BackendEvent::LeaderboardNotFound { op } => match state.ops.remove(&op) {
Some(Op::Find { name, waiters, jobs, .. }) => {
for id in waiters.into_iter().chain(jobs.iter().map(Job::id)) {
out.fail(&mut state, id, &name, LeaderboardErrorKind::NotFound, "no leaderboard with this name");
}
}
other => late(&mut state, op, other),
},
&BackendEvent::LeaderboardScoreUploaded { op, score, changed, rank_new, rank_previous } => match state.ops.remove(&op) {
Some(Op::Upload { job, .. }) => {
state.upload_in_flight = None;
state.pending.remove(&job.id);
if let Some(info) = state.boards.get_mut(&job.board) {
info.entry_count = api.leaderboard_entry_count(info.handle);
}
info!(">>> STEAM: leaderboard {:?}: score {score} uploaded (changed {changed}, rank {rank_previous} -> {rank_new})", job.board);
out.uploaded.write(ScoreUploaded { id: job.id, board: job.board, score, changed, rank_new, rank_previous });
}
other => late(&mut state, op, other),
},
&BackendEvent::LeaderboardUploadRejected { op } => match state.ops.remove(&op) {
Some(Op::Upload { job, .. }) => {
state.upload_in_flight = None;
out.fail(&mut state, job.id, &job.board, LeaderboardErrorKind::UploadRejected, "Steam did not accept the upload (no reason given)");
}
other => late(&mut state, op, other),
},
BackendEvent::LeaderboardScoresDownloaded { op, entries } => match state.ops.remove(op) {
Some(Op::Download { job, .. }) => {
let entries: Vec<LeaderboardEntry> =
entries.iter().map(|e| LeaderboardEntry { details: e.details.iter().copied().take(job.max_details).collect(), ..e.clone() }).collect();
let entry_count = state.boards.get(&job.board).map_or(0, |i| api.leaderboard_entry_count(i.handle));
if let Some(info) = state.boards.get_mut(&job.board) {
info.entry_count = entry_count;
}
state.pending.remove(&job.id);
out.downloaded.write(ScoresDownloaded { id: job.id, board: job.board, range: job.range, entries, entry_count });
}
other => late(&mut state, *op, other),
},
&BackendEvent::LeaderboardIoFailure { op } => match state.ops.remove(&op) {
Some(o) => {
if matches!(o, Op::Upload { .. }) {
state.upload_in_flight = None;
}
for (id, board) in o.waiting() {
out.fail(&mut state, id, &board, LeaderboardErrorKind::IoFailure, "Steam answered IOFailure");
}
}
None => late(&mut state, op, None),
},
#[allow(unreachable_patterns)]
_ => {}
}
}
}
fn late(state: &mut SteamLeaderboards, op: u64, other: Option<Op>) {
match other {
Some(o) => {
state.ops.insert(op, o);
}
None => info!(">>> STEAM: late leaderboard answer for a given-up call - dropped"),
}
}
fn validate(req: &LeaderboardRequest, settings: &LeaderboardSettings, state: &mut SteamLeaderboards, out: &mut BoardsOut) -> bool {
let (id, board) = (req.id(), req.board().to_string());
if state.pending.contains(&id) {
warn!(">>> STEAM: leaderboard request id {} is still pending", id.0);
out.error.write(LeaderboardError {
id,
board,
kind: LeaderboardErrorKind::DuplicateId,
message: "rejected: a request with this id is still pending (that one still gets its own answer)".into(),
});
return false;
}
if !is_valid_leaderboard_name(&board) {
out.fail(
state,
id,
&board,
LeaderboardErrorKind::InvalidName,
format!("invalid leaderboard name (empty, over {MAX_LEADERBOARD_NAME_BYTES} bytes, or a NUL byte)"),
);
return false;
}
match req {
LeaderboardRequest::UploadScore { details, .. } if details.len() > MAX_LEADERBOARD_DETAILS => {
out.fail(state, id, &board, LeaderboardErrorKind::TooManyDetails, format!("{} details (max {MAX_LEADERBOARD_DETAILS})", details.len()));
false
}
LeaderboardRequest::DownloadScores { max_details, .. } if *max_details > MAX_LEADERBOARD_DETAILS => {
out.fail(state, id, &board, LeaderboardErrorKind::TooManyDetails, format!("max_details {max_details} (max {MAX_LEADERBOARD_DETAILS})"));
false
}
LeaderboardRequest::DownloadScores { range, .. } if !range_ok(*range, settings.max_download_rows) => {
out.fail(state, id, &board, LeaderboardErrorKind::InvalidRange, format!("unusable range {range:?}"));
false
}
_ => true,
}
}
pub(crate) fn range_ok(range: ScoreRange, max_rows: u32) -> bool {
let max = u64::from(max_rows.clamp(1, MAX_ROWS_LIMIT));
match range {
ScoreRange::Global { first, last } => first >= 1 && last >= first && last <= MAX_ROWS_LIMIT && u64::from(last - first) < max,
ScoreRange::AroundUser { before, after } => u64::from(before) + u64::from(after) < max,
ScoreRange::Friends => true,
}
}
enum FindFor {
Request(LeaderboardRequestId),
Job(Job),
}
fn find(
api: &dyn LeaderboardBackend,
now: Option<Duration>,
state: &mut SteamLeaderboards,
out: &mut BoardsOut,
name: &str,
create: Option<(LeaderboardSort, LeaderboardDisplay)>,
who: FindFor,
) {
let (waiter, job) = match who {
FindFor::Request(id) => (Some(id), None),
FindFor::Job(job) => (None, Some(job)),
};
let joined = state.ops.values_mut().find_map(|op| match op {
Op::Find { name: n, create: c, waiters, jobs, .. } if n == name && *c == create.is_some() => Some((waiters, jobs)),
_ => None,
});
if let Some((waiters, jobs)) = joined {
waiters.extend(waiter);
jobs.extend(job);
return;
}
let op = state.op();
if api.find_leaderboard(op, name, create) {
state.ops.insert(
op,
Op::Find { name: name.to_string(), create: create.is_some(), waiters: waiter.into_iter().collect(), jobs: job.into_iter().collect(), started: now },
);
} else {
for id in waiter.into_iter().chain(job.map(|j| j.id())) {
out.fail(state, id, name, LeaderboardErrorKind::Refused, "the backend refused the find");
}
}
}
fn dispatch(api: &dyn LeaderboardBackend, now: Option<Duration>, settings: &LeaderboardSettings, state: &mut SteamLeaderboards, out: &mut BoardsOut, job: Job) {
let Some(handle) = state.boards.get(job.board()).map(|i| i.handle) else {
out.fail(state, job.id(), job.board(), LeaderboardErrorKind::NotFound, "board not found");
return;
};
match job {
Job::Upload(up) => {
if state.upload_queue.len() >= settings.max_queued_uploads.max(1) {
out.fail(state, up.id, &up.board, LeaderboardErrorKind::QueueFull, "too many uploads waiting");
} else {
state.upload_queue.push_back(up);
}
}
Job::Download(down) => {
let op = state.op();
if api.download_scores(op, handle, down.range) {
state.ops.insert(op, Op::Download { job: down, started: now });
} else {
out.fail(state, down.id, &down.board, LeaderboardErrorKind::Refused, "the backend refused the download");
}
}
}
}
fn handle_leaderboard_requests(
backend: Option<Res<SteamBackendRes>>,
time: Option<Res<Time<Real>>>,
settings: Res<LeaderboardSettings>,
messages: Res<Messages<LeaderboardRequest>>,
mut state: ResMut<SteamLeaderboards>,
mut out: BoardsOut,
) {
let requests: Vec<LeaderboardRequest> = state.cursor.read(&messages).cloned().collect();
let Some(api) = backend.as_ref().and_then(|b| b.0.leaderboards()) else {
if state.has_work() {
fail_all(&mut state, &mut out, LeaderboardErrorKind::NoBackend, "Steam backend removed while this request waited");
}
for req in requests {
out.error.write(LeaderboardError {
id: req.id(),
board: req.board().to_string(),
kind: LeaderboardErrorKind::NoBackend,
message: "leaderboards: Steam is not available".into(),
});
}
return;
};
let now = time.as_ref().map(|t| t.elapsed());
if let Some(now) = now {
for op in state.ops.values_mut() {
op.started_mut().get_or_insert(now);
}
let expired: Vec<u64> =
state.ops.iter().filter(|(_, op)| op.started().is_some_and(|t| now.saturating_sub(t) >= settings.timeout)).map(|(k, _)| *k).collect();
for op in expired {
let Some(o) = state.ops.remove(&op) else { continue };
if matches!(o, Op::Upload { .. }) {
state.upload_in_flight = None;
}
for (id, board) in o.waiting() {
out.fail(&mut state, id, &board, LeaderboardErrorKind::TimedOut, "no answer from Steam in time");
}
}
}
for job in std::mem::take(&mut state.ready_jobs) {
dispatch(api, now, &settings, &mut state, &mut out, job);
}
for req in requests {
if !validate(&req, &settings, &mut state, &mut out) {
continue;
}
let id = req.id();
state.pending.insert(id);
match req {
LeaderboardRequest::Find { name, .. } | LeaderboardRequest::FindOrCreate { name, .. } if state.boards.contains_key(&name) => {
let info = state.boards[&name].clone();
state.pending.remove(&id);
out.found.write(LeaderboardFound { id, info });
}
LeaderboardRequest::Find { name, .. } => find(api, now, &mut state, &mut out, &name, None, FindFor::Request(id)),
LeaderboardRequest::FindOrCreate { name, sort, display, .. } => {
find(api, now, &mut state, &mut out, &name, Some((sort, display)), FindFor::Request(id))
}
LeaderboardRequest::UploadScore { board, score, details, method, .. } => {
let job = Job::Upload(UploadJob { id, board: board.clone(), score, details, method });
if state.boards.contains_key(&board) {
dispatch(api, now, &settings, &mut state, &mut out, job);
} else {
find(api, now, &mut state, &mut out, &board, None, FindFor::Job(job));
}
}
LeaderboardRequest::DownloadScores { board, range, max_details, .. } => {
let job = Job::Download(DownloadJob { id, board: board.clone(), range, max_details });
if state.boards.contains_key(&board) {
dispatch(api, now, &settings, &mut state, &mut out, job);
} else {
find(api, now, &mut state, &mut out, &board, None, FindFor::Job(job));
}
}
}
}
while state.upload_in_flight.is_none() {
if let Some(now) = now {
while state.upload_starts.front().is_some_and(|t| now.saturating_sub(*t) >= settings.upload_window) {
state.upload_starts.pop_front();
}
if state.upload_starts.len() >= settings.uploads_per_window.max(1) as usize {
break;
}
}
let Some(job) = state.upload_queue.pop_front() else { break };
let Some(handle) = state.boards.get(&job.board).map(|i| i.handle) else {
out.fail(&mut state, job.id, &job.board, LeaderboardErrorKind::NotFound, "board not found");
continue;
};
let op = state.op();
if api.upload_score(op, handle, job.method, job.score, &job.details) {
state.upload_in_flight = Some(op);
if let Some(now) = now {
state.upload_starts.push_back(now);
}
state.ops.insert(op, Op::Upload { job, started: now });
} else {
out.fail(&mut state, job.id, &job.board, LeaderboardErrorKind::Refused, "the backend refused the upload");
}
}
}
fn answer_on_exit(
mut exit: MessageReader<AppExit>,
backend: Option<Res<SteamBackendRes>>,
messages: Res<Messages<LeaderboardRequest>>,
mut state: ResMut<SteamLeaderboards>,
mut out: BoardsOut,
) {
if exit.read().count() == 0 {
return;
}
let late: Vec<LeaderboardRequest> = state.cursor.read(&messages).cloned().collect();
let has_backend = backend.as_ref().and_then(|b| b.0.leaderboards()).is_some();
if state.has_work() {
warn!(">>> STEAM: exiting with leaderboard requests still waiting - answered Exiting");
fail_all(&mut state, &mut out, LeaderboardErrorKind::Exiting, "the app exited before Steam answered");
}
for req in late {
let kind = if has_backend { LeaderboardErrorKind::Exiting } else { LeaderboardErrorKind::NoBackend };
out.error.write(LeaderboardError { id: req.id(), board: req.board().to_string(), kind, message: "the app exited before this request was sent".into() });
}
}