use std::fs::{self, File, Metadata};
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
const FIRST: u64 = 64 << 10;
pub fn plain(home: &Path, path: &Path) -> Result<Metadata, String> {
let below = path
.strip_prefix(home)
.map_err(|_| "the file is not under the home".to_string())?;
let mut at = home.to_path_buf();
for part in below.components() {
at.push(part);
let found =
fs::symlink_metadata(&at).map_err(|_| format!("{} is missing", at.display()))?;
if found.file_type().is_symlink() {
return Err(format!("{} is a symbolic link", at.display()));
}
}
let found = fs::symlink_metadata(path).map_err(|e| e.to_string())?;
if !found.is_file() {
return Err(format!("{} is not a regular file", path.display()));
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if found.nlink() != 1 {
return Err(format!("{} has more than one hard link", path.display()));
}
}
Ok(found)
}
#[cfg(unix)]
fn same(checked: &Metadata, opened: &Metadata) -> bool {
use std::os::unix::fs::MetadataExt;
checked.dev() == opened.dev() && checked.ino() == opened.ino()
}
#[cfg(not(unix))]
fn same(checked: &Metadata, opened: &Metadata) -> bool {
opened.is_file() && checked.len() <= opened.len()
}
pub fn tail(
path: &Path,
checked: &Metadata,
cap: u64,
mut reached: impl FnMut(&[u8]) -> bool,
) -> Result<Vec<u8>, String> {
let mut file = File::open(path).map_err(|e| e.to_string())?;
let opened = file.metadata().map_err(|e| e.to_string())?;
if !same(checked, &opened) {
return Err(format!("{} changed while it was read", path.display()));
}
let length = opened.len();
let mut size = FIRST;
loop {
let start = length.saturating_sub(size);
if length - start > cap {
return Err(format!(
"the turn passed the bound of {} MiB read back from the end of its file",
cap >> 20
));
}
let mut window = Vec::with_capacity((length - start) as usize);
file.seek(SeekFrom::Start(start))
.and_then(|_| (&mut file).take(length - start).read_to_end(&mut window))
.map_err(|e| e.to_string())?;
let from = if start == 0 {
0
} else {
window
.iter()
.position(|b| *b == b'\n')
.map_or(window.len(), |i| i + 1)
};
if start == 0 || reached(&window[from..]) {
window.drain(..from);
return Ok(window);
}
size = size.saturating_mul(2);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::Scratch;
#[test]
fn the_window_grows_back_from_the_end_and_never_past_the_cap() {
let scratch = Scratch::new("bounded-tail");
let home = scratch.path();
let lines: String = (0..20_000).map(|i| format!("{i:08}\n")).collect();
let path = home.join("a/file.jsonl");
scratch.plant("a/file.jsonl", &lines);
let checked = plain(home, &path).unwrap();
let mut asked = 0;
let window = tail(&path, &checked, 1 << 20, |lines| {
asked += 1;
lines.starts_with(b"0000") && lines[..8] <= *b"00019000".as_slice()
})
.unwrap();
let text = String::from_utf8(window).unwrap();
assert!(text.ends_with("00019999\n") && text.len() < 64 << 11);
assert!(text.lines().next().unwrap() <= "00019000" && asked <= 3);
assert!(
tail(&path, &checked, 1 << 10, |_| false)
.unwrap_err()
.contains("bound")
);
let whole = tail(&path, &checked, 1 << 20, |_| false).unwrap();
assert_eq!(whole, lines.as_bytes());
#[cfg(unix)]
{
std::os::unix::fs::symlink(&path, home.join("a/link.jsonl")).unwrap();
assert!(
plain(home, &home.join("a/link.jsonl"))
.unwrap_err()
.contains("symbolic")
);
fs::hard_link(&path, home.join("a/second.jsonl")).unwrap();
assert!(plain(home, &path).unwrap_err().contains("hard link"));
}
}
}