ostrya_remote/session/pull_session.rs
1//! The session of a pull over either transport: the HTTP fetcher or a stream
2//! session.
3
4use std::io;
5
6use futures_io::{AsyncRead, AsyncWrite};
7use futures_lite::io::AsyncReadExt;
8use ostrya_core::RefSelector;
9use ostrya_fetch::{FetchRequest, Fetched, Fetcher, Priority};
10
11use super::pull::{PullBody, StreamSession, StreamSessionOptions, wire_entries};
12use crate::error::{Error, Result};
13use crate::proto::{ListRefsRequest, MAX_REF_LISTING};
14
15/// The cap on the `summary` and the `summary.sig` that
16/// [`PullSession::fetch_summary`] reads: 64 MiB.
17const MAX_SUMMARY_FILE: u64 = 64 * 1024 * 1024;
18
19/// The largest chunk of one read of a body: 128 KiB.
20const READ_CHUNK: usize = 128 * 1024;
21
22/// The path of the summary at the repository root.
23const SUMMARY_FILE: &str = "summary";
24
25/// The path of the signature of the summary at the repository root.
26const SUMMARY_SIG_FILE: &str = "summary.sig";
27
28/// The path of the ref listing of an ostrya server, under the base URL of
29/// each mirror.
30const REFS_PATH: &str = "_ostrya/refs/v1";
31
32/// The longest request target of a ref listing that the client sends:
33/// 16 KiB.
34///
35/// The target is [`REFS_PATH`], `?`, and the encoded query. The base path of
36/// the mirror comes before it on the wire, so the target that the server
37/// gets is longer.
38///
39/// An HTTP/2 server of ostrya takes a header list of at most 32 KiB. The list
40/// counts the base path, the other header fields, and 32 bytes for each
41/// field. A target that the client accepts fits in this list, with 16 KiB
42/// left for the base path and the other fields.
43const MAX_REFS_TARGET: usize = 16 * 1024;
44
45/// The key of each pair of the query of a ref listing that holds an entry of
46/// the local refs.
47const PATTERN_KEY: &str = "pattern=";
48
49/// The key of each pair of the query of a ref listing that holds an entry of
50/// the collection refs.
51const COLLECTION_KEY: &str = "collection=";
52
53/// Returns `true` if an HTTP answer with `status` marks an optional file of a
54/// pull absent: 403, 404, and 410.
55///
56/// A pull reads the optional files of a remote by this rule:
57/// `summary.sig`, `summary`, the ref listing, a ref file, the delta index, a
58/// superblock, a `.commitmeta`, and a commit that the pull can do without.
59/// A remote that keeps files from a client can answer 403 for a file that it
60/// does not hold, and a remote can answer 410 for a file that it removed.
61/// Each other status is an error, also 401.
62///
63/// ```
64/// use ostrya_remote::session::is_absent_status;
65///
66/// assert!(is_absent_status(403));
67/// assert!(is_absent_status(404));
68/// assert!(is_absent_status(410));
69/// assert!(!is_absent_status(401));
70/// ```
71pub const fn is_absent_status(status: u16) -> bool {
72 matches!(status, 403 | 404 | 410)
73}
74
75/// The session of a pull: the HTTP fetcher of a remote, or a stream session.
76///
77/// [`connect`](PullSession::connect) opens a session to an
78/// [`Endpoint`](crate::transport::Endpoint), and
79/// [`over_stream`](PullSession::over_stream) opens one over a pair of byte
80/// streams. The session is `Send + Sync`.
81/// [`fetch_summary`](PullSession::fetch_summary) and
82/// [`fetch_refs`](PullSession::fetch_refs) take `&self`, so the session stays
83/// usable after the read.
84///
85/// To read a raw file of the remote, a caller matches on the variant and
86/// uses the call of that variant: [`Fetcher::fetch`] for
87/// [`Http`](PullSession::Http), and [`StreamSession::get`] for
88/// [`Stream`](PullSession::Stream).
89///
90/// # Ref patterns
91///
92/// [`fetch_refs`](PullSession::fetch_refs) and [`StreamSession::list_refs`]
93/// send the entries of two [`RefSelector`] values. [`RefSelector`] and
94/// [`RefPattern`] give the pattern language.
95///
96/// - The first selector selects the local refs by name. In field 0, the
97/// listing holds the local refs that it selects, so a selector with no
98/// entry lists all local refs.
99/// - The second selector selects the collection refs by `ID/NAME`, for
100/// example `org.example.Os/stable` or `org.example.Os/**`. The listing
101/// holds the collection refs that it selects under
102/// `ostree.summary.collection-map`. A selector with no entry lists all
103/// collection refs. `None` asks for no collection ref, and the listing
104/// then has the bytes of a listing of the first selector alone.
105///
106/// The server leaves out each ref that the client cannot read. A caller
107/// reads the collection refs of a listing with
108/// `Summary::parse(&listing)?.collection_map()` of the `ostrya` crate.
109///
110/// Each of the two methods sends the entries by these rules, over both
111/// transports:
112///
113/// - In each list, the positive entries come first, then the negative
114/// entries, each with its `!`.
115/// - The method removes each exact duplicate of one kind in one list and
116/// keeps the first appearance, so `["a", "!b", "a"]` sends `["a", "!b"]`.
117/// An entry of the two lists stays in each list.
118/// - The method removes no entry because another entry covers it. A positive
119/// `a` and a negative `!a` both stay, and `a` and `a/b` both stay.
120/// - At most [`MAX_REF_PATTERNS`] entries can stay, positive and negative
121/// entries of the two lists together.
122/// - Over HTTP, `Some` of a second selector with no entry goes on the wire
123/// as one `**` entry, and that entry counts toward the limit. Thus
124/// [`MAX_REF_PATTERNS`] distinct entries in the first selector and `Some`
125/// of an empty second selector are refused over HTTP, and accepted over
126/// a stream session.
127/// - An entry has at most [`MAX_REF_ENTRY_LEN`] bytes, with its `!` counted
128/// as one byte. It has at most [`MAX_REF_ENTRY_PARTS`] parts, and the `!`
129/// adds no part.
130///
131/// # Reads
132///
133/// [`fetch_summary`](PullSession::fetch_summary) and
134/// [`fetch_refs`](PullSession::fetch_refs) read each body whole into one
135/// buffer. The buffer gets the size that the remote states for the body,
136/// within the cap of the method. Each read goes into a chunk of at most
137/// 128 KiB. Over HTTP, if a body fails in transit, the method fetches it
138/// again by the rules of [`Fetcher::refetching`].
139///
140/// [`RefPattern`]: ostrya_core::RefPattern
141/// [`MAX_REF_PATTERNS`]: crate::proto::MAX_REF_PATTERNS
142/// [`MAX_REF_ENTRY_LEN`]: crate::proto::MAX_REF_ENTRY_LEN
143/// [`MAX_REF_ENTRY_PARTS`]: crate::proto::MAX_REF_ENTRY_PARTS
144pub enum PullSession {
145 /// The fetcher of an HTTP remote.
146 Http(Fetcher),
147 /// A stream session, over ssh or over a pair of byte streams.
148 Stream(StreamSession),
149}
150
151/// The open of a session over a pair of byte streams, and the calls of the
152/// session.
153impl PullSession {
154 /// Opens a stream session over a pair of byte streams.
155 ///
156 /// The call is [`StreamSession::over_stream`], and the result is
157 /// [`PullSession::Stream`].
158 ///
159 /// # Errors
160 ///
161 /// - The [`Error`] variant of the code of an `Error` message from the
162 /// server.
163 /// - [`Error::VersionUnsupported`] if the server states a version out of
164 /// `1..=PULL_PROTOCOL_VERSION`.
165 /// - [`Error::Protocol`] if the reply is a message of another kind, or if
166 /// the codec refuses a frame of the reply.
167 /// - [`Error::Protocol`] if `agent` holds a NUL byte.
168 /// - [`Error::LimitExceeded`] if the `PullHello` frame or a frame of the
169 /// reply is longer than [`MIN_FRAME_LIMIT`].
170 /// - [`Error::Io`] if a read or a write of a stream fails.
171 ///
172 /// [`StreamSession::over_stream`] gives the conditions in full.
173 ///
174 /// [`MIN_FRAME_LIMIT`]: crate::proto::MIN_FRAME_LIMIT
175 pub async fn over_stream<R, W>(
176 input: R,
177 output: W,
178 opts: StreamSessionOptions,
179 ) -> Result<PullSession>
180 where
181 R: AsyncRead + Unpin + Send + 'static,
182 W: AsyncWrite + Unpin + Send + 'static,
183 {
184 StreamSession::over_stream(input, output, opts)
185 .await
186 .map(PullSession::Stream)
187 }
188
189 /// Reads the `summary` and the `summary.sig` of the remote.
190 ///
191 /// The call returns the bytes of `summary` and of `summary.sig`, in this
192 /// order. If the remote does not serve a file, the call gives `None` for
193 /// that file. Each file has a cap of 64 MiB. The call reads each file by
194 /// the rules of [Reads](PullSession#reads).
195 ///
196 /// # Order
197 ///
198 /// Over HTTP, the call asks for `summary.sig` first and for `summary`
199 /// second, at [`Priority::High`]. This is the order of the `ostree`
200 /// command. A reply with a status that [`is_absent_status`] accepts, 403,
201 /// 404, or 410, means that the remote does not serve the file.
202 ///
203 /// Over a stream session, the two `Get` calls are in flight together, in
204 /// the same order.
205 ///
206 /// # Errors
207 ///
208 /// - [`Error::Fetch`] over HTTP if a request fails after its retries, or
209 /// if the remote answers with a status other than 200, 403, 404, and
210 /// 410. For a stated length over the cap, the inner error of the fetcher
211 /// is [`FetchTooLarge`](ostrya_fetch::Error::FetchTooLarge). For a 304
212 /// reply, the inner error is [`Fetch`](ostrya_fetch::Error::Fetch).
213 /// - [`Error::Io`] over HTTP if the read of a body fails and no refetch
214 /// applies. If a body grows past the cap, the kind is
215 /// [`FileTooLarge`](std::io::ErrorKind::FileTooLarge), and the call does
216 /// not fetch the body again.
217 /// - Each error of [`StreamSession::get`] over a stream session. A stated
218 /// length over the cap is [`Error::LimitExceeded`].
219 /// - Over a stream session, the error of the session if the read of a
220 /// body fails, as [`PullBody`] states:
221 /// - [`Error::LimitExceeded`] for a body over the cap
222 /// - [`Error::Protocol`] for a body whose length is different from its
223 /// stated length
224 /// - the variant of an `Error` message from the server after the abandon
225 /// marker
226 /// - [`Error::Io`] for a failed read
227 /// - the repeat of an earlier failure of the session
228 pub async fn fetch_summary(&self) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
229 match self {
230 PullSession::Http(fetcher) => {
231 let signature = fetch_optional(
232 fetcher,
233 FetchRequest::path(SUMMARY_SIG_FILE),
234 MAX_SUMMARY_FILE,
235 )
236 .await?;
237 let summary =
238 fetch_optional(fetcher, FetchRequest::path(SUMMARY_FILE), MAX_SUMMARY_FILE)
239 .await?;
240 Ok((summary, signature))
241 }
242 PullSession::Stream(session) => {
243 let (signature, summary) = futures_lite::future::zip(
244 read_optional(session, SUMMARY_SIG_FILE),
245 read_optional(session, SUMMARY_FILE),
246 )
247 .await;
248 Ok((summary?, signature?))
249 }
250 }
251 }
252
253 /// Reads the ref listing of `refs` and `collections` from the remote.
254 ///
255 /// The listing is a summary of the local refs that `refs` selects and of
256 /// the collection refs that `collections` selects. `None` asks for no
257 /// collection ref. The server builds the listing for this request. The
258 /// listing has a cap of [`MAX_REF_LISTING`] bytes. No signature covers
259 /// the listing, and the call verifies none.
260 ///
261 /// The call sends the entries of the two selectors by the rules of
262 /// [Ref patterns](PullSession#ref-patterns). It reads the listing by the
263 /// rules of [Reads](PullSession#reads).
264 ///
265 /// # HTTP
266 ///
267 /// The call sends a `GET` of `_ostrya/refs/v1` under the base URL of each
268 /// mirror, at [`Priority::High`]. Each entry of `refs` that stays goes
269 /// into the query as one `pattern=VALUE` pair. Then each entry of
270 /// `collections` that stays goes into the query as one `collection=VALUE`
271 /// pair. `&` separates the pairs. With no entry and with `None`, the call
272 /// sends no query. `Some` of a selector with no entry goes into the query
273 /// as the one pair `collection=**`, which selects each collection ref and
274 /// counts toward the limit of entries.
275 ///
276 /// The value is the entry with each byte outside `A-Z`, `a-z`, `0-9`,
277 /// `-`, `.`, `_`, and `~` written as `%XX`. For example, `/` is `%2F`,
278 /// `!` is `%21`, and `*` is `%2A`.
279 ///
280 /// The request target that the call builds, from `_ostrya/refs/v1` to the
281 /// end of the query, is at most 16 KiB. The base path of the mirror comes
282 /// before it on the wire. An ostrya server over HTTP/2 takes a header list
283 /// of at most 32 KiB. The other 16 KiB are for the base path and the other
284 /// header fields.
285 ///
286 /// A 404 reply comes from a remote that serves no ref listing, for example
287 /// a static file server. The call then returns `None`. A 403 and a 410
288 /// reply also give `None`, by the rule of [`is_absent_status`]. An ostrya
289 /// server answers 403 to a client that it refuses.
290 ///
291 /// # Busy server
292 ///
293 /// An ostrya server answers 503 while it builds too many listings. The
294 /// fetcher retries a 503 with its backoff and does not read
295 /// `Retry-After`. If a 503 stays after the retries, the call returns
296 /// [`Error::Fetch`].
297 ///
298 /// If the mirrors are a static mirror and a busy ostrya server:
299 ///
300 /// - The fetcher keeps the 404 of the static mirror from the first round,
301 /// and asks only the busy server again. It keeps a 403 and a 410 in the
302 /// same way.
303 /// - If the busy server answers 200 in a later round, the call returns
304 /// `Some`.
305 /// - The call returns `None` only if the busy server answers 503 to each
306 /// retry. It then returns `None` after the full backoff, because a 404
307 /// has priority over a 503.
308 ///
309 /// # Stream session
310 ///
311 /// The call is [`StreamSession::list_refs`], in the pipeline with the
312 /// `get` calls. It returns `Some` with the bytes of the listing.
313 ///
314 /// # Errors
315 ///
316 /// - [`Error::InvalidInput`] if the entries break a limit of
317 /// [Ref patterns](PullSession#ref-patterns). The call sends no request.
318 /// - [`Error::InvalidInput`] over HTTP if the request target is longer
319 /// than 16 KiB. The call sends no request.
320 /// - [`Error::Fetch`] over HTTP if a request fails after its retries, or
321 /// if the remote answers with a status other than 200, 403, 404, and
322 /// 410. For a stated length over the cap, the inner error of the fetcher
323 /// is [`FetchTooLarge`](ostrya_fetch::Error::FetchTooLarge). For a 304
324 /// reply, the inner error is [`Fetch`](ostrya_fetch::Error::Fetch).
325 /// - [`Error::Fetch`] over HTTP if the server refuses the request. The
326 /// inner error is [`HttpStatus`](ostrya_fetch::Error::HttpStatus). For
327 /// example, the status is 400 for a pattern that the server refuses, or
328 /// for a `collection` pair that a server without collection refs in its
329 /// listing does not know, and
330 /// 414 or 431 for a target that is too long for it. A server that stays
331 /// busy gives 503. An ostrya server gives 500 for a listing over
332 /// [`MAX_REF_LISTING`] bytes.
333 /// - [`Error::Io`] over HTTP if the read of the body fails and no refetch
334 /// applies. If the body grows past the cap, the kind is
335 /// [`FileTooLarge`](std::io::ErrorKind::FileTooLarge), and the call does
336 /// not fetch the body again.
337 /// - Each error of [`StreamSession::list_refs`] over a stream session. A
338 /// stated length over the cap is [`Error::LimitExceeded`]. If the server
339 /// refuses the listing for its cap, the error is also
340 /// [`Error::LimitExceeded`].
341 /// - Over a stream session, the error of the session if the read of the
342 /// body fails, as [`fetch_summary`](PullSession::fetch_summary) lists.
343 pub async fn fetch_refs(
344 &self,
345 refs: &RefSelector,
346 collections: Option<&RefSelector>,
347 ) -> Result<Option<Vec<u8>>> {
348 match self {
349 PullSession::Http(fetcher) => {
350 // A query with no `collection` pair asks for no collection
351 // ref, so a list with no entry goes as the entry `**`.
352 let every;
353 let collections = match collections {
354 Some(selector)
355 if selector.positive().is_empty() && selector.negative().is_empty() =>
356 {
357 every = RefSelector::parse(["**"]).expect("`**` is a selector entry");
358 Some(&every)
359 }
360 other => other,
361 };
362 let request = wire_entries(refs, collections)?;
363 let query = refs_query(&request)?;
364 let request = match &query {
365 Some(query) => FetchRequest::path_query(REFS_PATH, query),
366 None => FetchRequest::path(REFS_PATH),
367 };
368 fetch_optional(fetcher, request, MAX_REF_LISTING).await
369 }
370 PullSession::Stream(session) => {
371 let body = session
372 .list_refs(refs, collections, MAX_REF_LISTING)
373 .await?;
374 read_body(body, MAX_REF_LISTING).await.map(Some)
375 }
376 }
377 }
378
379 /// Returns the most requests that the session keeps in flight at one time.
380 ///
381 /// The value is at least 1. For HTTP, it is [`Fetcher::max_outstanding`].
382 /// For a stream session, it is the
383 /// [`StreamSessionOptions::max_outstanding`] of the open, or 8 if that
384 /// field is `None`.
385 pub fn max_outstanding(&self) -> usize {
386 match self {
387 PullSession::Http(fetcher) => fetcher.max_outstanding(),
388 PullSession::Stream(session) => session.max_outstanding(),
389 }
390 }
391
392 /// Ends the session.
393 ///
394 /// For HTTP, the call returns `Ok(())`. For a stream session, it is
395 /// [`StreamSession::finish`].
396 ///
397 /// # Errors
398 ///
399 /// Over a stream session, the errors of [`StreamSession::finish`]:
400 ///
401 /// - The repeat of the first failure, if the session failed.
402 /// - [`Error::InvalidInput`] if the body of a reply is not read to its
403 /// end.
404 /// - [`Error::Transport`] if the ssh client exited with a failure status
405 /// and the error of the session is [`Error::Io`].
406 pub async fn finish(self) -> Result<()> {
407 match self {
408 PullSession::Http(_) => Ok(()),
409 PullSession::Stream(session) => session.finish().await,
410 }
411 }
412}
413
414/// Returns the query of a ref listing of `request`, or `None` for a request
415/// with no entry.
416///
417/// Each entry of the local refs is one `pattern=VALUE` pair. Then each entry
418/// of the collection refs is one `collection=VALUE` pair. `&` separates the
419/// pairs. The value is the entry with each byte outside the unreserved set
420/// of URIs written as `%XX`, in upper case.
421///
422/// # Errors
423///
424/// [`Error::InvalidInput`] if the request target, [`REFS_PATH`] with `?` and
425/// the query, is longer than [`MAX_REFS_TARGET`]. The function measures the
426/// target before it builds the query.
427fn refs_query(request: &ListRefsRequest) -> Result<Option<String>> {
428 let collections = request.collections.as_deref().unwrap_or_default();
429 let pairs = || {
430 let refs = request.refs.iter().map(|entry| (PATTERN_KEY, entry));
431 refs.chain(collections.iter().map(|entry| (COLLECTION_KEY, entry)))
432 };
433 let count = request.refs.len() + collections.len();
434 if count == 0 {
435 return Ok(None);
436 }
437 let len = pairs()
438 .map(|(key, entry)| key.len() + encoded_len(entry))
439 .sum::<usize>()
440 + count
441 - 1;
442 let target = REFS_PATH.len() + 1 + len;
443 if target > MAX_REFS_TARGET {
444 return Err(Error::InvalidInput(format!(
445 "the request target of the ref listing is {target} bytes, over the limit of \
446 {MAX_REFS_TARGET}: ask for fewer or shorter patterns"
447 )));
448 }
449 let mut query = String::with_capacity(len);
450 for (n, (key, entry)) in pairs().enumerate() {
451 if n > 0 {
452 query.push('&');
453 }
454 query.push_str(key);
455 encode(entry, &mut query);
456 }
457 Ok(Some(query))
458}
459
460/// Returns `true` if `byte` is in the unreserved set of URIs, which a query
461/// value carries without an escape.
462fn is_unreserved(byte: u8) -> bool {
463 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
464}
465
466/// Returns the length of `value` after [`encode`].
467fn encoded_len(value: &str) -> usize {
468 value
469 .bytes()
470 .map(|byte| if is_unreserved(byte) { 1 } else { 3 })
471 .sum()
472}
473
474/// Writes `value` to `out`, with each byte outside the unreserved set of URIs
475/// written as `%XX`, in upper case.
476fn encode(value: &str, out: &mut String) {
477 const HEX: &[u8; 16] = b"0123456789ABCDEF";
478 for byte in value.bytes() {
479 if is_unreserved(byte) {
480 out.push(char::from(byte));
481 } else {
482 out.push('%');
483 out.push(char::from(HEX[usize::from(byte >> 4)]));
484 out.push(char::from(HEX[usize::from(byte & 0xf)]));
485 }
486 }
487}
488
489/// Fetches `request` whole under `cap` bytes, or returns `None` if the remote
490/// answers with a status that [`is_absent_status`] accepts.
491async fn fetch_optional(
492 fetcher: &Fetcher,
493 request: FetchRequest<'_>,
494 cap: u64,
495) -> Result<Option<Vec<u8>>> {
496 match fetch_whole(fetcher, request, cap).await {
497 Ok(bytes) => Ok(Some(bytes)),
498 Err(Error::Fetch(ostrya_fetch::Error::HttpStatus { status, .. }))
499 if is_absent_status(status) =>
500 {
501 Ok(None)
502 }
503 Err(e) => Err(e),
504 }
505}
506
507/// Fetches `request` whole under `cap` bytes, at [`Priority::High`].
508///
509/// The fetcher refuses a stated `Content-Length` over the cap before it reads
510/// the body, and it stops a body that passes the cap. If a body fails in
511/// transit, the function fetches it again from the start, into a new buffer,
512/// while the retry count of the fetcher has a repeat left.
513async fn fetch_whole(fetcher: &Fetcher, request: FetchRequest<'_>, cap: u64) -> Result<Vec<u8>> {
514 let target = request.target;
515 let mut refetch = fetcher.refetching(FetchRequest {
516 priority: Priority::High,
517 max_size: Some(cap),
518 ..request
519 });
520 loop {
521 let Fetched::Body(body) = refetch.fetch().await.map_err(Error::Fetch)? else {
522 return Err(Error::Fetch(ostrya_fetch::Error::Fetch(format!(
523 "{target:?}: the remote answered 304 to an unconditional request"
524 ))));
525 };
526 let declared = body.content_length();
527 match read_whole(body, declared, cap).await {
528 Ok(out) => return Ok(out),
529 Err(e) => refetch.retry(Error::Io(e)).await?,
530 }
531 }
532}
533
534/// Reads `path` whole from `session` under [`MAX_SUMMARY_FILE`], or returns
535/// `None` if the server does not serve it.
536async fn read_optional(session: &StreamSession, path: &str) -> Result<Option<Vec<u8>>> {
537 let Some(body) = session.get(path, MAX_SUMMARY_FILE).await? else {
538 return Ok(None);
539 };
540 read_body(body, MAX_SUMMARY_FILE).await.map(Some)
541}
542
543/// Reads a stream `body` whole, with a buffer of at most `cap` bytes before
544/// the first read.
545async fn read_body(body: PullBody, cap: u64) -> Result<Vec<u8>> {
546 let declared = body.len();
547 // A failed read of a body carries the error of the session.
548 read_whole(body, declared, cap)
549 .await
550 .map_err(|e| e.downcast::<Error>().unwrap_or_else(Error::Io))
551}
552
553/// Reads `body` to its end into one buffer.
554///
555/// The size of the buffer comes from `declared`, the stated length, within
556/// `cap`. Each read goes into a chunk of at most [`READ_CHUNK`] bytes, also
557/// the read that finds the end of the body, so a buffer filled to its stated
558/// length does not grow. With a stated length, the chunk is that length
559/// plus 1, held between 4096 and [`READ_CHUNK`] bytes. With no stated length,
560/// the chunk is [`READ_CHUNK`] bytes.
561///
562/// A buffer that must grow doubles its capacity, to at most `cap`. The body
563/// stops at its cap, so the capacity of the buffer is never more than `cap`.
564async fn read_whole<R: AsyncRead + Unpin>(
565 mut body: R,
566 declared: Option<u64>,
567 cap: u64,
568) -> io::Result<Vec<u8>> {
569 let cap = usize::try_from(cap).unwrap_or(usize::MAX);
570 let declared = declared.map(|len| usize::try_from(len).unwrap_or(usize::MAX).min(cap));
571 let mut out = Vec::with_capacity(declared.unwrap_or(0));
572 let chunk_len = declared.map_or(READ_CHUNK, |len| {
573 len.saturating_add(1).clamp(4096, READ_CHUNK)
574 });
575 let mut chunk = vec![0u8; chunk_len];
576 loop {
577 let n = body.read(&mut chunk).await?;
578 if n == 0 {
579 return Ok(out);
580 }
581 let needed = out.len() + n;
582 if needed > out.capacity() {
583 let grown = out.capacity().saturating_mul(2).min(cap).max(needed);
584 out.reserve_exact(grown - out.len());
585 }
586 out.extend_from_slice(&chunk[..n]);
587 }
588}
589
590#[cfg(test)]
591mod tests {
592 use super::*;
593
594 /// 403, 404, and 410 mark an optional file absent. Each other status is
595 /// an error.
596 #[test]
597 fn the_absent_statuses_are_403_404_and_410() {
598 for status in [403, 404, 410] {
599 assert!(is_absent_status(status), "{status}");
600 }
601 for status in [200, 304, 400, 401, 405, 408, 429, 500, 503] {
602 assert!(!is_absent_status(status), "{status}");
603 }
604 }
605
606 /// A body with no stated length grows the buffer by doubling, and the
607 /// capacity stops at the cap.
608 #[test]
609 fn a_buffer_with_no_stated_length_grows_to_the_cap_at_most() {
610 for cap in [10_000usize, 4096, 1, 300_000] {
611 let bytes: Vec<u8> = (0..cap).map(|n| n as u8).collect();
612 let body = futures_lite::io::Cursor::new(bytes.clone());
613 let out = ostrya_rt::block_on(read_whole(body, None, cap as u64)).unwrap();
614 assert_eq!(out, bytes);
615 assert!(out.capacity() <= cap, "{cap}: {}", out.capacity());
616 }
617 }
618
619 /// Each byte outside the unreserved set is `%XX` in upper case, and the
620 /// measured length is the length of the result.
621 #[test]
622 fn an_entry_is_percent_encoded() {
623 let cases = [
624 ("a/b", "a%2Fb"),
625 ("A-z.0_9~", "A-z.0_9~"),
626 ("x y+z", "x%20y%2Bz"),
627 ("?#&=%", "%3F%23%26%3D%25"),
628 ("é", "%C3%A9"),
629 ("!a/*", "%21a%2F%2A"),
630 ("a/**", "a%2F%2A%2A"),
631 ];
632 for (value, encoded) in cases {
633 let mut out = String::new();
634 encode(value, &mut out);
635 assert_eq!(out, encoded);
636 assert_eq!(encoded_len(value), encoded.len());
637 }
638 assert_eq!(refs_query(&request(&[], None)).unwrap(), None);
639 assert_eq!(
640 refs_query(&request(&["a/b", "main"], None))
641 .unwrap()
642 .as_deref(),
643 Some("pattern=a%2Fb&pattern=main")
644 );
645 assert_eq!(
646 refs_query(&request(&["a/**", "x/*", "!a/b/*", "!z"], None))
647 .unwrap()
648 .as_deref(),
649 Some("pattern=a%2F%2A%2A&pattern=x%2F%2A&pattern=%21a%2Fb%2F%2A&pattern=%21z")
650 );
651 }
652
653 /// Returns the request of the entries `refs` and `collections`, as
654 /// `wire_entries` gives them.
655 fn request(refs: &[&str], collections: Option<&[&str]>) -> ListRefsRequest {
656 let entries = |list: &[&str]| list.iter().map(|e| (*e).to_owned()).collect();
657 ListRefsRequest {
658 refs: entries(refs),
659 collections: collections.map(entries),
660 }
661 }
662
663 /// The `collection` pairs come after the `pattern` pairs. A request with
664 /// collection entries alone has a query. An empty list of collection
665 /// entries adds no pair: `fetch_refs` sends it as the entry `**`.
666 #[test]
667 fn collection_entries_follow_the_pattern_pairs() {
668 assert_eq!(
669 refs_query(&request(&["main"], Some(&["org.a/**", "!org.b/x"])))
670 .unwrap()
671 .as_deref(),
672 Some("pattern=main&collection=org.a%2F%2A%2A&collection=%21org.b%2Fx")
673 );
674 assert_eq!(
675 refs_query(&request(&[], Some(&["*/main"])))
676 .unwrap()
677 .as_deref(),
678 Some("collection=%2A%2Fmain")
679 );
680 assert_eq!(refs_query(&request(&[], Some(&[]))).unwrap(), None);
681 assert_eq!(
682 refs_query(&request(&["a"], Some(&["**"])))
683 .unwrap()
684 .as_deref(),
685 Some("pattern=a&collection=%2A%2A")
686 );
687 }
688
689 /// The target limit counts the `collection` pairs, their keys, and the
690 /// `&` between the two kinds of pairs.
691 #[test]
692 fn the_target_limit_counts_the_collection_pairs() {
693 let fixed = REFS_PATH.len() + 1 + PATTERN_KEY.len() + 1 + 1 + COLLECTION_KEY.len();
694 let fits = "a".repeat(MAX_REFS_TARGET - fixed);
695 let query = refs_query(&request(&["a"], Some(&[&fits])))
696 .unwrap()
697 .unwrap();
698 assert_eq!(REFS_PATH.len() + 1 + query.len(), MAX_REFS_TARGET);
699 let over = "a".repeat(MAX_REFS_TARGET - fixed + 1);
700 let err = refs_query(&request(&["a"], Some(&[&over]))).unwrap_err();
701 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
702 }
703
704 /// The target limit counts `_ostrya/refs/v1`, the `?`, and the query. A
705 /// target of exactly the limit passes.
706 #[test]
707 fn the_target_limit_is_inclusive() {
708 let fixed = REFS_PATH.len() + 1 + PATTERN_KEY.len();
709 let fits = "a".repeat(MAX_REFS_TARGET - fixed);
710 let query = refs_query(&request(&[&fits], None)).unwrap().unwrap();
711 assert_eq!(REFS_PATH.len() + 1 + query.len(), MAX_REFS_TARGET);
712 assert_eq!(query.capacity(), query.len());
713 let over = "a".repeat(MAX_REFS_TARGET - fixed + 1);
714 let err = refs_query(&request(&[&over], None)).unwrap_err();
715 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
716 }
717
718 /// A `!` counts in the length of the target. `refs_query` refuses a
719 /// negative entry one byte over the limit, and accepts a negative entry at
720 /// the limit.
721 #[test]
722 fn the_target_limit_counts_the_bang() {
723 let fixed = REFS_PATH.len() + 1 + PATTERN_KEY.len();
724 let fits = format!("!{}", "a".repeat(MAX_REFS_TARGET - fixed - 3));
725 let query = refs_query(&request(&[&fits], None)).unwrap().unwrap();
726 assert_eq!(REFS_PATH.len() + 1 + query.len(), MAX_REFS_TARGET);
727 let over = format!("!{}", "a".repeat(MAX_REFS_TARGET - fixed - 2));
728 let err = refs_query(&request(&[&over], None)).unwrap_err();
729 assert!(matches!(err, Error::InvalidInput(_)), "{err:?}");
730 }
731}