//! The merged, sorted index over every raw file in a session, and the queries on top of it. //! //! `timeline.jsonl` holds one line per record: its time on every clock plus a *reference* //! (`file`, `offset`, `len`) into a raw file. Raw data is never copied or rewritten, so the index //! can be rebuilt at any time (`reindex`) and the streams stay separate. //! //! Queries binary-search the sorted file by byte offset, so asking about one second of a //! multi-gigabyte session does not load the index into memory. //! //! # The pieces //! //! | Item | Does | //! |---|---| //! | [`build`] | reads the raw files and the manifest, and writes `timeline.jsonl` | //! | [`query`] | the records whose time is in a range of video time, optionally narrowed by a [`Filter`] | //! | [`summary`] | a per-bucket digest of the whole recording ([`Bucket`]) | //! | [`locate`] | the reverse: a [`Locator`] (a UTC time, a log line, an event) to its video time ([`Located`]) | //! | [`render`], [`strip_ansi`], [`format_wall_us`] | pure formatting of a record, of text, and of a time | //! //! This module reads a session and is the same on every host and for either komorebi flavor. The //! host that recorded it shows only in what is in the raw files (the OS trace of a Mac, or of //! Windows) and in the tick size of the manifest's timebase. Which komorebi produced the log and //! events is not looked at here: it is a matter for `analysis`. //! //! # The file: `timeline.jsonl` //! //! The index is UTF-8, one JSON object per line ([`TimelineEntry`]), each line ending in `\n`, and //! is sorted by `mach_ns`, ascending. Records with the same `mach_ns` are ordered by the order in //! which their source was first met while building (`komorebi-log`, `events`, `recorder`, then the //! OS trace files in order of path), then by file, then by `offset`. [`build`] writes it to //! `timeline.jsonl.tmp` and renames that over `timeline.jsonl`, so a reader never sees a //! half-written index. //! //! | Field | JSON | Is | //! |---|---|---| //! | `video_s` | number | the record's time in video time: seconds since the first captured frame, negative before it. It is the manifest's `video_seconds` of `mach_ns` as the manifest was when the index was built | //! | `mach_ns` | integer | the record's time on the master clock, in nanoseconds (see [`crate::clock`]) | //! | `wall_utc` | string or `null` | the same time as RFC 3339 UTC with microseconds, `2027-01-15T08:00:02.000000Z`, worked out from the manifest's anchors. `null` if that cannot be done, which is if the manifest has none | //! | `source` | string | which stream the record is from, see below | //! | `pid` | integer, left out if unknown | the process the record is about: an OS trace record's `processID`, or the process id a window manager event carries | //! | `file` | string | the raw file, relative to the session directory, always with `/` separators | //! | `offset` | integer | the byte offset in `file` of the start of the record | //! | `len` | integer | how many bytes the record is, including its line terminator | //! | `line` | integer | the record's 1-based line number in `file` | //! | `seq` | integer, left out for all but events | the subscriber event sequence number | //! //! `file`, `offset` and `len` are the reference: the raw record is `len` bytes at `offset` of //! `file`, with a trailing `\n` or `\r\n` removed when it is shown. Nothing but the reference //! points into the raw files, so a raw file edited by hand needs a `reindex`, and an index older //! than its raw files can point into the wrong bytes. //! //! # The sources //! //! | `source` | Raw file | Time of a record | //! |---|---|---| //! | `komorebi-log` ([`SOURCE_KOMOREBI_LOG`]) | `komorebi.log` | the line's UTC time, through the manifest's anchors ([`crate::clock::ClockMap`]) | //! | `events` ([`SOURCE_EVENTS`]) | `events.jsonl` | `recv_mach_ns`, stamped on the master clock when the recorder received it | //! | `recorder` ([`SOURCE_RECORDER`]) | `recorder.jsonl` | the incident's `mach_ns` (see [`crate::incidents`]) | //! | `oslog:komorebi`, `oslog:system`, `oslog:eventlog`, `oslog:all`, `oslog:app:` | every `.ndjson` file in `oslog/` and `oslog/apps/` | `hostNs` if the line has one (the Windows OS trace), else its `machTimestamp` ticks converted with the manifest's timebase | //! //! The OS trace sources keep the `oslog:` prefix on every host, though on Windows it is not the //! unified log. A file's source is the one the manifest lists for it; for a file it does not list, //! such as one added by hand, it comes from the file's name: `komorebi.ndjson` and //! `komorebi-.ndjson` are `oslog:komorebi`, `system.ndjson`, `eventlog.ndjson` and //! `all.ndjson` are `oslog:system`, `oslog:eventlog` and `oslog:all`, and any other is //! `oslog:app:`, with a trailing `-` taken off. //! //! A line is left out of the index if it has no time: a line of `komorebi.log` before the first //! timestamped one, and every line of it if the manifest has no anchors; a row of `events.jsonl` //! or `recorder.jsonl` that is not valid JSON of the right shape, such as one cut short by a crash; //! an OS trace line with neither `hostNs` nor `machTimestamp`. Continuation lines of //! `komorebi.log` (a panic message, a backtrace) are in the index, with the time of the line they //! follow. //! //! # Cost //! //! [`build`] holds one compact record per index entry in memory while it sorts, and reads //! `komorebi.log` whole. [`query`] does not load the index: it finds its starting place by binary //! search on byte offsets, and reads only the lines in the range. [`summary`] reads the whole //! index, one line at a time. [`locate`] does not use the index at all: it reads `komorebi.log` or //! `events.jsonl`, and the manifest. //! //! # Example //! //! Building the index of a small session, and asking it questions: //! //! ```rust //! use chrono::Utc; //! use komorebi_recorder::clock::Anchor; //! use komorebi_recorder::session::{Manifest, Moment, Session, TIMELINE_FILE}; //! use komorebi_recorder::timeline::{self, Filter, Locator, TimelineEntry}; //! //! let dir = std::env::temp_dir().join(format!("komorebi-recorder-doc-timeline-{}", std::process::id())); //! let _ = std::fs::remove_dir_all(&dir); //! let session = Session::create(Some(dir.clone()), Utc::now())?; //! //! // the wall clock read 2027-01-15T08:00:00Z when the master clock read 100 s, which is also //! // when the first video frame was captured: video time 0 is master clock time 100 s //! let anchor = Anchor { wall_us: 1_800_000_000_000_000, mach_ns: 100_000_000_000 }; //! let start = Moment { mach_ns: anchor.mach_ns, wall_us: anchor.wall_us }; //! let mut manifest = Manifest::new(start, vec![anchor]); //! manifest.video_t0_mach_ns = Some(anchor.mach_ns); //! manifest.video_end_mach_ns = Some(110_000_000_000); //! session.write_manifest(&manifest)?; //! //! // komorebi's log is stamped with the wall clock: this line is 2 s into the video //! std::fs::write( //! session.path("komorebi.log"), //! "2027-01-15T08:00:02.000000Z INFO komorebi::process_event: processing event: Show\n", //! )?; //! // an event is stamped with the master clock when it is received, 10 ms later //! std::fs::write( //! session.path("events.jsonl"), //! concat!( //! r#"{"seq":1,"recv_wall_us":1800000002010000,"recv_mach_ns":102010000000,"#, //! r#""event":{"type":"Show","content":[{"type":"Accessibility","content":"AXWindowCreated"},111,7]}}"#, //! "\n", //! ), //! )?; //! //! let stats = timeline::build(&session)?; //! assert_eq!(stats.entries, 2); //! assert_eq!(stats.by_source["komorebi-log"], 1); //! assert_eq!(stats.by_source["events"], 1); //! //! // the index: one entry per record, sorted by time, pointing into the raw files //! let index = std::fs::read_to_string(session.path(TIMELINE_FILE))?; //! let entries: Vec = index //! .lines() //! .map(serde_json::from_str) //! .collect::>()?; //! assert_eq!(entries[0].source, "komorebi-log"); //! assert_eq!(entries[0].video_s, 2.0); //! assert_eq!(entries[0].wall_utc.as_deref(), Some("2027-01-15T08:00:02.000000Z")); //! assert_eq!((entries[0].file.as_str(), entries[0].offset, entries[0].line), ("komorebi.log", 0, 1)); //! assert_eq!(entries[1].source, "events"); //! assert_eq!(entries[1].pid, Some(111)); //! assert_eq!(entries[1].seq, Some(1)); //! //! // what happened between 1.5 s and 2.5 s into the video? //! let records = timeline::query(&session, &manifest, 1.5, 2.5, &Filter::default())?; //! assert_eq!(records.len(), 2); //! assert!(records[0].text.ends_with("processing event: Show")); //! assert!(records[1].text.starts_with("#1 {")); //! //! // only the events //! let only_events = Filter { sources: vec!["events".to_string()], ..Filter::default() }; //! assert_eq!(timeline::query(&session, &manifest, 0.0, 10.0, &only_events)?.len(), 1); //! //! // and the reverse: where in the video is line 1 of komorebi's log? //! let located = timeline::locate(&session, &manifest, &Locator::LogLine(1))?; //! assert_eq!(located.video_s, 2.0); //! assert!(located.in_video); //! # std::fs::remove_dir_all(&dir)?; //! # Ok::<(), Box>(()) //! ``` use crate::clock::ClockMap; use crate::incidents::INCIDENTS_FILE; use crate::incidents::Incident; use crate::session::Manifest; use crate::session::Session; use crate::session::TIMELINE_FILE; use crate::sources::komorebi_events::EventRow; use crate::sources::komorebi_log; use crate::sources::managed_apps; use crate::sources::oslog; use crate::sources::oslog::OsLogRecord; use chrono::DateTime; use chrono::Utc; use color_eyre::eyre; use color_eyre::eyre::WrapErr; use serde::Deserialize; use serde::Serialize; use std::collections::BTreeMap; use std::collections::HashMap; use std::fs::File; use std::io::BufRead; use std::io::BufReader; use std::io::BufWriter; use std::io::Read; use std::io::Seek; use std::io::SeekFrom; use std::io::Write; /// The timeline source of komorebi's log: `komorebi-log`. pub const SOURCE_KOMOREBI_LOG: &str = "komorebi-log"; /// The timeline source of the subscriber's events: `events`. pub const SOURCE_EVENTS: &str = "events"; /// The timeline source of incidents: `recorder` (see [`crate::incidents`]). pub use crate::incidents::SOURCE_RECORDER; /// One line of `timeline.jsonl`: a record's time on every clock, and where the record is. /// /// The fields are written in the order they are declared here. The format of the file, with what /// each field means, is in the [module docs](self#the-file-timelinejsonl). /// /// # Example /// /// ```rust /// use komorebi_recorder::timeline::TimelineEntry; /// /// // `pid` and `seq` are left out when there is none, and `wall_utc` is `null` when unknown /// let entry = TimelineEntry { /// video_s: 2.5, /// mach_ns: 102_500_000_000, /// wall_utc: None, /// source: "recorder".to_string(), /// pid: None, /// file: "recorder.jsonl".to_string(), /// offset: 120, /// len: 98, /// line: 2, /// seq: None, /// }; /// assert_eq!( /// serde_json::to_string(&entry)?, /// r#"{"video_s":2.5,"mach_ns":102500000000,"wall_utc":null,"source":"recorder","file":"recorder.jsonl","offset":120,"len":98,"line":2}"# /// ); /// /// // and a line reads back as it was written /// let back: TimelineEntry = serde_json::from_str(&serde_json::to_string(&entry)?)?; /// assert_eq!(back, entry); /// # Ok::<(), serde_json::Error>(()) /// ``` #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct TimelineEntry { /// Seconds since the first video frame (negative before it). pub video_s: f64, /// The record's time on the master clock, in nanoseconds. pub mach_ns: u64, /// RFC 3339 UTC with microseconds. pub wall_utc: Option, /// Which stream the record is from: `komorebi-log`, `events`, `recorder`, or an OS trace /// source starting `oslog:`. pub source: String, /// The process the record is about, where it has one: an OS trace record's `processID`, or the /// process id carried by a window manager event. #[serde(default, skip_serializing_if = "Option::is_none")] pub pid: Option, /// Raw file, relative to the session directory. pub file: String, /// The byte offset of the start of the record in `file`. pub offset: u64, /// How many bytes the record is in `file`, including its line terminator. pub len: u64, /// 1-based line number in the raw file. pub line: u64, /// The subscriber event sequence number, for `events` records. #[serde(default, skip_serializing_if = "Option::is_none")] pub seq: Option, } /// A timeline entry together with the raw text it points at. /// /// A query returns these. Serialized, a record is its entry's fields followed by `text`. #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Record { /// The index entry. #[serde(flatten)] pub entry: TimelineEntry, /// The raw record, rendered for reading (see [`render`]). pub text: String, } /// Compact in-memory form used only while building. struct Pending { mach_ns: u64, source: u32, file: u32, pid: Option, offset: u64, len: u64, line: u64, seq: Option, } #[derive(Default)] struct Interner { names: Vec, ids: HashMap, } impl Interner { fn id(&mut self, name: &str) -> u32 { if let Some(id) = self.ids.get(name) { return *id; } let id = self.names.len() as u32; self.names.push(name.to_string()); self.ids.insert(name.to_string(), id); id } } /// What [`build`] put in the index. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct BuildStats { /// How many entries the index has. pub entries: u64, /// How many of those are from each source, by source name. A source with no entries is not /// listed. pub by_source: BTreeMap, } fn wall_utc(clock: &ClockMap, mach_ns: u64) -> Option { let wall_us = clock.mach_to_wall(mach_ns)?; format_wall_us(wall_us) } /// Returns a wall clock time as RFC 3339 UTC with microseconds and a `Z`, or `None` if it is /// beyond what can be represented as a date. /// /// The argument is in microseconds since the Unix epoch, as `wall_us` is throughout a session. This /// is the form of `wall_utc` in the index. /// /// # Example /// /// ```rust /// use komorebi_recorder::timeline::format_wall_us; /// /// assert_eq!( /// format_wall_us(1_800_000_000_250_000).as_deref(), /// Some("2027-01-15T08:00:00.250000Z") /// ); /// assert_eq!(format_wall_us(0).as_deref(), Some("1970-01-01T00:00:00.000000Z")); /// assert_eq!(format_wall_us(i64::MAX), None); /// ``` #[must_use] pub fn format_wall_us(wall_us: i64) -> Option { DateTime::::from_timestamp_micros(wall_us) .map(|time| time.format("%Y-%m-%dT%H:%M:%S%.6fZ").to_string()) } /// Which timeline source an unknown file under `oslog/` belongs to, from its name alone. Used for /// hand-added files and when the manifest does not list a stream. fn source_for_oslog_file(relative: &str) -> String { let name = relative.strip_prefix("oslog/").unwrap_or(relative); match name { "komorebi.ndjson" => "oslog:komorebi".to_string(), _ if name.starts_with("komorebi-") && name.ends_with(".ndjson") => { "oslog:komorebi".to_string() } "system.ndjson" => "oslog:system".to_string(), "eventlog.ndjson" => "oslog:eventlog".to_string(), "all.ndjson" => "oslog:all".to_string(), _ => { let stem = name .strip_prefix("apps/") .unwrap_or(name) .trim_end_matches(".ndjson"); let exe = stem.rsplit_once('-').map_or(stem, |(exe, _pid)| exe); format!("oslog:app:{exe}") } } } fn list_oslog_files(session: &Session) -> Vec { let mut files = Vec::new(); for sub in ["oslog", "oslog/apps"] { let Ok(entries) = std::fs::read_dir(session.path(sub)) else { continue; }; for entry in entries.flatten() { let name = entry.file_name().to_string_lossy().into_owned(); if name.ends_with(".ndjson") { files.push(format!("{sub}/{name}")); } } } files.sort(); files } /// Builds `timeline.jsonl` from the raw files and the manifest. /// /// Every raw file the session has is read (see the sources in the [module docs](self#the-sources)), /// each record is given its time on the master clock, and the entries are written sorted, replacing /// any existing index. A raw file the session does not have is skipped, so a session with no /// events, say, has no `events` entries. The raw files are only read. The index is written to /// `timeline.jsonl.tmp` and renamed over `timeline.jsonl`, so the old index stays whole until the /// new one is. /// /// Building twice from the same raw files and manifest gives the same index (the test /// `reindex_is_idempotent_and_recovers_a_deleted_timeline`). /// /// # Errors /// /// Returns an error if /// /// * the manifest cannot be read (see [`Session::manifest`]); /// * a raw file that exists cannot be read; /// * `timeline.jsonl.tmp` cannot be created or written; /// * the finished file cannot be renamed over `timeline.jsonl`. /// /// # Example /// /// See the [module example](self#example), which builds the index of a session and reads it back. pub fn build(session: &Session) -> eyre::Result { let manifest = session.manifest()?; let clock = ClockMap::new(manifest.anchors.clone()); let mut sources = Interner::default(); let mut files = Interner::default(); let mut pending: Vec = Vec::new(); // komorebi's own log: UTC wall clock -> mach via the anchors let log_path = session.path("komorebi.log"); if log_path.is_file() { let bytes = std::fs::read(&log_path)?; let source = sources.id(SOURCE_KOMOREBI_LOG); let file = files.id("komorebi.log"); for line in komorebi_log::index_lines(&bytes) { let Some(timestamp) = line.timestamp else { continue; }; let Some(mach_ns) = clock.wall_to_mach(timestamp.timestamp_micros()) else { continue; }; pending.push(Pending { mach_ns, source, file, pid: None, offset: line.offset, len: line.len, line: line.number, seq: None, }); } } // subscriber events: stamped on the mach clock at receipt let events_path = session.path("events.jsonl"); if events_path.is_file() { let source = sources.id(SOURCE_EVENTS); let file = files.id("events.jsonl"); let mut reader = BufReader::new(File::open(&events_path)?); let mut buffer = String::new(); let (mut offset, mut number) = (0_u64, 0_u64); loop { buffer.clear(); let read = reader.read_line(&mut buffer)?; if read == 0 { break; } number += 1; if let Ok(row) = serde_json::from_str::(&buffer) { pending.push(Pending { mach_ns: row.recv_mach_ns, source, file, pid: row .event .as_ref() .and_then(managed_apps::event_pid) .map(i64::from), offset, len: read as u64, line: number, seq: Some(row.seq), }); } offset += read as u64; } } // incidents (display changes, sleep/wake, restarts): stamped on the mach clock when noticed let incidents_path = session.path(INCIDENTS_FILE); if incidents_path.is_file() { let source = sources.id(SOURCE_RECORDER); let file = files.id(INCIDENTS_FILE); let mut reader = BufReader::new(File::open(&incidents_path)?); let mut buffer = String::new(); let (mut offset, mut number) = (0_u64, 0_u64); loop { buffer.clear(); let read = reader.read_line(&mut buffer)?; if read == 0 { break; } number += 1; if let Ok(incident) = serde_json::from_str::(&buffer) { pending.push(Pending { mach_ns: incident.mach_ns, source, file, pid: None, offset, len: read as u64, line: number, seq: None, }); } offset += read as u64; } } // unified log streams: already on the mach clock let manifest_sources: HashMap<&str, &str> = manifest .oslog .iter() .map(|info| (info.spec.file.as_str(), info.spec.source.as_str())) .collect(); for relative in list_oslog_files(session) { let source_name = manifest_sources.get(relative.as_str()).map_or_else( || source_for_oslog_file(&relative), |source| (*source).to_string(), ); let source = sources.id(&source_name); let file = files.id(&relative); let mut reader = BufReader::with_capacity(256 * 1024, File::open(session.path(&relative))?); let mut buffer = Vec::new(); let (mut offset, mut number) = (0_u64, 0_u64); loop { buffer.clear(); let read = reader.read_until(b'\n', &mut buffer)?; if read == 0 { break; } number += 1; // converted with the session's own timebase, not this machine's: a session recorded on // one OS is read on another if let Some(mach_ns) = oslog::extract_time_ns(&buffer, manifest.timebase) { pending.push(Pending { mach_ns, source, file, pid: extract_pid(&buffer), offset, len: read as u64, line: number, seq: None, }); } offset += read as u64; } } pending.sort_by_key(|entry| (entry.mach_ns, entry.source, entry.file, entry.offset)); let path = session.path(TIMELINE_FILE); let temporary = session.path(format!("{TIMELINE_FILE}.tmp")); let mut writer = BufWriter::new( File::create(&temporary) .wrap_err_with(|| format!("could not create {}", temporary.display()))?, ); let mut stats = BuildStats::default(); for entry in &pending { let source = &sources.names[entry.source as usize]; let row = TimelineEntry { video_s: manifest.video_seconds(entry.mach_ns), mach_ns: entry.mach_ns, wall_utc: wall_utc(&clock, entry.mach_ns), source: source.clone(), pid: entry.pid, file: files.names[entry.file as usize].clone(), offset: entry.offset, len: entry.len, line: entry.line, seq: entry.seq, }; writeln!(writer, "{}", serde_json::to_string(&row)?)?; stats.entries += 1; *stats.by_source.entry(source.clone()).or_default() += 1; } writer.flush()?; drop(writer); std::fs::rename(&temporary, &path)?; Ok(stats) } /// Pull `"processID":` out of a raw ndjson line. fn extract_pid(line: &[u8]) -> Option { const KEY: &[u8] = b"\"processID\":"; let start = line.windows(KEY.len()).position(|window| window == KEY)? + KEY.len(); let digits: Vec = line[start..] .iter() .copied() .take_while(|byte| byte.is_ascii_digit() || *byte == b'-') .collect(); std::str::from_utf8(&digits).ok()?.parse().ok() } /// Narrowing for queries: which sources, and which application, to keep. /// /// The default keeps every record. When both fields are set, a record must pass both. /// /// # Example /// /// The two fields combine, and `app` keeps an application's OS trace records only, never the /// komorebi log or events that merely mention it: /// /// ```rust /// use komorebi_recorder::timeline::Filter; /// /// // the OS trace of one application, by exe name (any case) or by process id /// let ghostty = Filter { app: Some("ghostty".to_string()), sources: vec![] }; /// let by_pid = Filter { app: Some("111".to_string()), ..Filter::default() }; /// /// // two sources: komorebi's log, and the OS trace of the komorebi process /// let two = Filter { /// sources: vec!["komorebi-log".to_string(), "oslog:komorebi".to_string()], /// ..Filter::default() /// }; /// # let _ = (ghostty, by_pid, two); /// ``` /// /// The behavior is covered by the tests `source_filter_supports_prefixes` and /// `app_filter_returns_only_that_apps_records`. #[derive(Debug, Clone, Default)] pub struct Filter { /// An app's exe name (case-insensitive) or a pid. /// /// Keeps only OS trace records (sources starting `oslog:`) of that app: those with its process /// id, or whose source is `oslog:app:`. A name is looked up in the manifest's apps to /// find its process ids. pub app: Option, /// Sources to keep: `komorebi-log`, `events`, `oslog` (all OS trace), `oslog:komorebi`, /// `oslog:system`, `oslog:app` (all apps) or `oslog:app:`. Empty keeps everything. /// /// A name matches a source if it equals it, ignoring case, or is a prefix of it that ends /// where the source has a `:`. So `oslog` keeps `oslog:system`, but `osl` keeps nothing. pub sources: Vec, } fn source_matches(source: &str, wanted: &str) -> bool { source.eq_ignore_ascii_case(wanted) || source.get(..wanted.len()).is_some_and(|prefix| { prefix.eq_ignore_ascii_case(wanted) && source.as_bytes().get(wanted.len()) == Some(&b':') }) } /// The pids and source labels an `--app` argument refers to, using the manifest's app list. fn resolve_app(manifest: &Manifest, app: &str) -> (Vec, String) { if let Ok(pid) = app.parse::() { return (vec![pid], String::new()); } let pids = manifest .apps .iter() .filter(|record| record.exe.eq_ignore_ascii_case(app)) .map(|record| i64::from(record.pid)) .collect(); (pids, format!("oslog:app:{app}")) } impl Filter { fn accepts(&self, entry: &TimelineEntry, app: Option<&(Vec, String)>) -> bool { if !self.sources.is_empty() && !self .sources .iter() .any(|wanted| source_matches(&entry.source, wanted)) { return false; } if let Some((pids, source)) = app { let by_pid = entry.pid.is_some_and(|pid| pids.contains(&pid)); let by_source = !source.is_empty() && entry.source.eq_ignore_ascii_case(source); // `--app` is "only this app's records": the komorebi log and events are not that // app's, even though events may mention its pid let is_app_data = entry.source.starts_with("oslog:"); return is_app_data && (by_pid || by_source); } true } } fn read_entry_line( reader: &mut BufReader, buffer: &mut String, ) -> eyre::Result> { buffer.clear(); let read = reader.read_line(buffer)?; if read == 0 { return Ok(None); } let entry: TimelineEntry = serde_json::from_str(buffer.trim_end()) .wrap_err("timeline.jsonl contains an invalid line; run `reindex`")?; Ok(Some((entry, read as u64))) } /// The byte offset of the first line whose `mach_ns` is `>= target`, or the file length. fn lower_bound(file: &mut BufReader, size: u64, target: u64) -> eyre::Result { let mut buffer = String::new(); // the first line start at or after `position` let line_start_at_or_after = |file: &mut BufReader, position: u64| -> eyre::Result { if position == 0 { return Ok(0); } file.seek(SeekFrom::Start(position - 1))?; let mut skipped = Vec::new(); let read = file.read_until(b'\n', &mut skipped)?; Ok(position - 1 + read as u64) }; let (mut low, mut high) = (0_u64, size); while low < high { let middle = low + (high - low) / 2; let start = line_start_at_or_after(file, middle)?; if start >= high { high = middle; continue; } file.seek(SeekFrom::Start(start))?; match read_entry_line(file, &mut buffer)? { Some((entry, length)) => { if entry.mach_ns < target { low = start + length; } else { high = start; } } None => high = middle, } } Ok(low) } /// Raw files opened on demand while rendering records. struct RawFiles<'a> { session: &'a Session, open: HashMap, } impl<'a> RawFiles<'a> { fn new(session: &'a Session) -> Self { Self { session, open: HashMap::new(), } } fn read(&mut self, entry: &TimelineEntry) -> eyre::Result { if !self.open.contains_key(&entry.file) { let path = self.session.path(&entry.file); let file = File::open(&path).wrap_err_with(|| format!("could not open {}", path.display()))?; self.open.insert(entry.file.clone(), file); } let file = self .open .get_mut(&entry.file) .ok_or_else(|| eyre::Report::msg("raw file vanished"))?; file.seek(SeekFrom::Start(entry.offset))?; let mut bytes = vec![0_u8; entry.len as usize]; file.read_exact(&mut bytes)?; Ok(String::from_utf8_lossy(&bytes) .trim_end_matches(['\n', '\r']) .to_string()) } } const EVENT_TEXT_LIMIT: usize = 400; /// Renders a raw record for reading: one line of text for the entry `entry`, whose raw text is /// `raw`. /// /// What it does depends on the entry's source: /// /// | Source | Rendered as | /// |---|---| /// | `komorebi-log` | the raw line with ANSI escapes removed ([`strip_ansi`]) | /// | `recorder` | `: ` | /// | `events` | `# `, then ` state=states/.json` if the event stored a state (the id is zero padded to 6 digits) | /// | anything else, the OS trace | `