steid

@jamesgill /

Rust30.8 KBCode·Blame·History·Raw
1//! Long-lived `git cat-file` processes, pooled per repository.
2//!
3//! Stage 2 of the upgrade path in the Milestone 5 amendment to
4//! [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md): every object
5//! read used to cost a fork/exec of ~11–12ms, and the answer is the one Gitaly and
6//! Gitea both reached for — keep the process alive and write another line to it.
7//!
8//! # Two processes, not one
9//!
10//! `git cat-file --batch-check` answers existence, type and size; `git cat-file
11//! --batch` answers contents. They are separate processes because a single `--batch`
12//! stream cannot be asked a question whose answer is not read: writing a spec commits
13//! the reader to consuming however many bytes the object holds, and "is this blob
14//! small enough to read?" is exactly the question that must be answered *before* the
15//! bytes are on the wire.
16//!
17//! **Not `--batch-command`**, which would collapse the pair into one process by letting
18//! each line name its own verb. It arrived in git **2.36**, and Ubuntu 22.04 — which
19//! `install.sh` deliberately supports — ships **2.34**. Two processes cost one more
20//! fork per repository per five minutes; a raised floor costs an operator their install.
21//!
22//! Input is NUL-delimited (`-z`, git 2.31, comfortably below the floor) rather than
23//! newline-delimited, because a git path may contain a newline and a newline in a spec
24//! would otherwise be read as the start of another request.
25//!
26//! # What this module guarantees
27//!
28//! - **Requests serialise per process.** One mutex per process, so a repository can
29//! answer a `--batch-check` and a `--batch` at once but never two of either.
30//! - **A desync is fatal to the process, not to the stream.** If a reply does not parse
31//! as the protocol says it must — a header for a different object, a body not
32//! followed by its newline — the process is killed and the request fails. Reading on
33//! past a reply we did not understand would answer the *next* request with this one's
34//! bytes, which is worse than an error by exactly as much as a wrong file is worse
35//! than a missing one.
36//! - **A crashed process is respawned once per request.** `pkill` on a batch process,
37//! or an OOM kill, shows up as EOF on the next read; the second failure in one
38//! request is a real fault and is reported.
39//! - **The timeout is the same one every other read pays.** A pool request that outruns
40//! it kills the process, so a stuck git cannot hold the mutex for the next visitor.
41
42use std::{
43 collections::HashMap,
44 io::ErrorKind,
45 path::{Path, PathBuf},
46 process::Stdio,
47 sync::Mutex,
48 time::{Duration, Instant},
49};
50
51use tokio::{
52 io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
53 process::{Child, ChildStderr, ChildStdin, ChildStdout},
54 sync::Mutex as AsyncMutex,
55};
56
57use crate::{application::port::GitQueryError, domain::ObjectId, infrastructure::git::git_command};
58
59/// How many repositories may hold live processes at once.
60///
61/// Two processes each, so the cap is 128 file descriptors' worth of git and whatever
62/// each has mapped of a pack index — the memory is the reason there is a cap at all,
63/// since a `cat-file` process holds its repository's idx files open. Sixty-four is
64/// chosen rather than derived: a personal instance has single figures of repositories,
65/// and the number only bites on an instance browsing far more than that at once, where
66/// the eviction it causes costs one fork to undo.
67const MAX_LIVE_REPOSITORIES: usize = 64;
68
69/// How long a repository's processes survive with nothing asking them anything.
70///
71/// Long enough that a person reading a repository never pays a spawn twice, short
72/// enough that a crawler walking a hundred repositories does not leave a hundred
73/// processes behind for the rest of the day.
74const IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
75
76/// The read budget for one exchange with a pooled process.
77///
78/// The same twenty seconds `git_query`'s one-shot commands get, and for the same
79/// reason: a request that never finishes holds a worker for as long as the client
80/// waits. It is enforced here as well as there because the pool is where the *next*
81/// request queues — a hung `cat-file` holding its mutex would otherwise stall a
82/// repository rather than one page.
83const GIT_TIMEOUT: Duration = Duration::from_secs(20);
84
85/// The words `cat-file` ends a line with when it did not resolve a spec.
86///
87/// `missing` covers the common cases; `ambiguous` is an abbreviated id matching more
88/// than one object, and `dangling` and `notdir` appear when following a `^{}` or a path
89/// through something that cannot hold one. None of them is a failure — they are the
90/// answer "no such thing here".
91const NOT_FOUND_MARKERS: [&str; 4] = ["missing", "ambiguous", "dangling", "notdir"];
92
93/// How many specs are written before the replies are read.
94///
95/// A pipe holds 64 KiB; writing more than that without reading deadlocks, with git
96/// blocked writing replies nobody is draining and us blocked writing specs git is not
97/// reading. Both bounds are well under it, and the byte bound is the one that matters
98/// because a spec can be a path of any length.
99const MAX_BATCH_SPECS: usize = 256;
100const MAX_BATCH_BYTES: usize = 8 * 1024;
101
102/// What `cat-file --batch-check` said about one object.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub(crate) struct ObjectInfo {
105 pub(crate) id: ObjectId,
106 pub(crate) kind: ObjectKind,
107 pub(crate) size: u64,
108}
109
110/// A git object's type, as its header spells it.
111///
112/// Distinct from [`EntryKind`](crate::domain::EntryKind), which is about what a tree
113/// entry *means* — the object store cannot tell a symlink from a file, because both are
114/// blobs.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub(crate) enum ObjectKind {
117 Blob,
118 Tree,
119 Commit,
120 Tag,
121}
122
123impl ObjectKind {
124 fn from_str(value: &str) -> Option<Self> {
125 match value {
126 "blob" => Some(Self::Blob),
127 "tree" => Some(Self::Tree),
128 "commit" => Some(Self::Commit),
129 "tag" => Some(Self::Tag),
130 _ => None,
131 }
132 }
133}
134
135/// Which of a repository's two processes a request is for.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137enum Mode {
138 Check,
139 Contents,
140}
141
142impl Mode {
143 fn flag(self) -> &'static str {
144 match self {
145 Self::Check => "--batch-check",
146 Self::Contents => "--batch",
147 }
148 }
149}
150
151/// One question for a pooled process.
152///
153/// An enum rather than a closure because the retry in [`CatFilePool::exchange`] runs the
154/// same question twice against two different processes, and a borrow that outlives one
155/// attempt is exactly what a closure cannot promise here.
156#[derive(Debug, Clone, Copy)]
157enum Request<'a> {
158 /// Specs for `--batch-check`, answered one line each.
159 Check(&'a [String]),
160 /// An object `--batch-check` has already described, answered with its bytes.
161 Contents(&'a ObjectInfo),
162}
163
164impl Request<'_> {
165 fn mode(self) -> Mode {
166 match self {
167 Self::Check(_) => Mode::Check,
168 Self::Contents(_) => Mode::Contents,
169 }
170 }
171}
172
173/// What a process answered.
174#[derive(Debug)]
175enum Reply {
176 Check(Vec<Option<ObjectInfo>>),
177 Contents(Vec<u8>),
178}
179
180/// The `git cat-file` processes for one repository.
181///
182/// A mutex per process rather than one around the pair: the two answer independent
183/// questions, and a tree listing that reads a tree from `--batch` and then asks
184/// `--batch-check` for its blobs' sizes has no reason to stop another request doing the
185/// same in the other order.
186#[derive(Debug, Default)]
187struct Slot {
188 check: AsyncMutex<Option<Batch>>,
189 contents: AsyncMutex<Option<Batch>>,
190}
191
192impl Slot {
193 fn process(&self, mode: Mode) -> &AsyncMutex<Option<Batch>> {
194 match mode {
195 Mode::Check => &self.check,
196 Mode::Contents => &self.contents,
197 }
198 }
199}
200
201/// What the pool holds for one repository path.
202#[derive(Debug)]
203struct Entry {
204 slot: std::sync::Arc<Slot>,
205 last_used: Instant,
206}
207
208/// Kept-alive `git cat-file` processes, keyed by repository path.
209///
210/// Lives in app context, not in the adapter: `DiskGitQuery` is constructed per request,
211/// and a pool built per request would spawn and kill a process per request — the fork
212/// cost back, plus a pool that never pools. The Milestone 5 amendment to 0006 names
213/// this as the one thing that had to be got right before the first batch adapter
214/// existed.
215#[derive(Debug, Default)]
216pub struct CatFilePool {
217 repos: Mutex<HashMap<PathBuf, Entry>>,
218}
219
220impl CatFilePool {
221 pub fn new() -> Self {
222 Self::default()
223 }
224
225 /// Asks `--batch-check` about one spec.
226 pub(crate) async fn info(
227 &self,
228 repo: &Path,
229 spec: &str,
230 ) -> Result<Option<ObjectInfo>, GitQueryError> {
231 Ok(self
232 .info_many(repo, std::slice::from_ref(&spec.to_owned()))
233 .await?
234 .pop()
235 .flatten())
236 }
237
238 /// Asks `--batch-check` about many specs, in as few round trips as a pipe allows.
239 ///
240 /// One answer per spec, in the order asked. This is what makes a tree listing's
241 /// blob sizes cheap: the binary tree format carries no sizes, so they are asked for
242 /// in bulk rather than one process — or one round trip — at a time.
243 pub(crate) async fn info_many(
244 &self,
245 repo: &Path,
246 specs: &[String],
247 ) -> Result<Vec<Option<ObjectInfo>>, GitQueryError> {
248 let mut answers = Vec::with_capacity(specs.len());
249
250 for chunk in chunks(specs) {
251 let Reply::Check(replies) = self.exchange(repo, Request::Check(chunk)).await? else {
252 unreachable!("a check is answered with a check")
253 };
254
255 answers.extend(replies);
256 }
257
258 Ok(answers)
259 }
260
261 /// Reads an object's bytes from `--batch`.
262 ///
263 /// Takes the [`ObjectInfo`] a `--batch-check` already produced rather than a spec,
264 /// for two reasons that are really one: the caller has to know the size before it
265 /// decides to read (an oversized blob is never fetched), and knowing the id, type
266 /// and size in advance turns the reply header into a check rather than a parse. A
267 /// header that disagrees is a desync, and the process does not survive it.
268 pub(crate) async fn contents(
269 &self,
270 repo: &Path,
271 info: &ObjectInfo,
272 ) -> Result<Vec<u8>, GitQueryError> {
273 let Reply::Contents(bytes) = self.exchange(repo, Request::Contents(info)).await? else {
274 unreachable!("a contents request is answered with contents")
275 };
276
277 Ok(bytes)
278 }
279
280 /// One exchange with a pooled process: spawn if needed, run, and decide what a
281 /// failure means.
282 ///
283 /// The three outcomes are deliberately not one. A desync fails the request and
284 /// kills the process, because the stream can no longer be trusted. A dead process
285 /// is respawned and the exchange retried **once**, because a `pkill` between two
286 /// requests is not the visitor's fault and is invisible to them. A timeout kills
287 /// the process and fails, because the mutex is held until it does.
288 async fn exchange(&self, repo: &Path, request: Request<'_>) -> Result<Reply, GitQueryError> {
289 let mode = request.mode();
290 let slot = self.slot(repo);
291 let mut process = slot.process(mode).lock().await;
292
293 for attempt in 0..2 {
294 if process.is_none() {
295 *process = Some(Batch::spawn(repo, mode)?);
296 }
297
298 // Bound to a `let` rather than matched on directly: the future borrows the
299 // guard, and a match arm that replaces the process needs that borrow to have
300 // ended. A respawn makes a different `Batch`, which is what the second
301 // attempt re-borrows.
302 let outcome = {
303 let batch = process.as_mut().expect("just spawned");
304
305 tokio::time::timeout(GIT_TIMEOUT, batch.run(request)).await
306 };
307
308 match outcome {
309 Ok(Ok(value)) => return Ok(value),
310 Ok(Err(Desync::Protocol(message))) => {
311 // Killed rather than kept: the next request would otherwise read
312 // this one's leftovers as its own answer.
313 *process = None;
314 return Err(GitQueryError::new(format!(
315 "git cat-file {} spoke out of turn: {message}",
316 mode.flag()
317 )));
318 }
319 Ok(Err(Desync::Gone(message))) => {
320 *process = None;
321
322 if attempt == 1 {
323 return Err(GitQueryError::new(format!(
324 "git cat-file {} would not stay running: {message}",
325 mode.flag()
326 )));
327 }
328 }
329 Err(_elapsed) => {
330 *process = None;
331 return Err(GitQueryError::timed_out(GIT_TIMEOUT));
332 }
333 }
334 }
335
336 unreachable!("the loop either returns or retries once")
337 }
338
339 /// The slot for a repository, evicting what has gone stale on the way past.
340 ///
341 /// Eviction is lazy rather than a background task: the pool has no runtime of its
342 /// own, and a sweep on acquire runs exactly as often as the pool is used. A slot
343 /// somebody is still holding is never evicted — that is what the strong count is
344 /// read for — so the worst an eviction costs is one spawn.
345 fn slot(&self, repo: &Path) -> std::sync::Arc<Slot> {
346 let mut repos = self.repos.lock().expect("lock poisoned");
347 let now = Instant::now();
348
349 repos.retain(|_, entry| {
350 std::sync::Arc::strong_count(&entry.slot) > 1
351 || now.duration_since(entry.last_used) < IDLE_TIMEOUT
352 });
353
354 if let Some(entry) = repos.get_mut(repo) {
355 entry.last_used = now;
356 return entry.slot.clone();
357 }
358
359 if repos.len() >= MAX_LIVE_REPOSITORIES {
360 let oldest = repos
361 .iter()
362 .filter(|(_, entry)| std::sync::Arc::strong_count(&entry.slot) == 1)
363 .min_by_key(|(_, entry)| entry.last_used)
364 .map(|(path, _)| path.clone());
365
366 if let Some(oldest) = oldest {
367 repos.remove(&oldest);
368 }
369 }
370
371 let slot = std::sync::Arc::new(Slot::default());
372
373 repos.insert(
374 repo.to_path_buf(),
375 Entry {
376 slot: slot.clone(),
377 last_used: now,
378 },
379 );
380
381 slot
382 }
383
384 /// How many repositories currently hold a slot. Tests only.
385 #[cfg(test)]
386 fn live(&self) -> usize {
387 self.repos.lock().expect("lock poisoned").len()
388 }
389}
390
391/// Splits specs into groups small enough to write without reading.
392fn chunks(specs: &[String]) -> Vec<&[String]> {
393 let mut groups = Vec::new();
394 let mut start = 0;
395 let mut bytes = 0;
396
397 for (index, spec) in specs.iter().enumerate() {
398 let next = bytes + spec.len() + 1;
399
400 if index > start && (index - start >= MAX_BATCH_SPECS || next > MAX_BATCH_BYTES) {
401 groups.push(&specs[start..index]);
402 start = index;
403 bytes = spec.len() + 1;
404 } else {
405 bytes = next;
406 }
407 }
408
409 if start < specs.len() {
410 groups.push(&specs[start..]);
411 }
412
413 groups
414}
415
416/// Why an exchange did not produce an answer.
417#[derive(Debug)]
418enum Desync {
419 /// git said something the protocol does not allow. The stream is not trustworthy.
420 Protocol(String),
421 /// The process is not there any more — EOF, a broken pipe, a signal.
422 Gone(String),
423}
424
425/// One live `git cat-file` process and its pipes.
426#[derive(Debug)]
427struct Batch {
428 child: Child,
429 stdin: ChildStdin,
430 stdout: BufReader<ChildStdout>,
431 stderr: Option<ChildStderr>,
432}
433
434impl Batch {
435 /// Answers one question, leaving the stream positioned for the next.
436 async fn run(&mut self, request: Request<'_>) -> Result<Reply, Desync> {
437 match request {
438 Request::Check(specs) => self.check(specs).await.map(Reply::Check),
439 Request::Contents(info) => self.contents(info).await.map(Reply::Contents),
440 }
441 }
442
443 fn spawn(repo: &Path, mode: Mode) -> Result<Self, GitQueryError> {
444 let mut command = git_command();
445
446 command
447 .arg("-C")
448 .arg(repo)
449 .arg("cat-file")
450 .arg(mode.flag())
451 // NUL-delimited input, so a path containing a newline is one spec rather
452 // than two requests. git 2.31; the floor is 2.34.
453 .arg("-z")
454 .stdin(Stdio::piped())
455 .stdout(Stdio::piped())
456 .stderr(Stdio::piped())
457 // A pool entry dropped — evicted, killed after a desync, or the process
458 // shutting down — must take git with it, or the process outlives everything
459 // that could ever read from it.
460 .kill_on_drop(true);
461
462 let mut child = command
463 .spawn()
464 .map_err(|error| GitQueryError::new(format!("could not run git cat-file: {error}")))?;
465
466 let stdin = child.stdin.take().expect("stdin was piped");
467 let stdout = BufReader::new(child.stdout.take().expect("stdout was piped"));
468 let stderr = child.stderr.take();
469
470 Ok(Self {
471 child,
472 stdin,
473 stdout,
474 stderr,
475 })
476 }
477
478 /// Writes a group of specs and reads one reply line each.
479 async fn check(&mut self, specs: &[String]) -> Result<Vec<Option<ObjectInfo>>, Desync> {
480 let mut request = Vec::new();
481
482 for spec in specs {
483 request.extend_from_slice(spec.as_bytes());
484 request.push(0);
485 }
486
487 self.write(&request).await?;
488
489 let mut answers = Vec::with_capacity(specs.len());
490
491 for _ in specs {
492 let line = self.line().await?;
493
494 answers.push(parse_check_line(&line)?);
495 }
496
497 Ok(answers)
498 }
499
500 /// Writes one spec and reads the object it names.
501 async fn contents(&mut self, info: &ObjectInfo) -> Result<Vec<u8>, Desync> {
502 let mut request = info.id.as_str().as_bytes().to_vec();
503 request.push(0);
504
505 self.write(&request).await?;
506
507 let line = self.line().await?;
508
509 // The caller already knows what it asked for, so anything else is a stream that
510 // has slipped a reply — not an object that has changed.
511 let Some(header) = parse_check_line(&line)? else {
512 return Err(Desync::Protocol(format!(
513 "{} is missing from a repository that had just described it",
514 info.id.as_str()
515 )));
516 };
517
518 if &header != info {
519 return Err(Desync::Protocol(format!(
520 "asked for {:?} and was answered with {:?}",
521 info, header
522 )));
523 }
524
525 // One byte more than the object: git writes a newline after the body, and
526 // reading it is what leaves the stream positioned for the next request.
527 let mut body = vec![0u8; header.size as usize + 1];
528
529 self.stdout
530 .read_exact(&mut body)
531 .await
532 .map_err(|error| Desync::Gone(format!("reading {} bytes: {error}", header.size)))?;
533
534 if body.pop() != Some(b'\n') {
535 return Err(Desync::Protocol(format!(
536 "{} was not followed by a newline",
537 header.id.as_str()
538 )));
539 }
540
541 Ok(body)
542 }
543
544 async fn write(&mut self, request: &[u8]) -> Result<(), Desync> {
545 match self.stdin.write_all(request).await {
546 Ok(()) => self
547 .stdin
548 .flush()
549 .await
550 .map_err(|error| Desync::Gone(error.to_string())),
551 // A process that has died gives EPIPE here rather than at the read, which is
552 // the same fact arriving one step earlier.
553 Err(error) => Err(Desync::Gone(self.why_gone(error).await)),
554 }
555 }
556
557 async fn line(&mut self) -> Result<String, Desync> {
558 let mut line = String::new();
559
560 match self.stdout.read_line(&mut line).await {
561 // Zero bytes is EOF: git closed its stdout, which for a batch process means
562 // it exited.
563 Ok(0) => Err(Desync::Gone(
564 self.why_gone(ErrorKind::UnexpectedEof.into()).await,
565 )),
566 Ok(_) => Ok(line.trim_end_matches('\n').to_owned()),
567 Err(error) => Err(Desync::Gone(self.why_gone(error).await)),
568 }
569 }
570
571 /// What git said on its way out, if anything, for the message a visitor's 500 logs.
572 ///
573 /// Read only when the process is already known to be gone, and capped, because a
574 /// pipe nobody drains is a pipe that can fill.
575 async fn why_gone(&mut self, error: std::io::Error) -> String {
576 let mut said = String::new();
577
578 if let Some(stderr) = self.stderr.as_mut() {
579 let mut buffer = vec![0u8; 4096];
580
581 if let Ok(read) = stderr.read(&mut buffer).await {
582 said = String::from_utf8_lossy(&buffer[..read]).trim().to_owned();
583 }
584 }
585
586 let status = self.child.try_wait().ok().flatten();
587
588 match (said.is_empty(), status) {
589 (false, _) => said,
590 (true, Some(status)) => format!("{error} ({status})"),
591 (true, None) => error.to_string(),
592 }
593 }
594}
595
596/// Parses one `<id> <type> <size>` reply, or the not-found line git answers instead.
597///
598/// The marker is checked before the field count, because a not-found line echoes the
599/// spec back — and a spec naming a file with spaces in it has no fixed field count.
600fn parse_check_line(line: &str) -> Result<Option<ObjectInfo>, Desync> {
601 if line
602 .rsplit(' ')
603 .next()
604 .is_some_and(|last| NOT_FOUND_MARKERS.contains(&last))
605 {
606 return Ok(None);
607 }
608
609 let fields: Vec<&str> = line.split_whitespace().collect();
610
611 let [id, kind, size] = fields[..] else {
612 return Err(Desync::Protocol(format!(
613 "described an object in a shape we do not understand: {line:?}"
614 )));
615 };
616
617 Ok(Some(ObjectInfo {
618 // Validated rather than trusted. git's ids are trustworthy, but this is a parse
619 // of text whose layout we have assumed, and an id is about to appear in a URL —
620 // a misread field should stop here rather than surface as a broken link.
621 id: ObjectId::new(id)
622 .map_err(|error| Desync::Protocol(format!("named a bad object id: {error}")))?,
623 kind: ObjectKind::from_str(kind)
624 .ok_or_else(|| Desync::Protocol(format!("reported an unknown object type {kind:?}")))?,
625 size: size
626 .parse()
627 .map_err(|_| Desync::Protocol(format!("reported an unreadable size {size:?}")))?,
628 }))
629}
630
631#[cfg(test)]
632mod tests {
633 use std::process::Command;
634
635 use tempfile::TempDir;
636
637 use super::*;
638
639 /// A repository with one commit, one file and one directory.
640 fn fixture() -> TempDir {
641 let dir = tempfile::tempdir().expect("temp dir");
642 let path = dir.path();
643
644 run(path, &["init", "--quiet", "--initial-branch=main", "."]);
645 std::fs::create_dir(path.join("sub")).expect("mkdir");
646 std::fs::write(path.join("a.txt"), b"hello\n").expect("write");
647 std::fs::write(path.join("sub/b.txt"), b"nested\n").expect("write");
648 run(path, &["add", "-A"]);
649 run(
650 path,
651 &[
652 "-c",
653 "user.email=a@example.com",
654 "-c",
655 "user.name=A",
656 "commit",
657 "--quiet",
658 "-m",
659 "first",
660 ],
661 );
662
663 dir
664 }
665
666 fn run(dir: &Path, args: &[&str]) {
667 let status = Command::new("git")
668 .arg("-C")
669 .arg(dir)
670 .args(args)
671 .status()
672 .expect("git runs");
673
674 assert!(status.success(), "git {args:?} failed");
675 }
676
677 #[tokio::test]
678 async fn an_object_is_described_by_id_type_and_size() {
679 let dir = fixture();
680 let pool = CatFilePool::new();
681
682 let info = pool
683 .info(dir.path(), "HEAD:a.txt")
684 .await
685 .expect("asked")
686 .expect("found");
687
688 assert_eq!(info.kind, ObjectKind::Blob);
689 assert_eq!(info.size, 6);
690 }
691
692 #[tokio::test]
693 async fn a_spec_that_names_nothing_is_not_a_failure() {
694 let dir = fixture();
695 let pool = CatFilePool::new();
696
697 assert_eq!(
698 pool.info(dir.path(), "HEAD:nope").await.expect("asked"),
699 None
700 );
701 assert_eq!(
702 pool.info(dir.path(), "nosuchref").await.expect("asked"),
703 None
704 );
705 }
706
707 #[tokio::test]
708 async fn contents_come_back_whole() {
709 let dir = fixture();
710 let pool = CatFilePool::new();
711
712 let info = pool
713 .info(dir.path(), "HEAD:a.txt")
714 .await
715 .expect("asked")
716 .expect("found");
717
718 assert_eq!(
719 pool.contents(dir.path(), &info).await.expect("read"),
720 b"hello\n"
721 );
722 }
723
724 #[tokio::test]
725 async fn a_repository_is_asked_many_times_through_one_pair_of_processes() {
726 let dir = fixture();
727 let pool = CatFilePool::new();
728
729 for _ in 0..5 {
730 let info = pool
731 .info(dir.path(), "HEAD:a.txt")
732 .await
733 .expect("asked")
734 .expect("found");
735
736 pool.contents(dir.path(), &info).await.expect("read");
737 }
738
739 assert_eq!(pool.live(), 1, "one repository, one slot");
740
741 // The processes are the ones spawned on the first call: a respawn would have
742 // replaced the `Option`, and this reads the same two through the same slot.
743 let slot = pool.slot(dir.path());
744
745 assert!(slot.check.lock().await.is_some());
746 assert!(slot.contents.lock().await.is_some());
747 }
748
749 #[tokio::test]
750 async fn a_killed_process_is_replaced_on_the_next_request() {
751 let dir = fixture();
752 let pool = CatFilePool::new();
753
754 let info = pool
755 .info(dir.path(), "HEAD:a.txt")
756 .await
757 .expect("asked")
758 .expect("found");
759
760 // Exactly what `pkill -f 'cat-file --batch'` does to a running instance.
761 {
762 let slot = pool.slot(dir.path());
763 let mut process = slot.check.lock().await;
764 let batch = process.as_mut().expect("spawned");
765
766 batch.child.start_kill().expect("kill");
767 batch.child.wait().await.expect("reaped");
768 }
769
770 let again = pool
771 .info(dir.path(), "HEAD:a.txt")
772 .await
773 .expect("respawned and asked")
774 .expect("found");
775
776 assert_eq!(again, info);
777 }
778
779 #[tokio::test]
780 async fn a_reply_that_does_not_match_the_question_kills_the_process() {
781 let dir = fixture();
782 let pool = CatFilePool::new();
783
784 let mut info = pool
785 .info(dir.path(), "HEAD:a.txt")
786 .await
787 .expect("asked")
788 .expect("found");
789
790 // The size is what a desync looks like from here: git answers with the object's
791 // real header, which no longer matches what the caller believes it asked about.
792 info.size += 1;
793
794 let error = pool
795 .contents(dir.path(), &info)
796 .await
797 .expect_err("a mismatched header is not an answer");
798
799 assert!(
800 error.to_string().contains("spoke out of turn"),
801 "expected a desync, got {error}"
802 );
803
804 // And the process is gone rather than left holding an unread body.
805 let slot = pool.slot(dir.path());
806 assert!(slot.contents.lock().await.is_none());
807 }
808
809 #[tokio::test]
810 async fn the_stream_still_answers_correctly_after_a_desync() {
811 let dir = fixture();
812 let pool = CatFilePool::new();
813
814 let real = pool
815 .info(dir.path(), "HEAD:a.txt")
816 .await
817 .expect("asked")
818 .expect("found");
819
820 let mut wrong = real.clone();
821 wrong.size += 1;
822
823 pool.contents(dir.path(), &wrong).await.expect_err("desync");
824
825 // A respawned process, and the answer is the file's own bytes rather than the
826 // tail of the reply the killed one was part-way through.
827 assert_eq!(
828 pool.contents(dir.path(), &real).await.expect("read"),
829 b"hello\n"
830 );
831 }
832
833 #[tokio::test]
834 async fn a_repository_that_is_not_there_is_an_error() {
835 let dir = fixture();
836 let pool = CatFilePool::new();
837
838 let error = pool
839 .info(&dir.path().join("nowhere"), "HEAD")
840 .await
841 .expect_err("no repository, no answer");
842
843 assert!(
844 error.to_string().contains("would not stay running"),
845 "expected a spawn failure, got {error}"
846 );
847 }
848
849 #[tokio::test]
850 async fn the_pool_holds_at_most_its_cap() {
851 let pool = CatFilePool::new();
852 let dir = fixture();
853
854 // One real repository so the cap is exercised against something that answers,
855 // and the rest as distinct paths — the pool keys on the path, and a slot is
856 // created before any process is.
857 for index in 0..MAX_LIVE_REPOSITORIES + 10 {
858 pool.slot(&dir.path().join(format!("repo-{index}")));
859 }
860
861 assert_eq!(pool.live(), MAX_LIVE_REPOSITORIES);
862 }
863
864 #[tokio::test]
865 async fn the_repository_asked_about_most_recently_survives_eviction() {
866 let pool = CatFilePool::new();
867 let dir = fixture();
868 let kept = dir.path().join("repo-0");
869
870 pool.slot(&kept);
871
872 for index in 1..MAX_LIVE_REPOSITORIES {
873 pool.slot(&dir.path().join(format!("repo-{index}")));
874 }
875
876 // Touched again, so it is no longer the oldest when the cap next bites.
877 pool.slot(&kept);
878 pool.slot(&dir.path().join("one-too-many"));
879
880 let repos = pool.repos.lock().expect("lock poisoned");
881
882 assert_eq!(repos.len(), MAX_LIVE_REPOSITORIES);
883 assert!(repos.contains_key(&kept), "the most recent was evicted");
884 }
885
886 #[test]
887 fn specs_are_written_in_groups_a_pipe_can_hold() {
888 let many: Vec<String> = (0..MAX_BATCH_SPECS * 2 + 3)
889 .map(|index| format!("{index:040}"))
890 .collect();
891
892 let groups = chunks(&many);
893
894 assert!(groups.iter().all(|group| group.len() <= MAX_BATCH_SPECS));
895 assert!(groups.iter().all(
896 |group| group.iter().map(|spec| spec.len() + 1).sum::<usize>() <= MAX_BATCH_BYTES
897 ));
898 assert_eq!(
899 groups.iter().map(|group| group.len()).sum::<usize>(),
900 many.len()
901 );
902 }
903
904 #[test]
905 fn one_enormous_spec_is_still_a_group_of_its_own() {
906 let specs = vec!["a".repeat(MAX_BATCH_BYTES * 2), "b".to_owned()];
907 let groups = chunks(&specs);
908
909 assert_eq!(groups.len(), 2, "a spec too big to batch still gets asked");
910 }
911}