Skip to main content

subspace_client_github/transport/
mapping.rs

1//! The mapping of a failed GitHub response to a message.
2
3use subspace_core::credentials::{Credential, Source};
4use subspace_core::http::Error;
5use subspace_core::http::status as http_status;
6
7use super::Api;
8
9/// A failed HTTP response, reduced to what the mapping reads.
10#[derive(Debug, Clone, Copy)]
11pub struct Failure<'a> {
12    pub status: u16,
13    /// `x-ratelimit-remaining`.
14    pub remaining: Option<&'a str>,
15    /// `x-ratelimit-reset`, Unix seconds.
16    pub reset: Option<&'a str>,
17    /// `Retry-After`, which GitHub sends with a secondary rate limit.
18    pub retry_after: Option<&'a str>,
19    /// GitHub's JSON `message`, or empty.
20    pub message: &'a str,
21}
22
23pub(super) fn is_rate_limit(message: &str) -> bool {
24    message.to_lowercase().contains("rate limit")
25}
26
27pub(super) fn is_sso(message: &str) -> bool {
28    let lower = message.to_lowercase();
29    message.contains("SAML")
30        || lower.contains("single sign-on")
31        || message
32            .split(|c: char| !c.is_ascii_alphanumeric())
33            .any(|word| word.eq_ignore_ascii_case("sso"))
34}
35
36pub fn status(status: u16, message: impl Into<String>) -> Error {
37    Error::Status {
38        status,
39        message: message.into(),
40    }
41}
42
43pub fn not_found() -> Error {
44    status(http_status::NOT_FOUND, "Not found on GitHub.")
45}
46
47pub fn unexpected(what: &str) -> Error {
48    status(
49        http_status::BAD_GATEWAY,
50        format!("GitHub returned an unexpected {what}."),
51    )
52}
53
54/// "; it resets at HH:MM UTC", else "; try again in a few minutes".
55pub fn reset_hint(reset: Option<&str>) -> String {
56    reset
57        .and_then(|value| value.trim().parse::<i64>().ok())
58        .filter(|seconds| *seconds > 0)
59        .and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
60        .map_or_else(
61            || "; try again in a few minutes".to_owned(),
62            |time| format!("; it resets at {} UTC", time.format("%H:%M")),
63        )
64}
65
66/// The account a message names: the signed-in or gh login, else the one
67/// asked for.
68pub fn account_label(credential: &Credential, login: Option<&str>) -> String {
69    match &credential.source {
70        Source::GhCli { login } | Source::SignedIn { login } => login.clone(),
71        _ => login.unwrap_or("the GitHub token").to_owned(),
72    }
73}
74
75/// The 401 message, naming where the rejected token came from. It keeps
76/// status 401 so `send_with_retry` retries once.
77pub fn rejected(credential: &Credential, account: &str) -> Error {
78    let message = match &credential.source {
79        Source::Environment(name) => format!("GitHub rejected the token in {name}."),
80        Source::ConfigFile(key) => format!("GitHub rejected {key} from the config file."),
81        Source::SignedIn { login } => format!(
82            "GitHub no longer accepts the sign-in for {login}. Sign in with GitHub again in Settings."
83        ),
84        _ => format!("GitHub token rejected for {account}; run gh auth login."),
85    };
86    status(http_status::UNAUTHORIZED, message)
87}
88
89/// The message of a plain 403: GitHub refusing this account one resource.
90const ACCESS_REFUSED: &str = "GitHub refused access (HTTP 403).";
91
92/// Whether `error` is a plain 403 from [`http_failure`]: GitHub refusing
93/// the account one resource, not a rate limit, an SSO requirement or a
94/// rejected credential. Work over many items can skip that item rather
95/// than stop.
96// qual:api
97pub fn is_access_refusal(error: &Error) -> bool {
98    matches!(error, Error::Status { status: http_status::FORBIDDEN, message } if message == ACCESS_REFUSED)
99}
100
101/// Maps a failed HTTP response (not 401) to a message.
102pub fn http_failure(account: &str, api: Api, failure: Failure<'_>) -> Error {
103    let Failure {
104        status: code,
105        remaining,
106        reset,
107        retry_after,
108        message,
109    } = failure;
110    if matches!(
111        code,
112        http_status::FORBIDDEN | http_status::TOO_MANY_REQUESTS
113    ) && (remaining == Some("0") || retry_after.is_some() || is_rate_limit(message))
114    {
115        return status(
116            http_status::TOO_MANY_REQUESTS,
117            format!(
118                "GitHub rate limit reached for {account}{}.",
119                reset_hint(reset)
120            ),
121        );
122    }
123    if code == http_status::FORBIDDEN && is_sso(message) {
124        return status(http_status::FORBIDDEN, message);
125    }
126    match (api, code) {
127        (Api::GraphQl, http_status::BAD_GATEWAY | http_status::GATEWAY_TIMEOUT) => status(
128            http_status::GATEWAY_TIMEOUT,
129            "GitHub took too long to answer (its 10-second query limit); try again.",
130        ),
131        (Api::Rest, http_status::NOT_FOUND) => not_found(),
132        (Api::Rest, http_status::CONFLICT) => {
133            status(http_status::CONFLICT, "GitHub reported a conflict.")
134        }
135        // Lost or missing access: kept as 403 so callers can tell it from
136        // a transient failure. Rate limits and SSO are classified above.
137        (_, http_status::FORBIDDEN) => status(http_status::FORBIDDEN, ACCESS_REFUSED),
138        _ => status(
139            http_status::BAD_GATEWAY,
140            format!("GitHub request failed (HTTP {code})."),
141        ),
142    }
143}