use std::fmt::Write as _;
use std::time::{Duration, Instant, SystemTime};
use reqwest::header::HeaderMap;
use reqwest::{Method, StatusCode};
use crate::api::duration;
pub(super) const WINDOW: Duration = Duration::from_hours(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Class {
Runs,
Jobs,
Runners,
JobRead,
Registration,
Delete,
Other,
}
impl Class {
pub const ALL: [Class; 7] = [
Class::Runs,
Class::Jobs,
Class::Runners,
Class::JobRead,
Class::Registration,
Class::Delete,
Class::Other,
];
fn label(self) -> &'static str {
match self {
Class::Runs => "runs",
Class::Jobs => "jobs",
Class::Runners => "runners",
Class::JobRead => "job reads",
Class::Registration => "registrations",
Class::Delete => "deletes",
Class::Other => "other",
}
}
pub(super) fn of(method: &Method, path: &str) -> Class {
let path = path.split_once('?').map_or(path, |(path, _)| path);
let segments: Vec<&str> = path.split('/').skip(1).collect();
match (method.as_str(), segments.as_slice()) {
("GET", ["repos", _, _, "actions", "runs"]) => Class::Runs,
("GET", ["repos", _, _, "actions", "runs", _, "jobs"]) => Class::Jobs,
("GET", ["repos", _, _, "actions", "runners"]) => Class::Runners,
("GET", ["repos", _, _, "actions", "jobs", _]) => Class::JobRead,
("POST", ["repos", _, _, "actions", "runners", "generate-jitconfig"]) => {
Class::Registration
}
("DELETE", ["repos", _, _, "actions", "runners", _]) => Class::Delete,
_ => Class::Other,
}
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Tally {
pub fresh: u64,
pub unchanged: u64,
pub refused: u64,
}
impl Tally {
pub fn total(&self) -> u64 {
self.fresh + self.unchanged + self.refused
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RateLimit {
pub limit: u64,
pub remaining: u64,
pub reset: SystemTime,
}
impl RateLimit {
fn read(headers: &HeaderMap) -> Option<RateLimit> {
let resource = headers
.get("x-ratelimit-resource")
.and_then(|value| value.to_str().ok());
if resource.is_some_and(|resource| resource != "core") {
return None;
}
Some(RateLimit {
limit: super::header_number(headers, "x-ratelimit-limit")?,
remaining: super::header_number(headers, "x-ratelimit-remaining")?,
reset: SystemTime::UNIX_EPOCH
+ Duration::from_secs(super::header_number(headers, "x-ratelimit-reset")?),
})
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Spend {
pub rate_limit: Option<RateLimit>,
pub mutations: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Report {
tallies: [Tally; Class::ALL.len()],
rate_limit: Option<RateLimit>,
window: Duration,
}
impl Report {
pub fn tally(&self, class: Class) -> Tally {
self.tallies[class.index()]
}
pub fn is_empty(&self) -> bool {
Class::ALL
.iter()
.all(|class| self.tally(*class).total() == 0)
}
pub fn rate_limit(&self) -> Option<RateLimit> {
self.rate_limit
}
pub fn window(&self) -> Duration {
self.window
}
pub fn line(&self, now: SystemTime) -> String {
let mut line = format!(
"GitHub requests in the last {}: ",
duration(self.window.as_secs())
);
for (nth, class) in Class::ALL.into_iter().enumerate() {
let tally = self.tally(class);
if nth > 0 {
line.push_str(", ");
}
let _ = write!(
line,
"{} {} ({} fresh, {} unchanged",
class.label(),
tally.total(),
tally.fresh,
tally.unchanged
);
if tally.refused > 0 {
let _ = write!(line, ", {} refused", tally.refused);
}
line.push(')');
}
match self.rate_limit {
Some(limit) => {
let _ = write!(
line,
"; rate limit {} of {} left, ",
limit.remaining, limit.limit
);
match limit.reset.duration_since(now) {
Ok(left) => {
let _ = write!(line, "resets in {}", duration(left.as_secs()));
}
Err(_) => line.push_str("reset passed"),
}
}
None => line.push_str("; rate limit not read"),
}
line
}
}
pub(super) struct Counter {
report: Report,
mutations: u64,
began: Instant,
window: Duration,
}
impl Counter {
pub(super) fn new(now: Instant, window: Duration) -> Counter {
Counter {
report: Report {
tallies: [Tally::default(); Class::ALL.len()],
rate_limit: None,
window: Duration::ZERO,
},
mutations: 0,
began: now,
window,
}
}
pub(super) fn record(&mut self, class: Class, status: StatusCode, headers: &HeaderMap) {
if matches!(class, Class::Registration | Class::Delete) {
self.mutations += 1;
}
let tally = &mut self.report.tallies[class.index()];
match status {
StatusCode::NOT_MODIFIED => tally.unchanged += 1,
StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS => tally.refused += 1,
_ => tally.fresh += 1,
}
if status != StatusCode::UNAUTHORIZED
&& let Some(limit) = RateLimit::read(headers)
{
self.report.rate_limit = Some(limit);
}
}
pub(super) fn spend(&self) -> Spend {
Spend {
rate_limit: self.report.rate_limit,
mutations: self.mutations,
}
}
pub(super) fn peek(&self, now: Instant) -> Report {
Report {
window: now.saturating_duration_since(self.began),
..self.report.clone()
}
}
pub(super) fn due(&mut self, now: Instant) -> Option<Report> {
if now.saturating_duration_since(self.began) < self.window {
return None;
}
Some(self.take(now))
}
pub(super) fn take(&mut self, now: Instant) -> Report {
let report = self.peek(now);
self.report.tallies = [Tally::default(); Class::ALL.len()];
self.began = now;
report
}
}