//! The host's own log file, and the one reason it exists. //! //! **The launchd plist names no log path.** `StandardOutPath` and //! `StandardErrorPath` take an absolute path and launchd does not promise to //! expand `~` in either — and the plist carrying one lives INSIDE the app //! bundle, which is the same bytes on every Mac the release lane ships to. A //! home directory stamped in at build time would be one person's path shipped //! to everybody, so the keys are absent and the process points its own stderr //! at `/session-host.log` instead, beside the socket, under the rule //! `data_dir.rs` already keeps. //! //! **It is bounded.** A daemon with `KeepAlive` writes for months; a log //! nobody rotates is a disk nobody gets back. The cap is a decision //! ([`log_start`]), it is pure, and it is taken once — at the start of a //! `serve`, which is also the only moment a truncation cannot lose a line //! somebody is reading. use std::fs::{File, OpenOptions}; use std::io; use std::path::Path; /// How large the log may be when a `serve` opens it. /// /// Two mebibytes is tens of thousands of lines — every start, every refusal /// and every session this host has hosted since the last restart — and it is /// the size at which reading the file still costs nothing. pub const LOG_CAP_BYTES: u64 = 2 * 1024 * 1024; /// What opening the log at the start of a run should do. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LogStart { /// Keep what is there and write after it. Append, /// Start the file again: the last runs filled it. Fresh, } /// **THE DECISION.** Pure, so both arms are held by a test. /// /// At the cap exactly, the file starts again: a log allowed to sit ON the cap /// for ever is a cap that never fires. pub fn log_start(existing_len: u64) -> LogStart { if existing_len >= LOG_CAP_BYTES { LogStart::Fresh } else { LogStart::Append } } /// Open the log for this run, applying [`log_start`] to whatever is there. /// /// A missing file is a length of zero, which appends — the create flag makes /// it. A path that cannot be opened at all is an error the caller reports and /// carries on from: a host that refused to start because it could not write a /// log would be a host that cannot host a session over a disk that is full. pub fn open(path: &Path) -> io::Result { let existing = std::fs::metadata(path).map(|meta| meta.len()).unwrap_or(0); let mut options = OpenOptions::new(); options.create(true).write(true); match log_start(existing) { LogStart::Append => options.append(true), LogStart::Fresh => options.truncate(true), }; options.open(path) } #[cfg(test)] #[path = "log_tests.rs"] mod log_tests;