Files
leleka/crates/model-format/src/readahead.rs
T

276 lines
10 KiB
Rust

//! Sequential read-ahead for whole-file verification.
//!
//! A verification hashes a file that is tens of gigabytes long. Doing `read` and `update` in one thread alternates
//! I/O and hashing, so the wall time is their sum. Here one reader thread keeps `DEPTH` chunks ahead of the
//! consumers (positional reads, so the shared cursor is untouched), and the consumers hash while the next chunks
//! are read. The same chunk can go to several consumers (SHA-256 and CRC-32 of one archive). Buffers are
//! recycled, so a multi-gigabyte pass allocates about `DEPTH` chunks, not one per chunk.
//!
//! Nothing here decides what a digest means: a short read, a failed read or a file that ends early is an error,
//! as with `read_exact`.
use std::{
fs::File,
io,
ops::Deref,
sync::{
Arc, Mutex,
mpsc::{Receiver, SyncSender, sync_channel},
},
thread,
};
/// Bytes per chunk. Large enough to keep syscalls and channel hops negligible, small enough to stay in cache
/// between the read and the hash.
pub(crate) const CHUNK_BYTES: usize = 8 << 20;
/// Chunks the reader may run ahead of the slowest consumer.
pub(crate) const DEPTH: usize = 6;
type Pool = Arc<Mutex<Vec<Vec<u8>>>>;
/// One chunk of the stream: `offset` is relative to the start of the span.
pub(crate) struct Chunk {
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) offset: u64,
data: Vec<u8>,
pool: Pool,
}
impl Deref for Chunk {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.data
}
}
impl Drop for Chunk {
fn drop(&mut self) {
let buffer = std::mem::take(&mut self.data);
if let Ok(mut pool) = self.pool.lock() {
pool.push(buffer);
}
}
}
#[cfg(unix)]
fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
use std::os::unix::fs::FileExt;
file.read_at(buffer, offset)
}
#[cfg(windows)]
fn read_at(file: &File, buffer: &mut [u8], offset: u64) -> io::Result<usize> {
use std::os::windows::fs::FileExt;
file.seek_read(buffer, offset)
}
fn read_exact_at(file: &File, mut buffer: &mut [u8], mut offset: u64) -> io::Result<()> {
while !buffer.is_empty() {
match read_at(file, buffer, offset) {
Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
Ok(count) => {
buffer = &mut buffer[count..];
offset += count as u64;
}
Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
Err(error) => return Err(error),
}
}
Ok(())
}
/// Tell the kernel the file is read once, front to back (a larger read-ahead window).
#[cfg(target_os = "linux")]
fn advise_sequential(file: &File) {
let _ = rustix::fs::fadvise(file, 0, None, rustix::fs::Advice::Sequential);
}
#[cfg(not(target_os = "linux"))]
fn advise_sequential(_file: &File) {}
/// How far ahead of the reader the kernel is asked to fetch (`POSIX_FADV_WILLNEED`). A cold NVMe that serves one 128 KiB
/// window at a time reads at tens of MB/s; a few hundred MB of asynchronous readahead keeps its queue full while the
/// hash runs.
#[cfg(target_os = "linux")]
const WILLNEED_AHEAD: u64 = 512 << 20;
#[cfg(target_os = "linux")]
fn advise_willneed(file: &File, offset: u64, len: u64) {
if let Some(len) = std::num::NonZeroU64::new(len) {
let _ = rustix::fs::fadvise(file, offset, Some(len), rustix::fs::Advice::WillNeed);
}
}
#[cfg(not(target_os = "linux"))]
fn advise_willneed(_file: &File, _offset: u64, _len: u64) {}
/// Drop the clean page-cache pages of a span that has been read and handed on (`POSIX_FADV_DONTNEED`, never `drop_caches`;
/// best effort, a no-op for a memfd). A hash pass reads each byte once: without this the 55 GB archive and the 84 GB of shards
/// would sit in the page cache after the pass as a second copy of what the process keeps (or does not need) in its own memory.
#[cfg(target_os = "linux")]
fn evict_span(file: &File, offset: u64, len: u64) {
if let Some(len) = std::num::NonZeroU64::new(len) {
let _ = rustix::fs::fadvise(file, offset, Some(len), rustix::fs::Advice::DontNeed);
}
}
#[cfg(not(target_os = "linux"))]
fn evict_span(_file: &File, _offset: u64, _len: u64) {}
/// Run `body` with `fanout` receivers that each get every chunk of `file[start .. start + bytes]`, in order.
/// The reader thread ends when the span is read, when a read fails (the error is the last item) or when every
/// receiver is gone. `body` must drain or drop its receivers.
pub(crate) fn with_read_ahead<R>(
file: &File,
start: u64,
bytes: u64,
fanout: usize,
body: impl FnOnce(Vec<Receiver<io::Result<Arc<Chunk>>>>) -> R,
) -> R {
let pool: Pool = Arc::new(Mutex::new(Vec::new()));
let mut senders: Vec<SyncSender<io::Result<Arc<Chunk>>>> = Vec::with_capacity(fanout);
let mut receivers = Vec::with_capacity(fanout);
for _ in 0..fanout {
let (tx, rx) = sync_channel(DEPTH);
senders.push(tx);
receivers.push(rx);
}
advise_sequential(file);
thread::scope(|scope| {
scope.spawn(move || {
let mut offset = 0u64;
let mut advised = start;
while offset < bytes {
let count = (bytes - offset).min(CHUNK_BYTES as u64) as usize;
#[cfg(target_os = "linux")]
{
let target = (start + offset + count as u64 + WILLNEED_AHEAD).min(start + bytes);
if target > advised {
advise_willneed(file, advised, target - advised);
advised = target;
}
}
#[cfg(not(target_os = "linux"))]
let _ = (&mut advised, advise_willneed as fn(&File, u64, u64));
let mut buffer = pool
.lock()
.ok()
.and_then(|mut p| p.pop())
.unwrap_or_default();
buffer.resize(count, 0);
if let Err(error) = read_exact_at(file, &mut buffer, start + offset) {
for tx in &senders {
let _ = tx.send(Err(io::Error::new(error.kind(), error.to_string())));
}
return;
}
// The bytes are in `buffer` now; the cached pages behind them are not needed again by this pass.
evict_span(file, start + offset, count as u64);
let chunk = Arc::new(Chunk {
offset,
data: buffer,
pool: Arc::clone(&pool),
});
let mut any = false;
for tx in &senders {
any |= tx.send(Ok(Arc::clone(&chunk))).is_ok();
}
if !any {
return;
}
offset += count as u64;
}
});
body(receivers)
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn temp_file(name: &str, bytes: &[u8]) -> (std::path::PathBuf, File) {
let path =
std::env::temp_dir().join(format!("leleka-readahead-{}-{name}", std::process::id()));
let mut file = File::create(&path).unwrap();
file.write_all(bytes).unwrap();
drop(file);
(path.clone(), File::open(path).unwrap())
}
fn pattern(len: usize) -> Vec<u8> {
(0..len)
.map(|i| (i.wrapping_mul(31) ^ (i >> 7)) as u8)
.collect()
}
#[test]
fn every_consumer_sees_the_whole_span_in_order() {
let data = pattern(CHUNK_BYTES * 2 + 12345);
let (path, file) = temp_file("span", &data);
let collected: Vec<Vec<u8>> =
with_read_ahead(&file, 100, data.len() as u64 - 100, 2, |receivers| {
thread::scope(|scope| {
let handles: Vec<_> = receivers
.into_iter()
.map(|rx| {
scope.spawn(move || {
let mut out = Vec::new();
let mut expected = 0u64;
for item in rx {
let chunk = item.unwrap();
assert_eq!(chunk.offset, expected);
expected += chunk.len() as u64;
out.extend_from_slice(&chunk);
}
out
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
})
});
for out in collected {
assert_eq!(out, data[100..]);
}
std::fs::remove_file(path).unwrap();
}
#[test]
fn a_file_shorter_than_the_span_is_an_unexpected_eof() {
let data = pattern(1000);
let (path, file) = temp_file("short", &data);
let last = with_read_ahead(&file, 0, 5000, 1, |mut receivers| {
let rx = receivers.remove(0);
let mut last = None;
for item in rx {
last = Some(item.map(|c| c.len()));
}
last
});
let error = last.unwrap().unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof);
std::fs::remove_file(path).unwrap();
}
#[test]
fn dropping_the_receivers_early_stops_the_reader() {
let data = pattern(CHUNK_BYTES * 3);
let (path, file) = temp_file("early", &data);
let value = with_read_ahead(&file, 0, data.len() as u64, 1, |receivers| {
drop(receivers);
7
});
assert_eq!(value, 7);
std::fs::remove_file(path).unwrap();
}
#[test]
fn an_empty_span_yields_no_chunks() {
let (path, file) = temp_file("empty", b"abc");
let count = with_read_ahead(&file, 3, 0, 1, |mut r| r.remove(0).into_iter().count());
assert_eq!(count, 0);
std::fs::remove_file(path).unwrap();
}
}