panoramic_courier/
follow.rs1use 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
12const POLL_INTERVAL: Duration = Duration::from_millis(100);
14
15pub 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}