1use std::fmt::Write as _;
7use std::time::{Duration, Instant, SystemTime};
8
9use reqwest::header::HeaderMap;
10use reqwest::{Method, StatusCode};
11
12use crate::api::duration;
13
14pub(super) const WINDOW: Duration = Duration::from_hours(1);
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Class {
21 Runs,
23 Jobs,
25 Runners,
27 JobRead,
29 Registration,
31 Delete,
33 Other,
35}
36
37impl Class {
38 pub const ALL: [Class; 7] = [
40 Class::Runs,
41 Class::Jobs,
42 Class::Runners,
43 Class::JobRead,
44 Class::Registration,
45 Class::Delete,
46 Class::Other,
47 ];
48
49 fn label(self) -> &'static str {
50 match self {
51 Class::Runs => "runs",
52 Class::Jobs => "jobs",
53 Class::Runners => "runners",
54 Class::JobRead => "job reads",
55 Class::Registration => "registrations",
56 Class::Delete => "deletes",
57 Class::Other => "other",
58 }
59 }
60
61 pub(super) fn of(method: &Method, path: &str) -> Class {
63 let path = path.split_once('?').map_or(path, |(path, _)| path);
64 let segments: Vec<&str> = path.split('/').skip(1).collect();
65 match (method.as_str(), segments.as_slice()) {
66 ("GET", ["repos", _, _, "actions", "runs"]) => Class::Runs,
67 ("GET", ["repos", _, _, "actions", "runs", _, "jobs"]) => Class::Jobs,
68 ("GET", ["repos", _, _, "actions", "runners"]) => Class::Runners,
69 ("GET", ["repos", _, _, "actions", "jobs", _]) => Class::JobRead,
70 ("POST", ["repos", _, _, "actions", "runners", "generate-jitconfig"]) => {
71 Class::Registration
72 }
73 ("DELETE", ["repos", _, _, "actions", "runners", _]) => Class::Delete,
74 _ => Class::Other,
75 }
76 }
77
78 fn index(self) -> usize {
79 self as usize
80 }
81}
82
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85pub struct Tally {
86 pub fresh: u64,
88 pub unchanged: u64,
90 pub refused: u64,
92}
93
94impl Tally {
95 pub fn total(&self) -> u64 {
97 self.fresh + self.unchanged + self.refused
98 }
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub struct RateLimit {
104 pub limit: u64,
106 pub remaining: u64,
108 pub reset: SystemTime,
110}
111
112impl RateLimit {
113 fn read(headers: &HeaderMap) -> Option<RateLimit> {
116 let resource = headers
117 .get("x-ratelimit-resource")
118 .and_then(|value| value.to_str().ok());
119 if resource.is_some_and(|resource| resource != "core") {
120 return None;
121 }
122 Some(RateLimit {
123 limit: super::header_number(headers, "x-ratelimit-limit")?,
124 remaining: super::header_number(headers, "x-ratelimit-remaining")?,
125 reset: SystemTime::UNIX_EPOCH
126 + Duration::from_secs(super::header_number(headers, "x-ratelimit-reset")?),
127 })
128 }
129}
130
131#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
134pub struct Spend {
135 pub rate_limit: Option<RateLimit>,
137 pub mutations: u64,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Report {
144 tallies: [Tally; Class::ALL.len()],
145 rate_limit: Option<RateLimit>,
146 window: Duration,
148}
149
150impl Report {
151 pub fn tally(&self, class: Class) -> Tally {
153 self.tallies[class.index()]
154 }
155
156 pub fn is_empty(&self) -> bool {
158 Class::ALL
159 .iter()
160 .all(|class| self.tally(*class).total() == 0)
161 }
162
163 pub fn rate_limit(&self) -> Option<RateLimit> {
165 self.rate_limit
166 }
167
168 pub fn window(&self) -> Duration {
170 self.window
171 }
172
173 pub fn line(&self, now: SystemTime) -> String {
176 let mut line = format!(
177 "GitHub requests in the last {}: ",
178 duration(self.window.as_secs())
179 );
180 for (nth, class) in Class::ALL.into_iter().enumerate() {
181 let tally = self.tally(class);
182 if nth > 0 {
183 line.push_str(", ");
184 }
185 let _ = write!(
186 line,
187 "{} {} ({} fresh, {} unchanged",
188 class.label(),
189 tally.total(),
190 tally.fresh,
191 tally.unchanged
192 );
193 if tally.refused > 0 {
194 let _ = write!(line, ", {} refused", tally.refused);
195 }
196 line.push(')');
197 }
198 match self.rate_limit {
199 Some(limit) => {
200 let _ = write!(
201 line,
202 "; rate limit {} of {} left, ",
203 limit.remaining, limit.limit
204 );
205 match limit.reset.duration_since(now) {
206 Ok(left) => {
207 let _ = write!(line, "resets in {}", duration(left.as_secs()));
208 }
209 Err(_) => line.push_str("reset passed"),
210 }
211 }
212 None => line.push_str("; rate limit not read"),
213 }
214 line
215 }
216}
217
218pub(super) struct Counter {
220 report: Report,
221 mutations: u64,
223 began: Instant,
224 window: Duration,
226}
227
228impl Counter {
229 pub(super) fn new(now: Instant, window: Duration) -> Counter {
230 Counter {
231 report: Report {
232 tallies: [Tally::default(); Class::ALL.len()],
233 rate_limit: None,
234 window: Duration::ZERO,
235 },
236 mutations: 0,
237 began: now,
238 window,
239 }
240 }
241
242 pub(super) fn record(&mut self, class: Class, status: StatusCode, headers: &HeaderMap) {
244 if matches!(class, Class::Registration | Class::Delete) {
245 self.mutations += 1;
246 }
247 let tally = &mut self.report.tallies[class.index()];
248 match status {
249 StatusCode::NOT_MODIFIED => tally.unchanged += 1,
250 StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS => tally.refused += 1,
251 _ => tally.fresh += 1,
252 }
253 if status != StatusCode::UNAUTHORIZED
255 && let Some(limit) = RateLimit::read(headers)
256 {
257 self.report.rate_limit = Some(limit);
258 }
259 }
260
261 pub(super) fn spend(&self) -> Spend {
263 Spend {
264 rate_limit: self.report.rate_limit,
265 mutations: self.mutations,
266 }
267 }
268
269 pub(super) fn peek(&self, now: Instant) -> Report {
271 Report {
272 window: now.saturating_duration_since(self.began),
273 ..self.report.clone()
274 }
275 }
276
277 pub(super) fn due(&mut self, now: Instant) -> Option<Report> {
279 if now.saturating_duration_since(self.began) < self.window {
280 return None;
281 }
282 Some(self.take(now))
283 }
284
285 pub(super) fn take(&mut self, now: Instant) -> Report {
287 let report = self.peek(now);
288 self.report.tallies = [Tally::default(); Class::ALL.len()];
289 self.began = now;
290 report
291 }
292}