Skip to main content

transitous_core/
usage.rs

1//! The usage counter: the requests of the last 24 hours, in a file shared by
2//! every process on the machine, so the CLI and the MCP server keep to the
3//! limits together.
4//!
5//! - At most [`PER_MINUTE`] requests per minute, all endpoints together.
6//! - At most `plan_daily_limit` `plan` requests per 24 hours, with a warning
7//!   from [`WARN_PERCENT`] percent on.
8//!
9//! Only requests that reach the server count: cached answers do not.
10
11use std::fs::{File, OpenOptions};
12use std::io::{Read, Seek, Write};
13use std::path::{Path, PathBuf};
14
15use jiff::Timestamp;
16use serde::{Deserialize, Serialize};
17
18use crate::Error;
19use crate::model::{EndpointUsage, UsageSummary};
20
21pub const PER_MINUTE: u32 = 20;
22pub const WARN_PERCENT: u32 = 80;
23const MINUTE: i64 = 60;
24const DAY: i64 = 24 * 60 * 60;
25
26/// An endpoint of the API.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "kebab-case")]
29pub enum Endpoint {
30    Geocode,
31    ReverseGeocode,
32    Plan,
33    Stoptimes,
34    Trip,
35}
36
37impl Endpoint {
38    pub const ALL: [Self; 5] = [
39        Self::Geocode,
40        Self::ReverseGeocode,
41        Self::Plan,
42        Self::Stoptimes,
43        Self::Trip,
44    ];
45
46    pub fn as_str(self) -> &'static str {
47        match self {
48            Self::Geocode => "geocode",
49            Self::ReverseGeocode => "reverse-geocode",
50            Self::Plan => "plan",
51            Self::Stoptimes => "stoptimes",
52            Self::Trip => "trip",
53        }
54    }
55}
56
57#[derive(Debug, Default, Serialize, Deserialize)]
58struct State {
59    requests: Vec<Entry>,
60}
61
62#[derive(Debug, Serialize, Deserialize)]
63struct Entry {
64    endpoint: Endpoint,
65    at: Timestamp,
66}
67
68/// The counter file and the limits.
69#[derive(Debug, Clone)]
70pub struct Usage {
71    path: PathBuf,
72    plan_daily_limit: u32,
73}
74
75impl Usage {
76    /// The counter `usage.json` in `state_dir`, else in the temporary
77    /// directory.
78    pub fn new(state_dir: Option<&Path>, plan_daily_limit: u32) -> Self {
79        let dir = state_dir.map_or_else(|| std::env::temp_dir().join("transitous"), Path::to_owned);
80        Self {
81            path: dir.join("usage.json"),
82            plan_daily_limit,
83        }
84    }
85
86    pub fn path(&self) -> &Path {
87        &self.path
88    }
89
90    /// Counts a request to `endpoint` at `now`, if the limits allow it.
91    /// Returns a warning when the `plan` requests near the daily limit.
92    pub fn admit(&self, endpoint: Endpoint, now: Timestamp) -> Result<Option<String>, Error> {
93        self.update(now, |state| {
94            let in_minute: Vec<&Entry> = since(state, now, MINUTE).collect();
95            if in_minute.len() >= PER_MINUTE as usize {
96                return Err(Error::RateLimited {
97                    retry_after_seconds: retry_after(in_minute[0].at, MINUTE, now),
98                });
99            }
100            let mut warning = None;
101            if endpoint == Endpoint::Plan {
102                let plans: Vec<&Entry> = since(state, now, DAY)
103                    .filter(|entry| entry.endpoint == Endpoint::Plan)
104                    .collect();
105                let used = u32::try_from(plans.len()).unwrap_or(u32::MAX);
106                if used >= self.plan_daily_limit {
107                    return Err(Error::DailyLimit {
108                        limit: self.plan_daily_limit,
109                        retry_after_seconds: plans
110                            .first()
111                            .map_or(MINUTE.unsigned_abs(), |e| retry_after(e.at, DAY, now)),
112                    });
113                }
114                let used = used + 1;
115                if u64::from(used) * 100
116                    >= u64::from(self.plan_daily_limit) * u64::from(WARN_PERCENT)
117                {
118                    warning = Some(format!(
119                        "{used} of {} plan requests in 24 hours used",
120                        self.plan_daily_limit
121                    ));
122                }
123            }
124            state.requests.push(Entry { endpoint, at: now });
125            Ok(warning)
126        })
127    }
128
129    /// The requests of the last 24 hours.
130    pub fn summary(&self, now: Timestamp) -> Result<UsageSummary, Error> {
131        self.update(now, |state| {
132            let count = |endpoint| {
133                since(state, now, DAY)
134                    .filter(|entry| entry.endpoint == endpoint)
135                    .count()
136            };
137            let plans = u32::try_from(count(Endpoint::Plan)).unwrap_or(u32::MAX);
138            Ok(UsageSummary {
139                last_24h: Endpoint::ALL
140                    .into_iter()
141                    .map(|endpoint| EndpointUsage {
142                        endpoint: endpoint.as_str().to_owned(),
143                        requests: u32::try_from(count(endpoint)).unwrap_or(u32::MAX),
144                    })
145                    .collect(),
146                last_minute: u32::try_from(since(state, now, MINUTE).count()).unwrap_or(u32::MAX),
147                per_minute_limit: PER_MINUTE,
148                plan_daily_limit: self.plan_daily_limit,
149                plan_remaining: self.plan_daily_limit.saturating_sub(plans),
150                path: self.path.display().to_string(),
151            })
152        })
153    }
154
155    /// Runs `change` on the state with the file locked, after dropping the
156    /// entries older than a day, and writes the state back.
157    fn update<T>(
158        &self,
159        now: Timestamp,
160        change: impl FnOnce(&mut State) -> Result<T, Error>,
161    ) -> Result<T, Error> {
162        let fail = |source| Error::Usage {
163            path: self.path.display().to_string(),
164            source,
165        };
166        std::fs::create_dir_all(self.path.parent().unwrap_or(Path::new(""))).map_err(fail)?;
167        let mut file = OpenOptions::new()
168            .read(true)
169            .write(true)
170            .create(true)
171            .truncate(false)
172            .open(&self.path)
173            .map_err(fail)?;
174        file.lock().map_err(fail)?;
175        let mut text = String::new();
176        file.read_to_string(&mut text).map_err(fail)?;
177        // A damaged counter starts over rather than blocking every request.
178        let mut state: State = serde_json::from_str(&text).unwrap_or_default();
179        state
180            .requests
181            .retain(|entry| now.as_second() - entry.at.as_second() < DAY);
182        let result = change(&mut state)?;
183        write(&mut file, &state).map_err(fail)?;
184        Ok(result)
185    }
186}
187
188fn write(file: &mut File, state: &State) -> std::io::Result<()> {
189    let text = serde_json::to_vec(state).map_err(std::io::Error::other)?;
190    file.set_len(0)?;
191    file.rewind()?;
192    file.write_all(&text)
193}
194
195/// The entries of the last `seconds`, oldest first.
196fn since(state: &State, now: Timestamp, seconds: i64) -> impl Iterator<Item = &Entry> {
197    state
198        .requests
199        .iter()
200        .filter(move |entry| now.as_second() - entry.at.as_second() < seconds)
201}
202
203/// Seconds until `oldest` leaves a window of `seconds`, at least one.
204fn retry_after(oldest: Timestamp, seconds: i64, now: Timestamp) -> u64 {
205    (oldest.as_second() + seconds - now.as_second())
206        .max(1)
207        .unsigned_abs()
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    fn at(second: i64) -> Timestamp {
215        Timestamp::from_second(1_800_000_000 + second).unwrap()
216    }
217
218    fn usage(limit: u32) -> (tempfile::TempDir, Usage) {
219        let dir = tempfile::tempdir().unwrap();
220        let usage = Usage::new(Some(&dir.path().join("state")), limit);
221        (dir, usage)
222    }
223
224    #[test]
225    fn allows_twenty_requests_a_minute() {
226        let (_dir, usage) = usage(720);
227        for second in 0..20 {
228            usage.admit(Endpoint::Stoptimes, at(second)).unwrap();
229        }
230        let error = usage.admit(Endpoint::Geocode, at(30)).unwrap_err();
231        assert!(
232            matches!(
233                error,
234                Error::RateLimited {
235                    retry_after_seconds: 30
236                }
237            ),
238            "{error:?}"
239        );
240        usage.admit(Endpoint::Geocode, at(60)).unwrap();
241    }
242
243    #[test]
244    fn limits_plan_requests_per_day() {
245        let (_dir, usage) = usage(5);
246        let mut warnings = Vec::new();
247        for minute in 0..5 {
248            warnings.push(usage.admit(Endpoint::Plan, at(minute * 60)).unwrap());
249        }
250        assert_eq!(warnings[..3], [None, None, None]);
251        assert_eq!(
252            warnings[3].as_deref(),
253            Some("4 of 5 plan requests in 24 hours used")
254        );
255        let error = usage.admit(Endpoint::Plan, at(3600)).unwrap_err();
256        assert!(
257            matches!(
258                error,
259                Error::DailyLimit {
260                    limit: 5,
261                    retry_after_seconds: 82_800
262                }
263            ),
264            "{error:?}"
265        );
266        // Other endpoints go on, and a day later plan does too.
267        usage.admit(Endpoint::Trip, at(3600)).unwrap();
268        usage.admit(Endpoint::Plan, at(DAY)).unwrap();
269    }
270
271    #[test]
272    fn a_zero_limit_refuses_every_plan() {
273        let (_dir, usage) = usage(0);
274        let error = usage.admit(Endpoint::Plan, at(0)).unwrap_err();
275        assert!(
276            matches!(
277                error,
278                Error::DailyLimit {
279                    retry_after_seconds: 60,
280                    ..
281                }
282            ),
283            "{error:?}"
284        );
285    }
286
287    #[test]
288    fn sums_up_the_last_day() {
289        let (_dir, usage) = usage(720);
290        usage.admit(Endpoint::Plan, at(0)).unwrap();
291        usage.admit(Endpoint::Plan, at(DAY - 100)).unwrap();
292        usage.admit(Endpoint::Geocode, at(DAY - 10)).unwrap();
293        let summary = usage.summary(at(DAY)).unwrap();
294        let counts: Vec<(&str, u32)> = summary
295            .last_24h
296            .iter()
297            .map(|e| (e.endpoint.as_str(), e.requests))
298            .collect();
299        assert_eq!(
300            counts,
301            [
302                ("geocode", 1),
303                ("reverse-geocode", 0),
304                ("plan", 1),
305                ("stoptimes", 0),
306                ("trip", 0)
307            ]
308        );
309        assert_eq!(summary.last_minute, 1);
310        assert_eq!(summary.plan_remaining, 719);
311        assert!(summary.path.ends_with("usage.json"), "{}", summary.path);
312    }
313
314    #[test]
315    fn a_damaged_counter_starts_over() {
316        let (_dir, usage) = usage(720);
317        std::fs::create_dir_all(usage.path().parent().unwrap()).unwrap();
318        std::fs::write(usage.path(), "not json").unwrap();
319        usage.admit(Endpoint::Plan, at(0)).unwrap();
320        assert_eq!(usage.summary(at(1)).unwrap().last_24h[2].requests, 1);
321    }
322
323    #[test]
324    fn reports_a_counter_it_cannot_write() {
325        let dir = tempfile::tempdir().unwrap();
326        let blocker = dir.path().join("file");
327        std::fs::write(&blocker, "").unwrap();
328        let usage = Usage::new(Some(&blocker.join("state")), 720);
329        let error = usage.admit(Endpoint::Plan, at(0)).unwrap_err();
330        assert_eq!(error.status(), "usage_error");
331        assert!(error.to_string().contains("usage counter"), "{error}");
332    }
333
334    #[test]
335    fn falls_back_to_the_temporary_directory() {
336        let usage = Usage::new(None, 720);
337        assert!(usage.path().starts_with(std::env::temp_dir()));
338    }
339}