Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 10.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! One repository on a hub, as the transfer logic sees it: its refs, its
5//! objects and its landings, behind a small trait. Fetching, publishing and
6//! landing are written against [`Remote`], so that they run over HTTP
7//! ([`super::http`]) and, in tests, against a hub held in memory.
8
9use std::fmt;
10use std::io::{self, Read};
11
12use braid_format::{Kind, ObjectId};
13use braid_hubproto::api::{ErrorBody, LandRequest, LandResponse, MissingRequest, Refs, RepoInfo};
14use braid_hubproto::limits;
15
16use super::creds::{TokenSource, redact};
17
18/// At most this many ids go in one `lacks` request.
19pub(crate) const LACKS_BATCH: usize = limits::MAX_IDS;
20
21/// The largest request body the hub takes: 256 MiB.
22pub(crate) const MAX_BODY: u64 = limits::MAX_BODY;
23
24/// One repository on a hub: the routes of sections 4, 6 and 8 of
25/// `docs/hub.md` that moving history needs.
26pub(crate) trait Remote {
27 /// `GET …/refs`: every ref, with the op log's sequence number.
28 fn refs(&self) -> Result<Refs, HubError>;
29
30 /// `GET /v1/r/{owner}/{name}`: the repository itself.
31 fn info(&self) -> Result<RepoInfo, HubError>;
32
33 /// `HEAD …/o/{id}`: the kind of an object, or `None` when the hub does
34 /// not hold it.
35 fn kind(&self, id: &ObjectId) -> Result<Option<Kind>, HubError>;
36
37 /// `POST …/lacks`: the ids among `ids`, at most [`LACKS_BATCH`] of them,
38 /// that the hub does not store.
39 fn lacks(&self, ids: &[ObjectId]) -> Result<Vec<ObjectId>, HubError>;
40
41 /// `POST …/objects`: an object stream of exactly `len` bytes, read from
42 /// `body`. Returns how many records the hub stored.
43 fn send_objects(&self, body: &mut dyn Read, len: u64) -> Result<u64, HubError>;
44
45 /// `POST …/missing`, answered as an object stream: what a client needs
46 /// to hold `request.want`, less what `request.have` reaches.
47 fn missing(&self, request: &MissingRequest) -> Result<Box<dyn Read + '_>, HubError>;
48
49 /// `POST …/land`. Refusals the protocol names (`missing`,
50 /// `not_on_branch`) come back as [`HubError::Api`].
51 fn land(&self, request: &LandRequest) -> Result<LandResponse, HubError>;
52
53 /// The largest body an upload sends: [`MAX_BODY`], unless the client
54 /// was told to send less or the hub takes less.
55 fn max_body(&self) -> u64 {
56 MAX_BODY
57 }
58
59 /// The most ids one list of a request holds (`lacks`, `want`, `have`,
60 /// a stack): [`LACKS_BATCH`], unless the hub takes fewer.
61 fn max_ids(&self) -> usize {
62 LACKS_BATCH
63 }
64}
65
66/// Why a request to a hub failed. No variant ever holds a token, and what
67/// a hub says is shown with [`shown`].
68#[derive(Debug)]
69pub(crate) enum HubError {
70 /// The hub answered with an error: its HTTP status and its body.
71 Api {
72 /// The HTTP status.
73 status: u16,
74 /// `{"error", "detail"}`, with `ids` or `retry_after` where the
75 /// protocol adds them.
76 body: ErrorBody,
77 },
78 /// The hub refused the token the request carried (401): expired or
79 /// revoked. Where the token came from says what to do.
80 Refused {
81 /// The hub's URL.
82 hub: String,
83 /// Where the token came from.
84 source: TokenSource,
85 /// What the hub said.
86 detail: String,
87 },
88 /// The hub could not be reached, or the connection broke.
89 Transport {
90 /// The hub's URL.
91 hub: String,
92 /// What went wrong.
93 detail: String,
94 },
95 /// The hub answered something the protocol does not allow.
96 Protocol(String),
97 /// Reading or writing a body failed.
98 Io(io::Error),
99}
100
101/// Text from a hub, or from a proxy in front of it, as braid shows it:
102/// control characters escaped, so that none reaches a terminal raw, and the
103/// secret of any token in it left out.
104pub(crate) fn shown(text: &str) -> String {
105 let text = redact(text);
106 if !text.chars().any(char::is_control) {
107 return text.into_owned();
108 }
109 text.chars()
110 .map(|c| {
111 if c.is_control() {
112 c.escape_default().to_string()
113 } else {
114 c.to_string()
115 }
116 })
117 .collect()
118}
119
120impl HubError {
121 /// Whether the request may have taken effect although it failed: the
122 /// connection broke, the answer was not one, or the hub, or a proxy in
123 /// front of it, failed (5xx).
124 pub(crate) fn may_have_happened(&self) -> bool {
125 match self {
126 HubError::Api { status, .. } => *status >= 500,
127 HubError::Refused { .. } => false,
128 HubError::Transport { .. } | HubError::Protocol(_) | HubError::Io(_) => true,
129 }
130 }
131
132 /// Whether the hub refused the credentials, or wants some (401).
133 pub(crate) fn unauthorized(&self) -> bool {
134 match self {
135 HubError::Api { status, body } => *status == 401 || body.error == "unauthorized",
136 HubError::Refused { .. } => true,
137 _ => false,
138 }
139 }
140
141 /// Whether the hub asked to wait (429).
142 pub(crate) fn rate_limited(&self) -> bool {
143 matches!(self, HubError::Api { status, body } if *status == 429 || body.error == "rate_limited")
144 }
145 /// An error answer, as a hub gives it.
146 #[cfg(test)]
147 pub(crate) fn api(status: u16, error: &str, detail: impl Into<String>) -> HubError {
148 HubError::Api {
149 status,
150 body: ErrorBody {
151 error: error.to_owned(),
152 detail: detail.into(),
153 ids: Vec::new(),
154 retry_after: None,
155 head: None,
156 },
157 }
158 }
159
160 /// The protocol's error code (`missing`, `not_on_branch`, …), for an
161 /// error answer.
162 pub(crate) fn code(&self) -> Option<&str> {
163 match self {
164 HubError::Api { body, .. } => Some(&body.error),
165 HubError::Refused { .. } => Some("unauthorized"),
166 _ => None,
167 }
168 }
169
170 /// With `missing`: the objects the hub says it needs.
171 pub(crate) fn missing_ids(&self) -> &[ObjectId] {
172 match self {
173 HubError::Api { body, .. } if body.error == "missing" => &body.ids,
174 _ => &[],
175 }
176 }
177}
178
179impl fmt::Display for HubError {
180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181 match self {
182 HubError::Refused {
183 hub,
184 source,
185 detail,
186 } => {
187 let detail = shown(detail);
188 let flag = if hub == braid_hubproto::DEFAULT_HUB_URL {
189 String::new()
190 } else {
191 format!(" --hub {hub}")
192 };
193 match source {
194 TokenSource::Environment => write!(
195 f,
196 "the hub needs valid credentials ({detail}): {hub} refused BRAID_TOKEN, which expired or was revoked; set another, or unset it and run `braid login{flag}`"
197 ),
198 _ => write!(
199 f,
200 "the hub needs valid credentials ({detail}): {hub} refused the token saved for it, which expired or was revoked; run `braid login{flag}`"
201 ),
202 }
203 }
204 HubError::Api { status, body } => {
205 let detail = shown(&body.detail);
206 match (*status, body.error.as_str()) {
207 (401, _) | (_, "unauthorized") => write!(
208 f,
209 "the hub needs valid credentials ({detail}): sign in with `braid login`, or set BRAID_TOKEN"
210 ),
211 (403, _) | (_, "forbidden") => {
212 write!(f, "the hub does not allow this: {detail}")
213 }
214 (404, _) | (_, "not_found") => write!(f, "not found on the hub: {detail}"),
215 (413, _) | (_, "too_large") => write!(f, "too large for the hub: {detail}"),
216 (429, _) | (_, "rate_limited") => {
217 write!(f, "the hub is limiting requests: {detail}")?;
218 if let Some(seconds) = body.retry_after {
219 write!(f, " (try again in {seconds} seconds)")?;
220 }
221 Ok(())
222 }
223 (status, code) => {
224 write!(f, "the hub answered {status} {}: {detail}", shown(code))
225 }
226 }
227 }
228 HubError::Transport { hub, detail } => {
229 write!(f, "cannot reach the hub at {hub}: {}", shown(detail))
230 }
231 HubError::Protocol(what) => {
232 write!(f, "the hub's answer is not valid: {}", shown(what))
233 }
234 HubError::Io(err) => write!(
235 f,
236 "the transfer with the hub failed: {}",
237 shown(&err.to_string())
238 ),
239 }
240 }
241}
242
243impl std::error::Error for HubError {
244 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
245 match self {
246 HubError::Io(err) => Some(err),
247 _ => None,
248 }
249 }
250}
251
252impl From<io::Error> for HubError {
253 fn from(err: io::Error) -> Self {
254 HubError::Io(err)
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 #[test]
263 fn messages_say_what_to_do() {
264 let unauthorized = HubError::api(401, "unauthorized", "the token expired");
265 let text = unauthorized.to_string();
266 assert!(text.contains("the token expired"), "{text}");
267 assert!(text.contains("braid login"), "{text}");
268 let mut limited = HubError::api(429, "rate_limited", "slow down");
269 if let HubError::Api { body, .. } = &mut limited {
270 body.retry_after = Some(30);
271 }
272 assert!(limited.to_string().ends_with("(try again in 30 seconds)"));
273 let other = HubError::api(409, "exists", "kikocis/demo exists");
274 assert_eq!(
275 other.to_string(),
276 "the hub answered 409 exists: kikocis/demo exists"
277 );
278 assert_eq!(other.code(), Some("exists"));
279 assert!(other.missing_ids().is_empty());
280 }
281}