GITv
master
git_stream.rs111 lines, 4.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
//! Bounded, backpressured output from a pinned Git process.
use axum::body::{Body, Bytes};
use futures_util::{StreamExt, stream};
use std::{io, process::Stdio, time::Duration};
#[cfg(test)]
use tokio::sync::Semaphore;
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    process::Command,
    sync::{mpsc, oneshot},
};

pub struct Output {
    child: tokio::process::Child,
    stdout: tokio::process::ChildStdout,
}

impl Output {
    pub fn start(mut command: Command) -> io::Result<Self> {
        let mut child = command.kill_on_drop(true).stdout(Stdio::piped()).spawn()?;
        let stdout = child.stdout.take().ok_or_else(|| io::Error::other("missing Git stdout"))?;
        Ok(Self { child, stdout })
    }

    pub async fn prefix(&mut self, len: usize) -> io::Result<Bytes> {
        let mut bytes = vec![0; len];
        tokio::time::timeout(gitv_core::GIT_TIMEOUT, self.stdout.read_exact(&mut bytes)).await??;
        Ok(bytes.into())
    }

    pub fn body(mut self, prefix: Bytes, input: Option<Bytes>, permit: impl Send + 'static, timeout: Duration) -> Body {
        let (tx, rx) = mpsc::channel::<Bytes>(2);
        let (finished, status) = oneshot::channel();
        let (body_guard, dropped) = oneshot::channel::<()>();
        tokio::spawn(async move {
            let _permit = permit;
            let deadline = tokio::time::Instant::now() + timeout;
            let mut stdin = self.child.stdin.take();
            let write = async move {
                if let Some(input) = input {
                    stdin.as_mut().ok_or_else(|| io::Error::other("missing Git stdin"))?.write_all(&input).await?;
                }
                drop(stdin);
                Ok::<_, io::Error>(())
            };
            let read = async {
                let mut buf = vec![0; 65536];
                loop {
                    let count = self.stdout.read(&mut buf).await?;
                    if count == 0 {
                        break;
                    }
                    tx.send(Bytes::copy_from_slice(&buf[..count])).await.map_err(|_| io::ErrorKind::BrokenPipe)?;
                }
                if !self.child.wait().await?.success() {
                    return Err(io::Error::other("Git transfer failed"));
                }
                Ok(())
            };
            let outcome = tokio::select! {
                _ = tx.closed() => return,
                result = tokio::time::timeout_at(deadline, async { tokio::try_join!(write, read).map(|_| ()) }) =>
                    result.unwrap_or_else(|_| Err(io::ErrorKind::TimedOut.into())),
            };
            drop(self);
            drop(tx);
            let _ = finished.send(outcome);
            // Hold the slot through buffered delivery, but never beyond the transfer deadline.
            let _ = tokio::time::timeout_at(deadline, dropped).await;
        });
        // The worker's terminal status has its own channel (a oneshot), so a full
        // byte queue cannot turn a failed transfer into successful EOF.
        let chunks = stream::unfold(rx, |mut rx| async { Some((rx.recv().await?, rx)) }).map(Ok);
        let end = stream::once(async move {
            let _guard = body_guard;
            status.await.map_err(io::Error::other)??;
            Ok::<_, io::Error>(Bytes::new())
        });
        Body::from_stream(stream::iter((!prefix.is_empty()).then_some(Ok(prefix))).chain(chunks).chain(end))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn dropping_a_transfer_body_releases_its_slot() {
        static SLOT: Semaphore = Semaphore::const_new(1);
        let mut command = Command::new("head");
        command.args(["-c", "1048576", "/dev/zero"]);
        let output = Output::start(command).unwrap();
        let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_secs(300));
        drop(body);
        let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap();
        drop(permit);
    }

    #[tokio::test]
    async fn stalled_body_times_out_and_reports_the_error_after_buffered_bytes() {
        static SLOT: Semaphore = Semaphore::const_new(1);
        let mut command = Command::new("head");
        command.args(["-c", "1048576", "/dev/zero"]);
        let output = Output::start(command).unwrap();
        let body = output.body(Bytes::new(), None, SLOT.try_acquire().unwrap(), Duration::from_millis(50));
        assert!(SLOT.try_acquire().is_err());
        let permit = tokio::time::timeout(Duration::from_secs(3), SLOT.acquire()).await.unwrap().unwrap();
        assert!(axum::body::to_bytes(body, 1 << 20).await.is_err());
        drop(permit);
    }
}