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