Skip to main content

panoramic_courier/
follow.rs

1use std::{io, path::Path, time::Duration};
2
3use snafu::ResultExt as _;
4use tokio::{
5    fs::File,
6    io::{AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _},
7    time::{sleep_until, timeout_at, Instant},
8};
9
10use crate::{Error, OutputSnafu, TargetSnafu, TimedOutSnafu};
11
12/// How often to look again for a file that does not exist yet, or for more of one that has no new data.
13const POLL_INTERVAL: Duration = Duration::from_millis(100);
14
15/// Writes the contents of the file at `path` to `out` as they are written, until `limit` passes.
16///
17/// Waits for the file to exist, then writes it from the start. Reaching `limit` after the file was found is the
18/// normal end. A file that is truncated, renamed or replaced is not followed again.
19///
20/// # Errors
21///
22/// Fails with [`Error::TimedOut`] when the file does not appear before `limit` passes, [`Error::Target`] when it
23/// cannot be opened or read, and [`Error::Output`] when writing to `out` fails.
24pub async fn follow<W>(path: &Path, limit: Duration, out: &mut W) -> Result<(), Error>
25where
26    W: AsyncWrite + Unpin,
27{
28    let deadline = Instant::now() + limit;
29    let context = |action| TargetSnafu {
30        action,
31        target: path.display().to_string(),
32    };
33
34    let mut file = loop {
35        match File::open(path).await {
36            Ok(file) => break file,
37            Err(e) if e.kind() == io::ErrorKind::NotFound => {
38                if Instant::now() >= deadline {
39                    return TimedOutSnafu {
40                        operation: "follow",
41                        target: path.display().to_string(),
42                        limit,
43                    }
44                    .fail();
45                }
46                sleep_until((Instant::now() + POLL_INTERVAL).min(deadline)).await;
47            }
48            Err(e) => return Err(e).context(context("open")),
49        }
50    };
51
52    let mut buf = vec![0; 64 * 1024];
53    loop {
54        let n = match timeout_at(deadline, file.read(&mut buf)).await {
55            Ok(read) => read.with_context(|_| context("read"))?,
56            Err(_) => return Ok(()),
57        };
58        if n > 0 {
59            let written = timeout_at(deadline, async {
60                out.write_all(&buf[..n]).await?;
61                out.flush().await
62            })
63            .await;
64            match written {
65                Ok(written) => written.context(OutputSnafu)?,
66                Err(_) => return Ok(()),
67            }
68        } else if Instant::now() >= deadline {
69            return Ok(());
70        } else {
71            sleep_until((Instant::now() + POLL_INTERVAL).min(deadline)).await;
72        }
73    }
74}