//! What the terminal said, on disk, bounded. //! //! Terminal output is NEVER a row (design: "rows for facts, streams for //! bytes"). It is a live stream and one file per session, and this module is //! the file: an append-only log that never grows past //! [`SCROLLBACK_CAP_BYTES`], and a tail a phone replays when it attaches. //! //! THE BOUND IS A POST-CONDITION, NOT A HOPE. `append` writes first and then, //! if the file is over the cap, rewrites it keeping the last //! `cap - COMPACT_SLACK_BYTES` bytes. So the file is at most `cap` when //! `append` returns, and a compaction costs one rewrite per //! `COMPACT_SLACK_BYTES` written rather than one per write — which is the //! difference between eight megabytes of copying every 64 KiB of terminal //! output and eight megabytes of copying every megabyte of it. //! //! The cut is at a BYTE, not at a line or a UTF-8 boundary, because a terminal //! stream has neither: the bytes are an escape-sequence dialect and the //! attaching terminal emulator resynchronises on its own. What the offset //! guarantees is only that a byte's position is the same number for everybody. use std::fs::{File, OpenOptions}; use std::io::{Read as _, Seek as _, SeekFrom, Write as _}; use std::path::{Path, PathBuf}; /// The ring's size: eight megabytes per session. /// /// Big enough that a day's `cargo` output does not evict the morning's plan; /// small enough that four sessions on a 16 GB Mac cost 32 MB of disk and /// nothing of memory, because the ring IS the file. pub const SCROLLBACK_CAP_BYTES: u64 = 8 * 1024 * 1024; /// How far below the cap a compaction cuts. pub const COMPACT_SLACK_BYTES: u64 = 1024 * 1024; /// What an attach replays before the live stream starts. /// /// A quarter of a megabyte is several screens of scrollback on a phone and a /// fraction of a second on the socket. pub const REPLAY_TAIL_BYTES: u64 = 256 * 1024; /// A session's scrollback file. #[derive(Debug)] pub struct Scrollback { path: PathBuf, file: File, cap: u64, /// Bytes currently in the file. len: u64, /// Bytes ever written to this session — the number `attach` counts in, so /// it keeps rising across a compaction. offset: u64, } /// What an attach got. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Replay { /// The offset the first returned byte sits at. pub offset: u64, /// The bytes. pub bytes: Vec, } impl Scrollback { /// Open (or create) a session's scrollback at the default cap. pub fn open(path: impl Into) -> std::io::Result { Self::with_cap(path, SCROLLBACK_CAP_BYTES) } /// Open one at an explicit cap — what the tests use, so the ring's bound /// is proved over kilobytes rather than over eight megabytes. pub fn with_cap(path: impl Into, cap: u64) -> std::io::Result { let path = path.into(); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } let file = OpenOptions::new() .create(true) .read(true) .append(true) .open(&path)?; let len = file.metadata()?.len(); Ok(Self { path, file, cap, len, // A daemon that reopens a session's file counts from what is in // it. Offsets are per OPEN, and `attach` is told the offset it got // rather than assuming one — see `Replay`. offset: len, }) } /// The file. pub fn path(&self) -> &Path { &self.path } /// How many bytes this session has ever written. pub fn offset(&self) -> u64 { self.offset } /// How many are still on disk. pub fn len(&self) -> u64 { self.len } /// Whether anything is. pub fn is_empty(&self) -> bool { self.len == 0 } /// Append terminal output, and hold the bound. pub fn append(&mut self, bytes: &[u8]) -> std::io::Result<()> { if bytes.is_empty() { return Ok(()); } self.file.write_all(bytes)?; self.file.flush()?; self.len += bytes.len() as u64; self.offset += bytes.len() as u64; if self.len > self.cap { self.compact()?; } Ok(()) } /// Rewrite the file keeping its last `cap - COMPACT_SLACK_BYTES` bytes. fn compact(&mut self) -> std::io::Result<()> { let keep = self.cap.saturating_sub(COMPACT_SLACK_BYTES).max(1); let tail = self.read_last(keep)?; // Write beside, then rename: a daemon killed mid-compaction leaves // either the old file or the new one, never half of either. let beside = self.path.with_extension("log.compacting"); { let mut scratch = File::create(&beside)?; scratch.write_all(&tail)?; scratch.flush()?; } std::fs::rename(&beside, &self.path)?; self.file = OpenOptions::new() .create(true) .read(true) .append(true) .open(&self.path)?; self.len = tail.len() as u64; Ok(()) } /// The last `want` bytes of the file (all of it, when it is shorter). fn read_last(&self, want: u64) -> std::io::Result> { let take = want.min(self.len); let from = self.len - take; let mut reader = File::open(&self.path)?; reader.seek(SeekFrom::Start(from))?; let mut bytes = Vec::with_capacity(take as usize); reader.take(take).read_to_end(&mut bytes)?; Ok(bytes) } /// What an attaching viewer gets before the live stream. /// /// `from` is where the viewer left off. When that offset is still in the /// file, the replay starts exactly there; when it has been compacted away /// — or was never reached — the replay is the tail, and the returned /// `offset` SAYS SO. A viewer that trusted its own number would render a /// gap as continuity; being told the real offset is what lets it say /// "catching up" instead. pub fn replay(&self, from: Option, max: u64) -> std::io::Result { let earliest = self.offset - self.len; let asked = match from { Some(from) if from >= earliest && from <= self.offset => from, // No offset, or one the ring has already dropped: the tail. _ => earliest, }; // And never more than `max`, whatever was asked for. let start = asked.max(self.offset.saturating_sub(max)).max(earliest); let want = self.offset - start; let bytes = self.read_last(want)?; Ok(Replay { offset: self.offset - bytes.len() as u64, bytes, }) } } #[cfg(test)] #[path = "scrollback_tests.rs"] mod scrollback_tests;