//! 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::{Readas _, Seekas _, SeekFrom, Writeas _};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.pubconst SCROLLBACK_CAP_BYTES: u64 = 8 * 1024 * 1024;/// How far below the cap a compaction cuts.pubconst 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.pubconst REPLAY_TAIL_BYTES: u64 = 256 * 1024;/// A session's scrollback file.#[derive(Debug)]pubstructScrollback { 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)]pubstructReplay {/// The offset the first returned byte sits at.pub offset: u64,/// The bytes.pub bytes: Vec<u8>,}implScrollback {/// Open (or create) a session's scrollback at the default cap.pubfn open(path: implInto<PathBuf>) -> std::io::Result<Self> {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.pubfn with_cap(path: implInto<PathBuf>, cap: u64) -> std::io::Result<Self> {let path = path.into();ifletSome(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.pubfn path(&self) -> &Path { &self.path }/// How many bytes this session has ever written.pubfn offset(&self) -> u64 {self.offset }/// How many are still on disk.pubfn len(&self) -> u64 {self.len }/// Whether anything is.pubfn is_empty(&self) -> bool {self.len == 0 }/// Append terminal output, and hold the bound.pubfn append(&mutself, bytes: &[u8]) -> std::io::Result<()> {if bytes.is_empty() {returnOk(()); }self.file.write_all(bytes)?;self.file.flush()?;self.len += bytes.len() as u64;self.offset += bytes.len() as u64;ifself.len > self.cap {self.compact()?; }Ok(()) }/// Rewrite the file keeping its last `cap - COMPACT_SLACK_BYTES` bytes.fn compact(&mutself) -> 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"); {letmut 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<Vec<u8>> {let take = want.min(self.len);let from = self.len - take;letmut reader = File::open(&self.path)?; reader.seek(SeekFrom::Start(from))?;letmut 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.pubfn replay(&self, from: Option<u64>, max: u64) -> std::io::Result<Replay> {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;