Skip to main content

iphone_cli/
syslog.rs

1//! `iph syslog`: the phone's log stream, kept in the daemon while a test
2//! runs, so what an app logged after a tap can be read back.
3//!
4//! One capture per daemon. The stream is read by a task of its own that never
5//! touches the session, so commands keep working while it runs. An entry that
6//! passes the filters goes into a ring buffer bounded by entry count and by
7//! bytes and gets a `seq` (1 for the first). `read` returns what is newer than
8//! a `seq` the caller already has and says where to continue; the buffer goes
9//! with the capture. With `output` the kept entries are also written to a
10//! JSON Lines file: a `start` line, the entries, and an `end` line that says
11//! why the capture ended. A file without an `end` line belongs to a daemon
12//! that was killed.
13
14use std::{
15    collections::VecDeque,
16    fs::File,
17    io::{BufWriter, Write},
18    path::{Path, PathBuf},
19    sync::{Arc, Mutex, Weak},
20    time::Duration,
21};
22
23use idevice::{
24    IdeviceError,
25    core_device::AppListEntry,
26    os_trace_relay::{LogLevel, OsTraceLog, OsTraceRelayReceiver},
27};
28use regex::Regex;
29use serde_json::{Map, Value, json};
30
31use crate::{
32    clock,
33    device::session::{Session, plain_path},
34    fields, paths,
35    reply::{Fail, Res},
36    tcp::handle::Reset,
37};
38
39/// The buffer's defaults. Unfiltered over Wi-Fi the phone sent about 4,800
40/// entries/s, 1.4 MB/s, 290 B an entry as JSON; 100,000 entries hold about
41/// 20 s of that worst case, longer than a sensible gap between a tap and the
42/// `read` after it, and minutes of a filtered capture. In memory an entry
43/// weighs more than its JSON (see `Entry::weight`): about 430 B for one of
44/// 290 B of JSON, so 100,000 of them take about 41 MiB. The 64 MiB limit
45/// binds once messages average more than about 540 B.
46const DEFAULT_BUFFER_ENTRIES: u64 = 100_000;
47const MAX_BUFFER_ENTRIES: u64 = 1_000_000;
48const DEFAULT_BUFFER_MB: u64 = 64;
49const MAX_BUFFER_MB: u64 = 1024;
50const DEFAULT_MAX_MB: u64 = 64;
51/// The most `max_mb` takes. A part is read back whole by whoever opens it.
52const MAX_FILE_MB: u64 = 4096;
53const DEFAULT_MATCHES: u64 = 50;
54const MAX_MATCHES: u64 = 1000;
55/// Longest message a reply returns; the file keeps the whole message.
56const MATCH_CHARS: usize = 500;
57/// How long a written line may wait in the buffer before it is flushed.
58const FLUSH_EVERY: Duration = Duration::from_millis(250);
59const FILE_BUFFER: usize = 32 * 1024;
60
61/// Severity, lowest first. The device's own codes are not in this order.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
63pub enum Level {
64    Debug,
65    Info,
66    Notice,
67    Error,
68    Fault,
69}
70
71impl Level {
72    pub fn name(self) -> &'static str {
73        match self {
74            Level::Debug => "debug",
75            Level::Info => "info",
76            Level::Notice => "notice",
77            Level::Error => "error",
78            Level::Fault => "fault",
79        }
80    }
81
82    fn parse(s: &str) -> Option<Self> {
83        Some(match s.to_ascii_lowercase().as_str() {
84            "debug" => Level::Debug,
85            "info" => Level::Info,
86            // Apple's tools call this level "default".
87            "notice" | "default" => Level::Notice,
88            "error" => Level::Error,
89            "fault" => Level::Fault,
90            _ => return None,
91        })
92    }
93}
94
95impl From<LogLevel> for Level {
96    fn from(level: LogLevel) -> Self {
97        match level {
98            LogLevel::Debug => Level::Debug,
99            LogLevel::Info => Level::Info,
100            LogLevel::Notice => Level::Notice,
101            LogLevel::Error => Level::Error,
102            LogLevel::Fault => Level::Fault,
103        }
104    }
105}
106
107/// One log entry as it is kept. Its `seq` belongs to the buffer, not to it.
108#[derive(Debug, Clone, PartialEq)]
109pub struct Entry {
110    /// UTC.
111    pub time: String,
112    pub pid: u32,
113    /// The executable's file name, the same across restarts of the app.
114    pub process: String,
115    /// The library or executable that logged it.
116    pub sender: String,
117    pub level: Level,
118    pub subsystem: Option<String>,
119    pub category: Option<String>,
120    pub message: String,
121}
122
123/// The library hands the device's microseconds to a constructor that takes
124/// nanoseconds (idevice 0.1.68), so the sub-second part arrives as micros.
125fn utc_micros(secs: i64, micros: u32) -> String {
126    let whole = clock::format_utc(secs);
127    format!("{}.{:06}Z", whole.trim_end_matches('Z'), micros.min(999_999))
128}
129
130fn file_name(path: &str) -> &str {
131    path.rsplit('/').next().unwrap_or(path)
132}
133
134impl From<OsTraceLog> for Entry {
135    fn from(log: OsTraceLog) -> Self {
136        entry_and_executable(log).0
137    }
138}
139
140/// The entry, and the path of the executable that logged it, which is only
141/// for the filter: the buffer keeps the file name alone.
142fn entry_and_executable(log: OsTraceLog) -> (Entry, String) {
143    let (subsystem, category) = match log.label {
144        Some(l) => (Some(l.subsystem), Some(l.category)),
145        None => (None, None),
146    };
147    let entry = Entry {
148        time: utc_micros(log.timestamp.and_utc().timestamp(), log.timestamp.and_utc().timestamp_subsec_nanos()),
149        pid: log.pid,
150        process: file_name(&log.filename).to_string(),
151        sender: file_name(&log.image_name).to_string(),
152        level: log.level.into(),
153        subsystem,
154        category,
155        message: log.message,
156    };
157    (entry, log.filename)
158}
159
160impl Entry {
161    /// The entry as a reply or the file shows it. A message longer than
162    /// `max_chars` is cut and marked with `message_cut`.
163    fn value(&self, seq: u64, max_chars: usize) -> Value {
164        let mut v = json!({
165            "seq": seq,
166            "time": self.time,
167            "pid": self.pid,
168            "process": self.process,
169            "sender": self.sender,
170            "level": self.level.name(),
171        });
172        if let Some(s) = &self.subsystem {
173            v["subsystem"] = json!(s);
174        }
175        if let Some(c) = &self.category {
176            v["category"] = json!(c);
177        }
178        if self.message.len() > max_chars && self.message.chars().count() > max_chars {
179            v["message"] = json!(self.message.chars().take(max_chars).collect::<String>());
180            v["message_cut"] = json!(true);
181        } else {
182            v["message"] = json!(self.message);
183        }
184        v
185    }
186
187    /// The file's line: the whole message.
188    pub fn line(&self, seq: u64) -> String {
189        self.value(seq, usize::MAX).to_string()
190    }
191
192    /// What the buffer counts against its byte budget: the text, the struct
193    /// and a flat allowance for the six allocations behind it. An estimate,
194    /// not an allocator's figure; above the entry's JSON.
195    fn weight(&self) -> usize {
196        const ALLOCATOR_SLACK: usize = 96;
197        std::mem::size_of::<Entry>()
198            + ALLOCATOR_SLACK
199            + self.time.len()
200            + self.process.len()
201            + self.sender.len()
202            + self.subsystem.as_ref().map_or(0, String::len)
203            + self.category.as_ref().map_or(0, String::len)
204            + self.message.len()
205    }
206}
207
208/// An installed app, by where it lives on the phone.
209#[derive(Debug, Clone, PartialEq)]
210pub struct AppBundle {
211    pub bundle_id: String,
212    /// The bundle directory (`.../Papago.app`), as `plain_path` spells it.
213    pub path: String,
214}
215
216impl AppBundle {
217    /// `None` when the phone gave no absolute path to match against.
218    pub fn new(bundle_id: &str, path: &str) -> Option<Self> {
219        let path = plain_path(path);
220        path.starts_with('/').then(|| Self { bundle_id: bundle_id.to_string(), path })
221    }
222
223    /// Whether `executable` (already `plain_path`ed) lies in the bundle: the
224    /// app's own executable and its extensions, not a path that only starts
225    /// with the same letters.
226    fn contains(&self, executable: &str) -> bool {
227        executable.strip_prefix(self.path.as_str()).is_some_and(|rest| rest.starts_with('/'))
228    }
229}
230
231/// The app in `apps` with this bundle id.
232fn find_bundle(apps: &[AppListEntry], bundle_id: &str) -> Option<AppBundle> {
233    apps.iter().find(|a| a.bundle_identifier == bundle_id).and_then(|a| AppBundle::new(bundle_id, &a.path))
234}
235
236fn bundles_in(listed: &[AppListEntry], apps: &[String]) -> Res<Vec<AppBundle>> {
237    let mut found: Vec<AppBundle> = Vec::new();
238    for app in apps {
239        let bundle_id = crate::actions::bundle_id_in(listed, app)?;
240        if found.iter().any(|b| b.bundle_id == bundle_id) {
241            continue;
242        }
243        found.push(find_bundle(listed, &bundle_id).ok_or_else(|| {
244            Fail::not_sent("app_not_found", format!("no installed app has the bundle id {bundle_id}, or the phone gave no path for it"))
245                .hint(crate::i18n::t(
246                    "`iph apps`로 이름과 bundle id를 확인하세요.",
247                    "See names and bundle ids with `iph apps`.",
248                ))
249        })?);
250    }
251    Ok(found)
252}
253
254/// What is kept on this side. A pid is filtered by the phone instead.
255///
256/// With neither `processes` nor `apps` every entry passes. With either, an
257/// entry passes when it is from any listed process or any listed app;
258/// `min_level` then applies on top of that.
259#[derive(Debug, Clone, Default, PartialEq)]
260pub struct Filter {
261    pub processes: Vec<String>,
262    pub apps: Vec<AppBundle>,
263    pub min_level: Option<Level>,
264}
265
266impl Filter {
267    /// `executable` is the logging process's path as the phone gave it.
268    pub fn keeps(&self, e: &Entry, executable: &str) -> bool {
269        let selected = (self.processes.is_empty() && self.apps.is_empty())
270            || self.processes.contains(&e.process)
271            || (!self.apps.is_empty() && {
272                let executable = plain_path(executable);
273                self.apps.iter().any(|app| app.contains(&executable))
274            });
275        selected && self.min_level.is_none_or(|min| e.level >= min)
276    }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq)]
280pub struct Limits {
281    pub entries: usize,
282    pub bytes: usize,
283}
284
285#[derive(Debug, Clone, PartialEq)]
286pub struct FileSpec {
287    pub path: PathBuf,
288    pub max_bytes: u64,
289}
290
291#[derive(Debug, Clone, PartialEq)]
292pub struct Spec {
293    pub processes: Vec<String>,
294    /// As given: a bundle id or a name, resolved when the capture starts.
295    pub apps: Vec<String>,
296    pub min_level: Option<Level>,
297    pub pid: Option<u32>,
298    pub limits: Limits,
299    /// Only when `output` is given: nothing is written to disk otherwise.
300    pub file: Option<FileSpec>,
301}
302
303#[derive(Debug)]
304pub struct Query {
305    pub grep: Option<Regex>,
306    pub max: usize,
307}
308
309#[derive(Debug)]
310pub enum Request {
311    Start(Spec),
312    /// Entries newer than `after` (0: from the start), without stopping.
313    Read { after: u64, query: Query },
314    /// `None`: report the counts only.
315    Stop(Option<Query>),
316    Status,
317}
318
319/// Parse the arguments every surface sends. A given `output` must be
320/// absolute, since the daemon writes it.
321pub fn parse(args: &Value) -> Res<Request> {
322    let given: Map<String, Value> = match args {
323        Value::Null => Map::new(),
324        Value::Object(m) => m.iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k.clone(), v.clone())).collect(),
325        _ => return Err(Fail::invalid("syslog takes an object of arguments")),
326    };
327    let action = given
328        .get("action")
329        .and_then(|v| v.as_str())
330        .ok_or_else(|| Fail::invalid("syslog needs an action: start, read, stop or status"))?;
331    let allowed: &[&str] = match action {
332        "start" => &["action", "process", "app", "pid", "level", "output", "max_mb", "buffer_entries", "buffer_mb"],
333        "read" => &["action", "after", "grep", "max"],
334        "stop" => &["action", "grep", "max"],
335        "status" => &["action"],
336        other => return Err(Fail::invalid(format!("unknown syslog action `{other}` (start, read, stop, status)"))),
337    };
338    if let Some(key) = given.keys().find(|k| !allowed.contains(&k.as_str())) {
339        return Err(Fail::invalid(format!("`syslog {action}` takes no `{key}`")));
340    }
341    let number = |key: &str| -> Res<Option<u64>> {
342        match given.get(key) {
343            None => Ok(None),
344            Some(v) => v.as_u64().map(Some).ok_or_else(|| Fail::invalid(format!("`{key}` takes a whole number"))),
345        }
346    };
347    let sized = |key: &str, default: u64, most: u64| -> Res<u64> {
348        let n = number(key)?.unwrap_or(default);
349        if (1..=most).contains(&n) {
350            Ok(n)
351        } else {
352            Err(Fail::invalid(format!("`{key}` takes a whole number from 1 to {most}")))
353        }
354    };
355    let names = |key: &str| -> Res<Vec<String>> {
356        match given.get(key) {
357            None => Ok(Vec::new()),
358            Some(Value::String(s)) => Ok(vec![s.clone()]),
359            Some(Value::Array(a)) => a
360                .iter()
361                .map(|v| v.as_str().map(String::from))
362                .collect::<Option<Vec<_>>>()
363                .ok_or_else(|| Fail::invalid(format!("`{key}` takes names"))),
364            Some(_) => Err(Fail::invalid(format!("`{key}` takes a name or a list of names"))),
365        }
366    };
367    let grep = || -> Res<Option<Regex>> {
368        match given.get("grep") {
369            None => Ok(None),
370            Some(v) => {
371                let pattern = v.as_str().ok_or_else(|| Fail::invalid("`grep` takes a regular expression"))?;
372                Ok(Some(Regex::new(pattern).map_err(|e| Fail::invalid(format!("`grep`: {e}")))?))
373            }
374        }
375    };
376    match action {
377        "start" => {
378            let processes = names("process")?;
379            if processes.iter().any(|p| p.is_empty() || p.contains('/')) {
380                return Err(Fail::invalid("`process` takes executable names such as Preferences, not paths"));
381            }
382            let apps = names("app")?;
383            if apps.iter().any(|a| a.trim().is_empty()) {
384                return Err(Fail::invalid("`app` takes a bundle id or an app's name, as `iph launch` does"));
385            }
386            let min_level = match given.get("level") {
387                None => None,
388                Some(v) => Some(v.as_str().and_then(Level::parse).ok_or_else(|| {
389                    Fail::invalid("`level` takes debug, info, notice, error or fault")
390                })?),
391            };
392            let pid = match number("pid")? {
393                None => None,
394                Some(n) => Some(u32::try_from(n).map_err(|_| Fail::invalid("`pid` is out of range"))?),
395            };
396            let limits = Limits {
397                entries: usize::try_from(sized("buffer_entries", DEFAULT_BUFFER_ENTRIES, MAX_BUFFER_ENTRIES)?)
398                    .map_err(|_| Fail::invalid("`buffer_entries` is out of range"))?,
399                bytes: sized("buffer_mb", DEFAULT_BUFFER_MB, MAX_BUFFER_MB)?
400                    .checked_mul(1024 * 1024)
401                    .and_then(|b| usize::try_from(b).ok())
402                    .ok_or_else(|| Fail::invalid("`buffer_mb` is out of range"))?,
403            };
404            let file = match given.get("output") {
405                None if given.contains_key("max_mb") => {
406                    return Err(Fail::invalid("`max_mb` sizes the file that `output` names"));
407                }
408                None => None,
409                Some(v) => {
410                    let path = PathBuf::from(v.as_str().ok_or_else(|| Fail::invalid("`output` takes a path"))?);
411                    if !path.is_absolute() {
412                        return Err(Fail::invalid("`output` must be an absolute path"));
413                    }
414                    let max_bytes = sized("max_mb", DEFAULT_MAX_MB, MAX_FILE_MB)?
415                        .checked_mul(1024 * 1024)
416                        .ok_or_else(|| Fail::invalid("`max_mb` is out of range"))?;
417                    Some(FileSpec { path, max_bytes })
418                }
419            };
420            Ok(Request::Start(Spec { processes, apps, min_level, pid, limits, file }))
421        }
422        "read" => {
423            let max = number("max")?.unwrap_or(DEFAULT_MATCHES);
424            if max == 0 {
425                return Err(Fail::invalid("`max` must be at least 1"));
426            }
427            Ok(Request::Read {
428                after: number("after")?.unwrap_or(0),
429                query: Query { grep: grep()?, max: max.min(MAX_MATCHES) as usize },
430            })
431        }
432        "stop" => {
433            let grep = grep()?;
434            let max = number("max")?;
435            if grep.is_none() && max.is_none() {
436                return Ok(Request::Stop(None));
437            }
438            let max = max.unwrap_or(DEFAULT_MATCHES).min(MAX_MATCHES) as usize;
439            Ok(Request::Stop(Some(Query { grep, max })))
440        }
441        _ => Ok(Request::Status),
442    }
443}
444
445/// The kept entries, newest last. Their seqs run without a gap from
446/// `first_seq` to `newest_seq`, since only the oldest are evicted, so a seq
447/// finds its entry by position.
448pub struct Ring {
449    entries: VecDeque<Entry>,
450    bytes: usize,
451    /// The seq of the next entry kept. The first is 1.
452    next_seq: u64,
453    limits: Limits,
454}
455
456/// One `read`: the matching entries oldest first and where to go on.
457#[derive(Debug, PartialEq)]
458pub struct Page {
459    pub entries: Vec<Value>,
460    /// Pass it as `after` to the next read. Everything up to it has been
461    /// returned or did not match; nothing after it has been looked at, except
462    /// when it is the newest seq, which means everything has.
463    pub cursor: u64,
464    /// `max` cut the page short: another matching entry is already waiting.
465    pub more: bool,
466    /// Entries newer than `after` that were evicted before this read.
467    pub dropped: u64,
468}
469
470impl Ring {
471    pub fn new(limits: Limits) -> Self {
472        Self { entries: VecDeque::new(), bytes: 0, next_seq: 1, limits }
473    }
474
475    fn first_seq(&self) -> u64 {
476        self.next_seq - self.entries.len() as u64
477    }
478
479    fn newest_seq(&self) -> u64 {
480        self.next_seq - 1
481    }
482
483    /// Keep an entry, evicting the oldest while over a limit. An entry larger
484    /// than the byte budget evicts itself and everything before it.
485    pub fn push(&mut self, entry: Entry) -> u64 {
486        let seq = self.next_seq;
487        self.next_seq += 1;
488        self.bytes += entry.weight();
489        self.entries.push_back(entry);
490        while self.entries.len() > self.limits.entries || self.bytes > self.limits.bytes {
491            let Some(old) = self.entries.pop_front() else { break };
492            self.bytes = self.bytes.saturating_sub(old.weight());
493        }
494        seq
495    }
496
497    pub fn usage(&self) -> Value {
498        let mut v = json!({
499            "entries": self.entries.len(),
500            "bytes": self.bytes,
501            "max_entries": self.limits.entries,
502            "max_bytes": self.limits.bytes,
503            "evicted": self.first_seq() - 1,
504        });
505        if !self.entries.is_empty() {
506            v["oldest_seq"] = json!(self.first_seq());
507        }
508        if self.next_seq > 1 {
509            v["newest_seq"] = json!(self.newest_seq());
510        }
511        v
512    }
513
514    /// The entries newer than `after` whose message matches, at most `max`,
515    /// oldest first. A cursor is only meaningful in the capture that issued
516    /// it, since seqs begin again at 1 with each capture. One that is newer
517    /// than every entry returns nothing and gets the newest seq back, so it
518    /// cannot run ahead of the buffer.
519    pub fn read(&self, after: u64, grep: Option<&Regex>, max: usize) -> Page {
520        let first = self.first_seq();
521        let newest = self.newest_seq();
522        let next = after.saturating_add(1);
523        let skip = usize::try_from(next.saturating_sub(first)).unwrap_or(usize::MAX);
524        let mut entries = Vec::new();
525        let mut last = None;
526        let mut more = false;
527        for (i, entry) in self.entries.iter().enumerate().skip(skip) {
528            if grep.is_some_and(|re| !re.is_match(&entry.message)) {
529                continue;
530            }
531            if entries.len() == max {
532                more = true;
533                break;
534            }
535            let seq = first + i as u64;
536            entries.push(entry.value(seq, MATCH_CHARS));
537            last = Some(seq);
538        }
539        Page {
540            entries,
541            cursor: if more { last.unwrap_or(after.min(newest)) } else { newest },
542            more,
543            dropped: first.saturating_sub(next),
544        }
545    }
546
547    /// The latest `max` entries whose message matches, oldest first, with
548    /// the number that matched in all.
549    pub fn latest(&self, grep: Option<&Regex>, max: usize) -> (Vec<Value>, u64) {
550        let first = self.first_seq();
551        let mut found = VecDeque::new();
552        let mut matched = 0;
553        for (i, entry) in self.entries.iter().enumerate() {
554            if grep.is_some_and(|re| !re.is_match(&entry.message)) {
555                continue;
556            }
557            matched += 1;
558            if max == 0 {
559                continue;
560            }
561            if found.len() == max {
562                found.pop_front();
563            }
564            found.push_back(i);
565        }
566        let entries = found.into_iter().map(|i| self.entries[i].value(first + i as u64, MATCH_CHARS)).collect();
567        (entries, matched)
568    }
569}
570
571/// Where the previous part goes when the file reaches its size.
572pub fn rotated(path: &Path) -> PathBuf {
573    let mut name = path.file_name().unwrap_or_default().to_os_string();
574    name.push(".1");
575    path.with_file_name(name)
576}
577
578fn open_private(path: &Path) -> std::io::Result<BufWriter<File>> {
579    let file = paths::private_file().write(true).create(true).truncate(true).open(path)?;
580    #[cfg(unix)]
581    {
582        // `private_file` sets the mode only on a file it creates.
583        use std::os::unix::fs::PermissionsExt;
584        file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
585    }
586    Ok(BufWriter::with_capacity(FILE_BUFFER, file))
587}
588
589/// The file, kept under a size: once the next line would pass it, the file
590/// becomes `<file>.1` (replacing an older one) and a new file starts.
591///
592/// Writes are buffered. A line reaches the file when the buffer fills, on
593/// `flush` (the capture flushes every `FLUSH_EVERY` and when it ends) and
594/// before a rotation. The buffer only ever holds whole lines, so a killed
595/// process loses at most the last few, never half of one.
596pub struct Sink {
597    path: PathBuf,
598    /// `None` only after a rotation that could reopen neither part.
599    writer: Option<BufWriter<File>>,
600    size: u64,
601    cap: u64,
602    pub rotations: u32,
603}
604
605impl Sink {
606    pub fn create(path: &Path, cap: u64) -> std::io::Result<Self> {
607        let writer = open_private(path)?;
608        // A part left from an earlier capture would read as this one's.
609        let _ = std::fs::remove_file(rotated(path));
610        Ok(Self { path: path.to_path_buf(), writer: Some(writer), size: 0, cap, rotations: 0 })
611    }
612
613    pub fn write(&mut self, line: &str) -> std::io::Result<()> {
614        if self.size > 0 && self.size + line.len() as u64 + 1 > self.cap {
615            self.rotate()?;
616        }
617        self.append(line)
618    }
619
620    /// Without rotating first, for the `end` line: it goes right after the
621    /// last entry, even past the size or after a rotation that failed.
622    fn append(&mut self, line: &str) -> std::io::Result<()> {
623        let bytes = format!("{line}\n");
624        self.writer.as_mut().ok_or_else(Self::closed)?.write_all(bytes.as_bytes())?;
625        self.size += bytes.len() as u64;
626        Ok(())
627    }
628
629    pub fn flush(&mut self) -> std::io::Result<()> {
630        self.writer.as_mut().map_or(Ok(()), |w| w.flush())
631    }
632
633    /// On failure the file that holds the last entry stays open, so the
634    /// `end` line still lands after it.
635    fn rotate(&mut self) -> std::io::Result<()> {
636        // Close the file and clear the old `.1` before the rename, so it
637        // does not depend on how a platform treats an open file or an
638        // existing target.
639        if let Some(writer) = self.writer.as_mut() {
640            writer.flush()?;
641        }
642        self.writer = None;
643        let previous = rotated(&self.path);
644        let renamed = match std::fs::remove_file(&previous) {
645            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
646            _ => std::fs::rename(&self.path, &previous),
647        };
648        if let Err(e) = renamed {
649            self.writer = reopen(&self.path);
650            return Err(e);
651        }
652        match open_private(&self.path) {
653            Ok(writer) => self.writer = Some(writer),
654            Err(e) => {
655                self.writer = reopen(&previous);
656                return Err(e);
657            }
658        }
659        self.size = 0;
660        self.rotations += 1;
661        Ok(())
662    }
663
664    fn closed() -> std::io::Error {
665        std::io::Error::other("the file could not be reopened after a rotation")
666    }
667}
668
669fn reopen(path: &Path) -> Option<BufWriter<File>> {
670    let file = std::fs::OpenOptions::new().append(true).open(path).ok()?;
671    Some(BufWriter::with_capacity(FILE_BUFFER, file))
672}
673
674/// What the reading task and the session share.
675pub struct Live {
676    ring: Ring,
677    sink: Option<Sink>,
678    filter: Filter,
679    pub seen: u64,
680    pub kept: u64,
681    /// Entries the library could not parse; the stream goes on after them.
682    pub unparsed: u64,
683    pub ended: Option<String>,
684}
685
686impl Live {
687    pub fn new(ring: Ring, sink: Option<Sink>, filter: Filter) -> Self {
688        Self { ring, sink, filter, seen: 0, kept: 0, unparsed: 0, ended: None }
689    }
690
691    pub fn take(&mut self, entry: Entry, executable: &str) -> std::io::Result<()> {
692        if self.ended.is_some() {
693            return Ok(());
694        }
695        self.seen += 1;
696        if !self.filter.keeps(&entry, executable) {
697            return Ok(());
698        }
699        let line = self.sink.is_some().then(|| entry.line(self.ring.next_seq));
700        self.ring.push(entry);
701        self.kept += 1;
702        match (self.sink.as_mut(), line) {
703            (Some(sink), Some(line)) => sink.write(&line),
704            _ => Ok(()),
705        }
706    }
707
708    /// A line that is not an entry (`start`, `end`), for the file only.
709    fn note(&mut self, line: &Value) -> std::io::Result<()> {
710        self.sink.as_mut().map_or(Ok(()), |s| s.write(&line.to_string()))
711    }
712
713    /// Write the `end` line once; later calls change nothing.
714    pub fn end(&mut self, reason: &str) {
715        if self.ended.is_some() {
716            return;
717        }
718        let line = json!({
719            "event": "end",
720            "time": clock::now_utc(),
721            "reason": reason,
722            "seen": self.seen,
723            "kept": self.kept,
724            "unparsed": self.unparsed,
725            "rotations": self.sink.as_ref().map_or(0, |s| s.rotations),
726        });
727        // The end line is what tells a reader the capture finished.
728        if let Some(sink) = self.sink.as_mut() {
729            let _ = sink.append(&line.to_string()).and_then(|()| sink.flush());
730        }
731        self.ended = Some(reason.to_string());
732    }
733
734    fn flush(&mut self) {
735        let _ = self.sink.as_mut().map(Sink::flush);
736    }
737
738    fn state(&self) -> &'static str {
739        if self.ended.is_none() { "running" } else { "ended" }
740    }
741
742    /// `status`: what was received, and what the buffer holds.
743    fn counts(&self) -> Map<String, Value> {
744        let mut out = fields! {
745            "state": self.state(),
746            "seen": self.seen,
747            "kept": self.kept,
748            "unparsed": self.unparsed,
749            "buffer": self.ring.usage(),
750        };
751        if let Some(sink) = &self.sink {
752            out.insert("rotations".into(), json!(sink.rotations));
753        }
754        if let Some(reason) = &self.ended {
755            out.insert("ended_reason".into(), json!(reason));
756        }
757        out
758    }
759
760    /// `read`: the page, and whether the capture is still running, so a
761    /// caller that polls sees it end.
762    fn read(&self, after: u64, q: &Query) -> Map<String, Value> {
763        let page = self.ring.read(after, q.grep.as_ref(), q.max);
764        let mut out = fields! {
765            "state": self.state(),
766            "count": page.entries.len(),
767            "entries": page.entries,
768            "cursor": page.cursor,
769            "more": page.more,
770            "dropped": page.dropped,
771        };
772        if let Some(reason) = &self.ended {
773            out.insert("ended_reason".into(), json!(reason));
774        }
775        out
776    }
777}
778
779/// Puts buffered lines in the file while the stream is quiet. Not part of
780/// the reading task: that one must never be interrupted between two reads.
781async fn flusher(live: Weak<Mutex<Live>>) {
782    let mut tick = tokio::time::interval(FLUSH_EVERY);
783    loop {
784        tick.tick().await;
785        let Some(live) = live.upgrade() else { return };
786        let mut live = live.lock().unwrap();
787        if live.ended.is_some() {
788            return;
789        }
790        live.flush();
791    }
792}
793
794/// The library reads a whole entry before parsing it, so an entry it cannot
795/// parse costs only that entry. A missing leading byte means the stream lost
796/// its place, and nothing after it can be trusted.
797fn skippable(e: &IdeviceError) -> bool {
798    matches!(e, IdeviceError::UnexpectedResponse(m) if !m.contains("leading byte"))
799}
800
801async fn pump(mut stream: OsTraceRelayReceiver, live: Arc<Mutex<Live>>) {
802    loop {
803        // Never under a timeout: an entry is several reads, and giving up
804        // between them would leave the stream mid-entry.
805        let reason = match stream.next().await {
806            Ok(log) => {
807                let (entry, executable) = entry_and_executable(log);
808                match live.lock().unwrap().take(entry, &executable) {
809                    Ok(()) => continue,
810                    Err(e) => format!("cannot write the file: {e}"),
811                }
812            }
813            Err(e) if skippable(&e) => {
814                live.lock().unwrap().unparsed += 1;
815                continue;
816            }
817            Err(e) => format!("the log stream ended: {e}"),
818        };
819        live.lock().unwrap().end(&reason);
820        return;
821    }
822}
823
824pub struct Capture {
825    spec: Spec,
826    /// `spec`'s apps resolved to where they live.
827    filter: Filter,
828    started_at: String,
829    started: std::time::Instant,
830    live: Arc<Mutex<Live>>,
831    task: tokio::task::JoinHandle<()>,
832    /// Only with a file.
833    flusher: Option<tokio::task::JoinHandle<()>>,
834    reset: Reset,
835}
836
837impl Capture {
838    /// End it now. The task is stopped first, so the `end` line is the last.
839    /// The connection is reset here, not when the stopped task drops the
840    /// stream: by then `Session::reset` may have closed the tunnel.
841    pub fn end(&self, reason: &str) {
842        self.reset.now();
843        self.task.abort();
844        if let Some(flusher) = &self.flusher {
845            flusher.abort();
846        }
847        self.live.lock().unwrap().end(reason);
848    }
849
850    /// After `end`: wait until the connection has been reset, so the relay
851    /// has let go of it before the next capture connects or the daemon exits.
852    pub async fn settle(&mut self) {
853        let _ = tokio::time::timeout(Duration::from_secs(1), self.reset.sent()).await;
854    }
855
856    /// A task that stopped without saying why (a panic in the parser).
857    fn check(&self) {
858        if self.task.is_finished() {
859            self.live.lock().unwrap().end("the log reader stopped unexpectedly");
860        }
861    }
862
863    pub fn is_running(&self) -> bool {
864        self.check();
865        self.live.lock().unwrap().ended.is_none()
866    }
867
868    /// While nothing has arrived for a while: why that can be. Not with
869    /// `--pid`, where a quiet process sends nothing either.
870    fn hint_if_silent(&self, live: &Live, out: &mut Map<String, Value>) {
871        if live.ended.is_none()
872            && self.spec.pid.is_none()
873            && live.seen == 0
874            && self.started.elapsed() > Duration::from_secs(5)
875        {
876            // Seen live: a relay connection that was dropped, not reset,
877            // held the next capture for about 30 s.
878            out.insert("hint".into(), json!(crate::i18n::t(
879                "아직 받은 로그가 없습니다. 연결이 끊긴 직후에는 폰이 약 30초 뒤에야 로그를 보냅니다.",
880                "No entries yet. Right after a dropped connection the phone starts sending about 30 s later.",
881            )));
882        }
883    }
884
885    pub fn read(&self, after: u64, q: &Query) -> Map<String, Value> {
886        self.check();
887        let live = self.live.lock().unwrap();
888        let mut out = live.read(after, q);
889        self.hint_if_silent(&live, &mut out);
890        out
891    }
892
893    pub fn report(&self) -> Map<String, Value> {
894        self.check();
895        let live = self.live.lock().unwrap();
896        let mut out = live.counts();
897        out.insert("started_at".into(), json!(self.started_at));
898        if !self.filter.processes.is_empty() {
899            out.insert("process".into(), json!(self.filter.processes));
900        }
901        if !self.filter.apps.is_empty() {
902            out.insert("app".into(), json!(self.filter.apps.iter().map(|a| &a.bundle_id).collect::<Vec<_>>()));
903        }
904        if let Some(pid) = self.spec.pid {
905            out.insert("pid".into(), json!(pid));
906        }
907        if let Some(level) = self.filter.min_level {
908            out.insert("level".into(), json!(level.name()));
909        }
910        if let Some(file) = &self.spec.file {
911            out.insert("path".into(), json!(file.path.display().to_string()));
912            if live.sink.as_ref().is_some_and(|s| s.rotations > 0) {
913                out.insert("previous_part".into(), json!(rotated(&file.path).display().to_string()));
914            }
915        }
916        self.hint_if_silent(&live, &mut out);
917        out
918    }
919}
920
921impl Session {
922    pub async fn cmd_syslog(&mut self, args: &Value) -> Res {
923        let udid = self.udid.clone();
924        match parse(args)? {
925            Request::Status => Ok(match &self.capture {
926                Some(c) => c.report(),
927                None => fields! { "state": "none" },
928            }),
929            Request::Read { after, query } => match &self.capture {
930                Some(c) => Ok(c.read(after, &query)),
931                None => Err(Fail::not_sent("no_capture", "no capture to read").hint(crate::i18n::t(
932                    "`iph syslog start`로 먼저 시작하세요.",
933                    "Start one with `iph syslog start`.",
934                ))),
935            },
936            Request::Start(spec) => {
937                if let Some(c) = &self.capture {
938                    // An ended capture is kept for `read` until `stop`.
939                    let (code, message) = if c.is_running() {
940                        ("capture_running", "a capture is already running")
941                    } else {
942                        ("capture_ended", "an ended capture has not been stopped")
943                    };
944                    return Err(Fail::not_sent(code, message).with("started_at", c.started_at.clone()).hint(
945                        crate::i18n::t(
946                            "`iph syslog stop`으로 끝낸 뒤 다시 시작하세요.",
947                            "End it with `iph syslog stop` first.",
948                        ),
949                    ));
950                }
951                // Before anything is created or opened: an unknown app is an error.
952                let apps = self.app_bundles(&spec.apps).await?;
953                let filter = Filter { processes: spec.processes.clone(), apps, min_level: spec.min_level };
954                // The file is opened only once the relay runs: a start that
955                // fails leaves an earlier capture's file as it was.
956                let (stream, reset) = self.os_trace(spec.pid).await?;
957                let sink = spec
958                    .file
959                    .as_ref()
960                    .map(|f| {
961                        Sink::create(&f.path, f.max_bytes).map_err(|e| Fail::invalid(format!("{}: {e}", f.path.display())))
962                    })
963                    .transpose()?;
964                let mut live = Live::new(Ring::new(spec.limits), sink, filter.clone());
965                let started_at = clock::now_utc();
966                let start = json!({
967                    "event": "start",
968                    "time": started_at,
969                    "udid": udid,
970                    "process": filter.processes,
971                    "app": filter.apps.iter().map(|a| &a.bundle_id).collect::<Vec<_>>(),
972                    "pid": spec.pid,
973                    "level": filter.min_level.map(Level::name),
974                    "max_mb": spec.file.as_ref().map(|f| f.max_bytes / (1024 * 1024)),
975                });
976                if let Err(e) = live.note(&start) {
977                    let path = spec.file.as_ref().map(|f| f.path.display().to_string()).unwrap_or_default();
978                    return Err(Fail::invalid(format!("{path}: {e}")));
979                }
980                let live = Arc::new(Mutex::new(live));
981                let task = tokio::task::spawn_local(pump(stream, live.clone()));
982                let flusher = spec.file.is_some().then(|| tokio::task::spawn_local(flusher(Arc::downgrade(&live))));
983                let started = std::time::Instant::now();
984                let capture = Capture { spec, filter, started_at, started, live, task, flusher, reset };
985                let report = capture.report();
986                self.capture = Some(capture);
987                Ok(report)
988            }
989            Request::Stop(query) => {
990                let Some(mut capture) = self.capture.take() else {
991                    return Err(Fail::not_sent("no_capture", "no capture to stop"));
992                };
993                capture.end("stopped");
994                capture.settle().await;
995                let mut out = capture.report();
996                if let Some(q) = query {
997                    let (entries, matched) = capture.live.lock().unwrap().ring.latest(q.grep.as_ref(), q.max);
998                    out.insert("matched".into(), json!(matched));
999                    out.insert("entries".into(), json!(entries));
1000                }
1001                Ok(out)
1002            }
1003        }
1004    }
1005
1006    /// Each app, named as `iph launch` takes it, with where it is installed.
1007    async fn app_bundles(&mut self, apps: &[String]) -> Res<Vec<AppBundle>> {
1008        if apps.is_empty() {
1009            return Ok(Vec::new());
1010        }
1011        // Not the cached list: a reinstall moves an app to a new container,
1012        // and its old path would match no entry at all.
1013        bundles_in(&self.list_apps(true).await?, apps)
1014    }
1015
1016    /// End the capture, keeping it for `status`, `read` and `stop`.
1017    pub fn end_capture(&mut self, reason: &str) {
1018        if let Some(c) = &self.capture {
1019            c.end(reason);
1020        }
1021    }
1022
1023    /// Before the daemon exits: end the capture and let its reset go out.
1024    pub async fn end_capture_before_exit(&mut self, reason: &str) {
1025        if let Some(c) = &mut self.capture {
1026            c.end(reason);
1027            c.settle().await;
1028        }
1029    }
1030
1031    pub fn capture_state(&self) -> Option<&'static str> {
1032        self.capture.as_ref().map(|c| if c.is_running() { "running" } else { "ended" })
1033    }
1034}
1035
1036#[cfg(test)]
1037mod tests {
1038    use super::*;
1039
1040    fn log(filename: &str, level: &str, label: Option<(&str, &str)>) -> OsTraceLog {
1041        serde_json::from_value(json!({
1042            "pid": 412,
1043            // What the library produces for 01:02:03.004005: micros in the nanos field.
1044            "timestamp": "2026-11-19T01:02:03.000004005",
1045            "level": level,
1046            "image_name": "/System/Library/Frameworks/UIKitCore.framework/UIKitCore",
1047            "filename": filename,
1048            "message": "tapped row",
1049            "label": label.map(|(s, c)| json!({ "subsystem": s, "category": c })),
1050            "procid": 412,
1051            "thread_id": 7,
1052            "image_offset": 0,
1053            "image_uuid": "00000000-0000-0000-0000-000000000000",
1054            "process_image_uuid": "00000000-0000-0000-0000-000000000000",
1055            "mach_timestamp": 0,
1056        }))
1057        .unwrap()
1058    }
1059
1060    fn entry(process: &str, level: Level, message: &str) -> Entry {
1061        Entry {
1062            time: "2026-11-19T01:02:03.000000Z".into(),
1063            pid: 1,
1064            process: process.into(),
1065            sender: process.into(),
1066            level,
1067            subsystem: None,
1068            category: None,
1069            message: message.into(),
1070        }
1071    }
1072
1073    fn note(message: &str) -> Entry {
1074        entry("Papago", Level::Info, message)
1075    }
1076
1077    /// Where an entry's process lives, as far as tests without apps care.
1078    fn feed(live: &mut Live, e: Entry) {
1079        let executable = format!("/usr/libexec/{}", e.process);
1080        live.take(e, &executable).unwrap();
1081    }
1082
1083    fn roomy() -> Limits {
1084        Limits { entries: 1000, bytes: 1 << 20 }
1085    }
1086
1087    fn temp_dir(name: &str) -> PathBuf {
1088        let dir = std::env::temp_dir().join(format!("iph-syslog-{name}-{}", std::process::id()));
1089        let _ = std::fs::remove_dir_all(&dir);
1090        std::fs::create_dir_all(&dir).unwrap();
1091        dir
1092    }
1093
1094    fn lines(path: &Path) -> Vec<Value> {
1095        std::fs::read_to_string(path)
1096            .unwrap()
1097            .lines()
1098            .map(|l| serde_json::from_str(l).expect("every line is JSON"))
1099            .collect()
1100    }
1101
1102    fn seqs(page: &Page) -> Vec<u64> {
1103        page.entries.iter().map(|e| e["seq"].as_u64().unwrap()).collect()
1104    }
1105
1106    fn messages(page: &Page) -> Vec<&str> {
1107        page.entries.iter().map(|e| e["message"].as_str().unwrap()).collect()
1108    }
1109
1110    /// A ring holding `n` entries "m1".."mN" (seq 1..=N).
1111    fn filled(limits: Limits, n: u64) -> Ring {
1112        let mut ring = Ring::new(limits);
1113        for i in 1..=n {
1114            assert_eq!(ring.push(note(&format!("m{i}"))), i);
1115        }
1116        ring
1117    }
1118
1119    #[test]
1120    fn an_entry_becomes_one_json_line_named_by_its_executable() {
1121        let e = Entry::from(log("/Applications/Preferences.app/Preferences", "Error", Some(("com.apple.settings", "ui"))));
1122        let v: Value = serde_json::from_str(&e.line(7)).unwrap();
1123        assert_eq!(
1124            v,
1125            json!({
1126                "seq": 7, "time": "2026-11-19T01:02:03.004005Z", "pid": 412, "process": "Preferences", "sender": "UIKitCore",
1127                "level": "error", "subsystem": "com.apple.settings", "category": "ui", "message": "tapped row",
1128            })
1129        );
1130        let plain = Entry::from(log("/usr/libexec/backboardd", "Notice", None));
1131        let v: Value = serde_json::from_str(&plain.line(1)).unwrap();
1132        assert_eq!(v["process"], "backboardd");
1133        assert_eq!(v["level"], "notice");
1134        assert!(v.get("subsystem").is_none());
1135    }
1136
1137    #[test]
1138    fn a_long_message_is_cut_in_a_reply_and_whole_in_the_file() {
1139        let long = note(&"y".repeat(900));
1140        let cut = long.value(3, MATCH_CHARS);
1141        assert_eq!(cut["message"].as_str().unwrap().chars().count(), MATCH_CHARS);
1142        assert_eq!(cut["message_cut"], true);
1143        let whole: Value = serde_json::from_str(&long.line(3)).unwrap();
1144        assert_eq!(whole["message"].as_str().unwrap().len(), 900);
1145        assert!(whole.get("message_cut").is_none());
1146        let short = note("short").value(3, MATCH_CHARS);
1147        assert!(short.get("message_cut").is_none());
1148        // Cut by characters, not bytes.
1149        let korean = note(&"가".repeat(600)).value(1, MATCH_CHARS);
1150        assert_eq!(korean["message"].as_str().unwrap().chars().count(), MATCH_CHARS);
1151    }
1152
1153    #[test]
1154    fn the_filter_keeps_named_processes_at_or_above_a_level() {
1155        let any = Filter::default();
1156        assert!(any.keeps(&entry("SpringBoard", Level::Debug, ""), "/usr/libexec/SpringBoard"));
1157        let f = Filter { processes: vec!["Preferences".into(), "Papago".into()], min_level: Some(Level::Notice), ..Filter::default() };
1158        let keeps = |e: Entry| f.keeps(&e, "/somewhere/else");
1159        assert!(keeps(entry("Preferences", Level::Notice, "")));
1160        assert!(keeps(entry("Papago", Level::Fault, "")));
1161        assert!(!keeps(entry("Preferences", Level::Info, "")));
1162        assert!(!keeps(entry("SpringBoard", Level::Error, "")));
1163        // Exact names only: a prefix is another process.
1164        assert!(!keeps(entry("PreferencesExtension", Level::Error, "")));
1165    }
1166
1167    fn papago() -> AppBundle {
1168        AppBundle::new("com.naver.papago", "file:///private/var/containers/Bundle/Application/AAAA-1111/Papago.app/").unwrap()
1169    }
1170
1171    #[test]
1172    fn an_app_is_matched_by_where_it_is_installed_whichever_way_the_prefix_is_spelled() {
1173        let app = papago();
1174        assert_eq!(app.path, "/var/containers/Bundle/Application/AAAA-1111/Papago.app");
1175        let f = Filter { apps: vec![app], ..Filter::default() };
1176        let from = |executable: &str| f.keeps(&note(""), executable);
1177        assert!(from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago"));
1178        assert!(from("/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago"), "without /private");
1179        assert!(from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/PlugIns/Share.appex/Share"), "an extension of the app");
1180        assert!(!from("/private/var/containers/Bundle/Application/BBBB-2222/Papago.app/Papago"), "the same name from another install");
1181        assert!(!from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.appex/Papago"), "a directory that only starts like the bundle");
1182        assert!(!from("/private/var/containers/Bundle/Application/AAAA-1111/Papago.app"), "the bundle directory itself is not an executable in it");
1183        assert!(!from("/usr/libexec/backboardd"));
1184        assert!(!from(""));
1185        // The same bundle given with a /var path, a URL, a trailing slash.
1186        for spelling in [
1187            "/var/containers/Bundle/Application/AAAA-1111/Papago.app",
1188            "/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/",
1189            "file:///var/containers/Bundle/Application/AAAA-1111/Papago.app/",
1190        ] {
1191            assert_eq!(AppBundle::new("com.naver.papago", spelling).unwrap(), papago(), "{spelling}");
1192        }
1193    }
1194
1195    #[test]
1196    fn an_app_filter_follows_the_app_across_a_restart_and_matches_non_ascii_paths() {
1197        let f = Filter { apps: vec![papago()], ..Filter::default() };
1198        let executable = "/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago";
1199        for pid in [412, 977] {
1200            let mut e = note("");
1201            e.pid = pid;
1202            assert!(f.keeps(&e, executable), "pid {pid}");
1203        }
1204        let notes = AppBundle::new("com.apple.mobilenotes", "file:///Applications/%EB%A9%94%EB%AA%A8.app/").unwrap();
1205        assert_eq!(notes.path, "/Applications/메모.app");
1206        let f = Filter { apps: vec![notes], ..Filter::default() };
1207        assert!(f.keeps(&note(""), "/Applications/메모.app/메모"));
1208    }
1209
1210    #[test]
1211    fn a_process_and_an_app_each_select_and_the_level_narrows_both() {
1212        let f = Filter { processes: vec!["SpringBoard".into()], apps: vec![papago()], min_level: Some(Level::Notice) };
1213        let papago_exe = "/private/var/containers/Bundle/Application/AAAA-1111/Papago.app/Papago";
1214        assert!(f.keeps(&entry("SpringBoard", Level::Notice, ""), "/usr/libexec/SpringBoard"), "a listed process");
1215        assert!(f.keeps(&entry("Papago", Level::Error, ""), papago_exe), "a listed app");
1216        assert!(!f.keeps(&entry("Papago", Level::Info, ""), papago_exe), "the level applies to the app");
1217        assert!(!f.keeps(&entry("SpringBoard", Level::Debug, ""), "/usr/libexec/SpringBoard"), "and to the process");
1218        assert!(!f.keeps(&entry("backboardd", Level::Fault, ""), "/usr/libexec/backboardd"), "neither listed");
1219        // A process named like the app's executable is its own selector.
1220        let only_process = Filter { processes: vec!["Papago".into()], ..Filter::default() };
1221        assert!(only_process.keeps(&entry("Papago", Level::Debug, ""), "/elsewhere/Papago"));
1222        // An app listed alone does not let other processes through.
1223        let only_app = Filter { apps: vec![papago()], ..Filter::default() };
1224        assert!(!only_app.keeps(&entry("Papago", Level::Debug, ""), "/elsewhere/Papago"));
1225    }
1226
1227    fn listed(bundle_id: &str, name: &str, path: &str) -> AppListEntry {
1228        serde_json::from_value(json!({
1229            "isRemovable": true, "name": name, "isFirstParty": false, "path": path, "bundleIdentifier": bundle_id,
1230            "isDeveloperApp": false, "isInternal": false, "isHidden": false, "isAppClip": false,
1231        }))
1232        .unwrap()
1233    }
1234
1235    #[test]
1236    fn an_app_is_found_by_bundle_id_in_the_phones_list_and_needs_a_usable_path() {
1237        let apps = vec![
1238            listed("com.apple.Preferences", "설정", "file:///Applications/Preferences.app/"),
1239            listed("com.naver.papago", "Papago", "file:///private/var/containers/Bundle/Application/AAAA-1111/Papago.app/"),
1240            listed("com.example.nopath", "No path", ""),
1241        ];
1242        assert_eq!(find_bundle(&apps, "com.naver.papago"), Some(papago()));
1243        assert_eq!(find_bundle(&apps, "com.apple.Preferences").unwrap().path, "/Applications/Preferences.app");
1244        assert_eq!(find_bundle(&apps, "com.example.missing"), None);
1245        assert_eq!(find_bundle(&apps, "com.example.nopath"), None, "an empty path would match nothing useful");
1246    }
1247
1248    #[test]
1249    fn apps_named_either_way_resolve_to_one_bundle_from_the_same_list() {
1250        let reinstalled = vec![
1251            listed("com.apple.Preferences", "설정", "file:///Applications/Preferences.app/"),
1252            listed("com.naver.papago", "Papago", "file:///private/var/containers/Bundle/Application/BBBB-2222/Papago.app/"),
1253        ];
1254        let bundles = bundles_in(&reinstalled, &["Papago".into(), "com.naver.papago".into()]).unwrap();
1255        assert_eq!(bundles.len(), 1);
1256        assert_eq!(bundles[0].path, "/var/containers/Bundle/Application/BBBB-2222/Papago.app");
1257        assert_eq!(bundles_in(&reinstalled, &["Unknown".into()]).unwrap_err().code, "app_not_found");
1258        assert_eq!(bundles_in(&reinstalled, &["com.example.missing".into()]).unwrap_err().code, "app_not_found");
1259    }
1260
1261    #[test]
1262    fn only_an_entry_the_library_could_not_parse_is_skipped() {
1263        let unparsed = IdeviceError::UnexpectedResponse("unknown log level byte value".into());
1264        let lost_place = IdeviceError::UnexpectedResponse("expected leading byte 0x02 at start of log packet".into());
1265        let gone = IdeviceError::Socket(std::io::Error::from(std::io::ErrorKind::ConnectionReset));
1266        assert!(skippable(&unparsed));
1267        assert!(!skippable(&lost_place));
1268        assert!(!skippable(&gone));
1269    }
1270
1271    #[test]
1272    fn device_levels_rank_by_severity_not_by_code() {
1273        let levels: Vec<Level> = [LogLevel::Fault, LogLevel::Debug, LogLevel::Error, LogLevel::Notice, LogLevel::Info]
1274            .into_iter()
1275            .map(Level::from)
1276            .collect();
1277        let mut sorted = levels.clone();
1278        sorted.sort();
1279        assert_eq!(sorted, [Level::Debug, Level::Info, Level::Notice, Level::Error, Level::Fault]);
1280    }
1281
1282    #[test]
1283    fn kept_entries_get_seqs_from_one_and_the_oldest_are_evicted_by_count() {
1284        let mut ring = filled(Limits { entries: 3, bytes: 1 << 20 }, 5);
1285        let usage = ring.usage();
1286        assert_eq!(
1287            (usage["entries"].as_u64(), usage["oldest_seq"].as_u64(), usage["newest_seq"].as_u64(), usage["evicted"].as_u64()),
1288            (Some(3), Some(3), Some(5), Some(2))
1289        );
1290        assert_eq!(usage["max_entries"], 3);
1291        assert_eq!(ring.push(note("m6")), 6, "a seq is never reused");
1292        assert_eq!(messages(&ring.read(0, None, 10)), ["m4", "m5", "m6"]);
1293        let fresh = Ring::new(roomy()).usage();
1294        assert!(fresh.get("oldest_seq").is_none() && fresh.get("newest_seq").is_none());
1295        assert_eq!(fresh["evicted"], 0);
1296    }
1297
1298    #[test]
1299    fn the_byte_budget_evicts_by_weight_and_the_count_stays_exact() {
1300        let w = note("m1").weight();
1301        let mut ring = Ring::new(Limits { entries: 100, bytes: 3 * w });
1302        for i in 1..=5 {
1303            ring.push(note(&format!("m{i}")));
1304        }
1305        let usage = ring.usage();
1306        assert_eq!(usage["entries"], 3);
1307        assert_eq!(usage["bytes"], 3 * w);
1308        assert_eq!(usage["oldest_seq"], 3);
1309        // A heavy entry pushes out as many light ones as it takes.
1310        ring.push(note(&"z".repeat(w)));
1311        let usage = ring.usage();
1312        assert!(usage["bytes"].as_u64().unwrap() <= 3 * w as u64);
1313        assert_eq!((usage["newest_seq"].as_u64(), usage["oldest_seq"].as_u64(), usage["entries"].as_u64()), (Some(6), Some(5), Some(2)));
1314    }
1315
1316    #[test]
1317    fn an_entry_larger_than_the_whole_budget_evicts_itself_and_the_ring_goes_on() {
1318        let mut ring = Ring::new(Limits { entries: 10, bytes: note("m1").weight() * 2 });
1319        ring.push(note("m1"));
1320        assert_eq!(ring.push(note(&"z".repeat(10_000))), 2);
1321        let usage = ring.usage();
1322        assert_eq!((usage["entries"].as_u64(), usage["bytes"].as_u64(), usage["evicted"].as_u64()), (Some(0), Some(0), Some(2)));
1323        let page = ring.read(0, None, 10);
1324        assert_eq!((page.entries.len(), page.cursor, page.dropped), (0, 2, 2));
1325        ring.push(note("m3"));
1326        assert_eq!(seqs(&ring.read(2, None, 10)), [3]);
1327    }
1328
1329    #[test]
1330    fn a_read_without_after_starts_at_the_oldest_kept_entry() {
1331        let ring = filled(Limits { entries: 4, bytes: 1 << 20 }, 6);
1332        let page = ring.read(0, None, 10);
1333        assert_eq!(seqs(&page), [3, 4, 5, 6]);
1334        assert_eq!((page.cursor, page.more, page.dropped), (6, false, 2), "the two evicted before this first read are reported");
1335        let untouched = filled(roomy(), 3).read(0, None, 10);
1336        assert_eq!((seqs(&untouched), untouched.cursor, untouched.dropped), (vec![1, 2, 3], 3, 0));
1337    }
1338
1339    #[test]
1340    fn a_read_after_a_seq_the_ring_still_holds_returns_only_what_is_newer() {
1341        let ring = filled(Limits { entries: 4, bytes: 1 << 20 }, 6);
1342        let page = ring.read(4, None, 10);
1343        assert_eq!((seqs(&page), page.cursor, page.dropped, page.more), (vec![5, 6], 6, 0, false));
1344        let page = ring.read(2, None, 10);
1345        assert_eq!((seqs(&page), page.dropped), (vec![3, 4, 5, 6], 0), "seq 2 was the last one the caller had; 3 is still here");
1346    }
1347
1348    #[test]
1349    fn a_read_after_a_seq_older_than_the_ring_counts_what_was_lost() {
1350        let ring = filled(Limits { entries: 4, bytes: 1 << 20 }, 10);
1351        // Held: 7..=10. The caller has 3, so 4, 5 and 6 are gone.
1352        let page = ring.read(3, None, 10);
1353        assert_eq!(seqs(&page), [7, 8, 9, 10]);
1354        assert_eq!((page.dropped, page.cursor), (3, 10));
1355    }
1356
1357    #[test]
1358    fn a_read_after_the_newest_seq_is_empty_and_a_cursor_beyond_it_is_pulled_back() {
1359        let ring = filled(roomy(), 3);
1360        let caught_up = ring.read(3, None, 10);
1361        assert_eq!((caught_up.entries.len(), caught_up.cursor, caught_up.more, caught_up.dropped), (0, 3, false, 0));
1362        // A cursor from an earlier capture, whose seqs ran higher.
1363        let stale = ring.read(5000, None, 10);
1364        assert_eq!((stale.entries.len(), stale.cursor, stale.dropped), (0, 3, 0));
1365        let empty = Ring::new(roomy()).read(0, None, 10);
1366        assert_eq!((empty.entries.len(), empty.cursor, empty.more, empty.dropped), (0, 0, false, 0));
1367        assert_eq!(Ring::new(roomy()).read(u64::MAX, None, 10).cursor, 0);
1368    }
1369
1370    #[test]
1371    fn a_grep_with_no_match_returns_nothing_and_still_moves_the_cursor() {
1372        let ring = filled(roomy(), 5);
1373        let re = Regex::new("nothing like this").unwrap();
1374        let page = ring.read(1, Some(&re), 10);
1375        assert_eq!((page.entries.len(), page.cursor, page.more, page.dropped), (0, 5, false, 0));
1376        // Reading on from that cursor looks at nothing already looked at.
1377        let mut ring = ring;
1378        ring.push(note("nothing like this, at last"));
1379        assert_eq!(seqs(&ring.read(page.cursor, Some(&re), 10)), [6]);
1380    }
1381
1382    #[test]
1383    fn max_cuts_a_page_and_the_cursor_continues_exactly_after_the_last_entry_returned() {
1384        let ring = filled(roomy(), 7);
1385        let first = ring.read(0, None, 3);
1386        assert_eq!((seqs(&first), first.cursor, first.more), (vec![1, 2, 3], 3, true));
1387        let second = ring.read(first.cursor, None, 3);
1388        assert_eq!((seqs(&second), second.cursor, second.more), (vec![4, 5, 6], 6, true));
1389        let last = ring.read(second.cursor, None, 3);
1390        assert_eq!((seqs(&last), last.cursor, last.more), (vec![7], 7, false));
1391        // A page that is exactly full and has nothing behind it is not "more".
1392        let exact = ring.read(4, None, 3);
1393        assert_eq!((seqs(&exact), exact.cursor, exact.more), (vec![5, 6, 7], 7, false));
1394    }
1395
1396    #[test]
1397    fn a_grep_cut_by_max_leaves_the_cursor_on_the_last_match_so_nothing_between_is_skipped() {
1398        let mut ring = Ring::new(roomy());
1399        for i in 1..=10 {
1400            ring.push(note(&if i % 3 == 0 { format!("hit {i}") } else { format!("miss {i}") }));
1401        }
1402        let re = Regex::new("^hit").unwrap();
1403        let first = ring.read(0, Some(&re), 2);
1404        assert_eq!((seqs(&first), first.cursor, first.more), (vec![3, 6], 6, true));
1405        let second = ring.read(first.cursor, Some(&re), 2);
1406        assert_eq!((seqs(&second), second.cursor, second.more), (vec![9], 10, false));
1407    }
1408
1409    #[test]
1410    fn paging_to_the_end_equals_one_read_of_the_same_filter() {
1411        let mut ring = Ring::new(roomy());
1412        for i in 1..=60 {
1413            ring.push(note(&if i % 4 == 0 { format!("hit {i}") } else { format!("miss {i}") }));
1414        }
1415        let re = Regex::new("^hit").unwrap();
1416        let whole = seqs(&ring.read(0, Some(&re), 1000));
1417        for max in [1, 2, 3, 7, 15] {
1418            let (mut cursor, mut got) = (0, Vec::new());
1419            loop {
1420                let page = ring.read(cursor, Some(&re), max);
1421                assert_eq!(page.dropped, 0);
1422                assert!(page.cursor >= cursor, "the cursor never goes back");
1423                got.extend(seqs(&page));
1424                cursor = page.cursor;
1425                if !page.more {
1426                    break;
1427                }
1428            }
1429            assert_eq!(got, whole, "max {max}");
1430            assert_eq!(cursor, 60);
1431        }
1432    }
1433
1434    #[test]
1435    fn eviction_between_pages_is_reported_and_the_cursor_still_leaves_no_gap_in_what_remains() {
1436        let mut ring = Ring::new(Limits { entries: 5, bytes: 1 << 20 });
1437        let push = |ring: &mut Ring, from: u64, to: u64| {
1438            for i in from..=to {
1439                ring.push(note(&if i % 2 == 0 { format!("hit {i}") } else { format!("miss {i}") }));
1440            }
1441        };
1442        let re = Regex::new("^hit").unwrap();
1443        push(&mut ring, 1, 8);
1444        // Held: 4..=8. Seqs 1, 2 and 3 went before anything was read.
1445        let a = ring.read(0, Some(&re), 2);
1446        assert_eq!((seqs(&a), a.cursor, a.more, a.dropped), (vec![4, 6], 6, true, 3));
1447        push(&mut ring, 9, 12);
1448        // Held: 8..=12. Seq 7 went while the caller was away.
1449        let b = ring.read(a.cursor, Some(&re), 2);
1450        assert_eq!((seqs(&b), b.cursor, b.more, b.dropped), (vec![8, 10], 10, true, 1));
1451        let c = ring.read(b.cursor, Some(&re), 2);
1452        assert_eq!((seqs(&c), c.cursor, c.more, c.dropped), (vec![12], 12, false, 0));
1453    }
1454
1455    #[test]
1456    fn paging_while_entries_are_evicted_returns_or_reports_every_seq_exactly_once() {
1457        for (capacity, page_size, burst) in [(6, 3, 4), (5, 1, 2), (10, 4, 9), (3, 2, 5), (50, 7, 1)] {
1458            let mut ring = Ring::new(Limits { entries: capacity, bytes: 1 << 20 });
1459            let (mut pushed, mut cursor, mut returned, mut dropped) = (0u64, 0u64, Vec::new(), 0u64);
1460            for round in 0..40 {
1461                for _ in 0..burst {
1462                    pushed += 1;
1463                    ring.push(note(&format!("m{pushed}")));
1464                }
1465                // Read at an uneven pace: some rounds skip, so evictions pile up.
1466                if round % 3 == 2 {
1467                    continue;
1468                }
1469                loop {
1470                    let page = ring.read(cursor, None, page_size);
1471                    dropped += page.dropped;
1472                    returned.extend(seqs(&page));
1473                    assert!(page.cursor >= cursor, "the cursor never goes back");
1474                    cursor = page.cursor;
1475                    if !page.more {
1476                        break;
1477                    }
1478                }
1479                assert_eq!(cursor, pushed, "a page that is not cut short has looked at everything");
1480            }
1481            assert!(returned.windows(2).all(|w| w[0] < w[1]), "oldest first, never twice ({capacity}, {page_size}, {burst})");
1482            assert_eq!(returned.len() as u64 + dropped, pushed, "every seq was returned or counted as dropped ({capacity}, {page_size}, {burst})");
1483        }
1484    }
1485
1486    #[test]
1487    fn latest_returns_the_most_recent_matches_oldest_first_with_the_total() {
1488        let mut ring = Ring::new(roomy());
1489        for i in 0..3 {
1490            ring.push(note(&format!("hit {i}")));
1491        }
1492        ring.push(note("miss"));
1493        ring.push(note(&format!("hit 3 {}", "y".repeat(900))));
1494        let re = Regex::new("^hit").unwrap();
1495        let (found, matched) = ring.latest(Some(&re), 2);
1496        assert_eq!(matched, 4);
1497        assert_eq!(found.iter().map(|e| e["seq"].as_u64().unwrap()).collect::<Vec<_>>(), [3, 5]);
1498        assert_eq!(found[0]["message"], "hit 2");
1499        assert_eq!(found[1]["message"].as_str().unwrap().chars().count(), MATCH_CHARS);
1500        assert_eq!(found[1]["message_cut"], true);
1501        let (all, matched) = ring.latest(None, 0);
1502        assert_eq!((all.len(), matched), (0, 5), "max 0 only counts");
1503        let (everything, _) = ring.latest(None, 1000);
1504        assert_eq!(everything.len(), 5);
1505    }
1506
1507    #[test]
1508    fn the_file_rolls_over_at_its_size_with_whole_lines_in_both_parts() {
1509        let dir = temp_dir("rotate");
1510        let path = dir.join("cap.jsonl");
1511        std::fs::write(rotated(&path), "left from before\n").unwrap();
1512        let line = |i: u32| json!({ "i": format!("{i:02}"), "message": "x".repeat(80) }).to_string();
1513        let part = 10 * (line(0).len() as u64 + 1);
1514        let mut sink = Sink::create(&path, part).unwrap();
1515        assert!(!rotated(&path).exists(), "an earlier part is removed at start");
1516        // Ten lines fit in a part, so 25 lines rotate twice and the second
1517        // rotation renames over the `.1` the first one made.
1518        for i in 0..25 {
1519            sink.write(&line(i)).unwrap();
1520        }
1521        sink.flush().unwrap();
1522        assert_eq!(sink.rotations, 2);
1523        let indexes = |p: &Path| lines(p).iter().map(|v| v["i"].as_str().unwrap().parse().unwrap()).collect::<Vec<u32>>();
1524        assert_eq!(indexes(&rotated(&path)), (10..20).collect::<Vec<_>>(), "only the last full part is kept");
1525        assert_eq!(indexes(&path), (20..25).collect::<Vec<_>>());
1526        for p in [&path, &rotated(&path)] {
1527            assert!(std::fs::metadata(p).unwrap().len() <= part);
1528            assert!(lines(p).iter().all(|v| v["message"].as_str().unwrap().len() == 80));
1529        }
1530        #[cfg(unix)]
1531        {
1532            use std::os::unix::fs::PermissionsExt;
1533            assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1534            assert_eq!(std::fs::metadata(rotated(&path)).unwrap().permissions().mode() & 0o777, 0o600);
1535        }
1536        let _ = std::fs::remove_dir_all(&dir);
1537    }
1538
1539    #[test]
1540    fn a_rotation_that_fails_still_ends_the_file_with_the_end_line() {
1541        let dir = temp_dir("rotate-fail");
1542        let path = dir.join("cap.jsonl");
1543        let mut sink = Sink::create(&path, 200).unwrap();
1544        // A directory where the previous part goes: the rotation cannot clear it.
1545        std::fs::create_dir_all(rotated(&path).join("x")).unwrap();
1546        sink.write(&json!({ "message": "a".repeat(100) }).to_string()).unwrap();
1547        assert!(sink.write(&json!({ "message": "b".repeat(100) }).to_string()).is_err());
1548        let mut live = Live::new(Ring::new(roomy()), Some(sink), Filter::default());
1549        live.end("cannot write the file");
1550        let got = lines(&path);
1551        assert_eq!(got.len(), 2, "the entry before the failed rotation, then the end line");
1552        assert_eq!(got[1]["event"], "end");
1553        let _ = std::fs::remove_dir_all(&dir);
1554    }
1555
1556    #[test]
1557    fn a_rotation_flushes_what_is_buffered_before_it_moves_the_file() {
1558        let dir = temp_dir("rotate-flush");
1559        let path = dir.join("cap.jsonl");
1560        let mut sink = Sink::create(&path, 200).unwrap();
1561        sink.write(&json!({ "message": "a".repeat(100) }).to_string()).unwrap();
1562        // Nothing was flushed yet; the rotation must not lose this line.
1563        sink.write(&json!({ "message": "b".repeat(100) }).to_string()).unwrap();
1564        assert_eq!(sink.rotations, 1);
1565        sink.flush().unwrap();
1566        assert_eq!(lines(&rotated(&path))[0]["message"], "a".repeat(100));
1567        assert_eq!(lines(&path)[0]["message"], "b".repeat(100));
1568        let _ = std::fs::remove_dir_all(&dir);
1569    }
1570
1571    #[test]
1572    fn the_flusher_puts_a_quiet_capture_in_the_file() {
1573        let dir = temp_dir("flusher");
1574        let path = dir.join("cap.jsonl");
1575        let sink = Sink::create(&path, 1 << 20).unwrap();
1576        let live = Arc::new(Mutex::new(Live::new(Ring::new(roomy()), Some(sink), Filter::default())));
1577        feed(&mut live.lock().unwrap(), note("quiet"));
1578        let runtime = tokio::runtime::Builder::new_current_thread().enable_time().start_paused(true).build().unwrap();
1579        runtime.block_on(async {
1580            let task = tokio::spawn(flusher(Arc::downgrade(&live)));
1581            tokio::time::sleep(FLUSH_EVERY * 4).await;
1582            assert_eq!(lines(&path)[0]["message"], "quiet", "written without an explicit flush");
1583            live.lock().unwrap().end("stopped");
1584            tokio::time::timeout(FLUSH_EVERY * 4, task).await.expect("the flusher stops once the capture ended").unwrap();
1585        });
1586        let _ = std::fs::remove_dir_all(&dir);
1587    }
1588
1589    #[test]
1590    fn a_capture_ends_with_one_end_line_and_keeps_nothing_after_it() {
1591        let dir = temp_dir("end");
1592        let path = dir.join("cap.jsonl");
1593        let filter = Filter { processes: vec!["Papago".into()], ..Filter::default() };
1594        let mut live = Live::new(Ring::new(roomy()), Some(Sink::create(&path, 1 << 20).unwrap()), filter);
1595        feed(&mut live, note("one"));
1596        feed(&mut live, entry("SpringBoard", Level::Info, "other"));
1597        live.end("the log stream ended: socket closed");
1598        live.end("stopped");
1599        feed(&mut live, note("late"));
1600        let got = lines(&path);
1601        assert_eq!(got.len(), 2, "the end line is flushed without anyone asking");
1602        assert_eq!((got[0]["seq"].as_u64(), got[0]["message"].as_str()), (Some(1), Some("one")));
1603        assert_eq!(got[1]["event"], "end");
1604        assert_eq!(got[1]["reason"], "the log stream ended: socket closed");
1605        assert_eq!((got[1]["seen"].as_u64(), got[1]["kept"].as_u64()), (Some(2), Some(1)));
1606        assert_eq!(live.ended.as_deref(), Some("the log stream ended: socket closed"));
1607        let _ = std::fs::remove_dir_all(&dir);
1608    }
1609
1610    #[test]
1611    fn without_a_file_nothing_is_written_and_the_ring_alone_serves_reads() {
1612        let dir = temp_dir("memory");
1613        let mut live = Live::new(Ring::new(roomy()), None, Filter::default());
1614        feed(&mut live, note("one"));
1615        live.note(&json!({ "event": "start" })).unwrap();
1616        live.end("stopped");
1617        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0);
1618        let out = live.read(0, &Query { grep: None, max: 10 });
1619        assert_eq!(out["count"], 1);
1620        assert!(live.counts().get("rotations").is_none());
1621        let _ = std::fs::remove_dir_all(&dir);
1622    }
1623
1624    #[test]
1625    fn the_file_and_the_ring_number_an_entry_alike() {
1626        let dir = temp_dir("seq");
1627        let path = dir.join("cap.jsonl");
1628        let mut live = Live::new(Ring::new(roomy()), Some(Sink::create(&path, 1 << 20).unwrap()), Filter::default());
1629        for m in ["a", "b", "c"] {
1630            feed(&mut live, note(m));
1631        }
1632        live.end("stopped");
1633        let in_file: Vec<(u64, String)> = lines(&path)
1634            .iter()
1635            .filter(|v| v.get("event").is_none())
1636            .map(|v| (v["seq"].as_u64().unwrap(), v["message"].as_str().unwrap().to_string()))
1637            .collect();
1638        let page = live.ring.read(0, None, 10);
1639        let in_ring: Vec<(u64, String)> =
1640            page.entries.iter().map(|e| (e["seq"].as_u64().unwrap(), e["message"].as_str().unwrap().to_string())).collect();
1641        assert_eq!(in_file, in_ring);
1642        let _ = std::fs::remove_dir_all(&dir);
1643    }
1644
1645    #[test]
1646    fn only_kept_entries_are_numbered_and_a_read_keeps_working_after_the_capture_ended() {
1647        let filter = Filter { processes: vec!["Papago".into()], ..Filter::default() };
1648        let mut live = Live::new(Ring::new(roomy()), None, filter);
1649        feed(&mut live, note("one"));
1650        feed(&mut live, entry("SpringBoard", Level::Info, "skipped"));
1651        feed(&mut live, note("two"));
1652        let q = Query { grep: None, max: 10 };
1653        let running = live.read(0, &q);
1654        assert_eq!((running["state"].as_str(), running["cursor"].as_u64(), running["dropped"].as_u64()), (Some("running"), Some(2), Some(0)));
1655        assert!(running.get("ended_reason").is_none());
1656        live.end("the connection to the phone was reset");
1657        let ended = live.read(1, &q);
1658        assert_eq!(ended["state"], "ended");
1659        assert_eq!(ended["ended_reason"], "the connection to the phone was reset");
1660        assert_eq!(ended["entries"][0]["message"], "two");
1661        assert_eq!(ended["entries"][0]["seq"], 2);
1662        let counts = live.counts();
1663        assert_eq!((counts["seen"].as_u64(), counts["kept"].as_u64()), (Some(3), Some(2)));
1664        assert_eq!(counts["buffer"]["entries"], 2);
1665    }
1666
1667    fn parsed(args: Value) -> Res<Request> {
1668        parse(&args)
1669    }
1670
1671    fn absolute(name: &str) -> PathBuf {
1672        std::env::temp_dir().join(name)
1673    }
1674
1675    #[test]
1676    fn a_start_keeps_to_memory_unless_a_file_is_asked_for() {
1677        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": "Preferences", "level": "default", "pid": null })) else {
1678            panic!("start")
1679        };
1680        assert_eq!(spec.processes, ["Preferences"]);
1681        assert_eq!(spec.min_level, Some(Level::Notice));
1682        assert_eq!((spec.apps.len(), spec.file), (0, None));
1683        assert_eq!(spec.limits, Limits { entries: 100_000, bytes: 64 * 1024 * 1024 });
1684        let out = absolute("x.jsonl");
1685        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "process": ["A", "B"], "pid": 7, "output": out, "max_mb": 2 })) else {
1686            panic!("start with a file")
1687        };
1688        assert_eq!((spec.processes.len(), spec.pid), (2, Some(7)));
1689        assert_eq!(spec.file, Some(FileSpec { path: out.clone(), max_bytes: 2 * 1024 * 1024 }));
1690        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "output": out })) else { panic!("default size") };
1691        assert_eq!(spec.file.unwrap().max_bytes, DEFAULT_MAX_MB * 1024 * 1024);
1692        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "output": absolute("y.jsonl"), "max_mb": MAX_FILE_MB })) else {
1693            panic!("the largest max_mb")
1694        };
1695        assert_eq!(spec.file.unwrap().max_bytes, MAX_FILE_MB * 1024 * 1024);
1696        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "buffer_entries": 500, "buffer_mb": 2 })) else {
1697            panic!("buffer limits")
1698        };
1699        assert_eq!(spec.limits, Limits { entries: 500, bytes: 2 * 1024 * 1024 });
1700    }
1701
1702    #[test]
1703    fn an_app_is_a_name_or_a_list_of_names_for_start_only() {
1704        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "app": "Papago", "process": "Preferences" })) else {
1705            panic!("one app")
1706        };
1707        assert_eq!((spec.apps, spec.processes), (strings(&["Papago"]), strings(&["Preferences"])));
1708        let Ok(Request::Start(spec)) = parsed(json!({ "action": "start", "app": ["com.naver.papago", "설정"] })) else {
1709            panic!("two apps")
1710        };
1711        assert_eq!(spec.apps, strings(&["com.naver.papago", "설정"]));
1712        for bad in [
1713            json!({ "action": "start", "app": "" }),
1714            json!({ "action": "start", "app": ["a", " "] }),
1715            json!({ "action": "start", "app": 7 }),
1716            json!({ "action": "start", "app": [1] }),
1717            json!({ "action": "read", "app": "Papago" }),
1718            json!({ "action": "stop", "app": "Papago" }),
1719        ] {
1720            assert_eq!(parsed(bad.clone()).expect_err(&bad.to_string()).code, "invalid_argument", "{bad}");
1721        }
1722    }
1723
1724    fn strings(v: &[&str]) -> Vec<String> {
1725        v.iter().map(|s| s.to_string()).collect()
1726    }
1727
1728    #[test]
1729    fn read_and_stop_take_a_cursor_a_pattern_and_a_count() {
1730        let Ok(Request::Read { after, query }) = parsed(json!({ "action": "read" })) else { panic!("bare read") };
1731        assert_eq!((after, query.max, query.grep.is_none()), (0, DEFAULT_MATCHES as usize, true));
1732        let Ok(Request::Read { after, query }) = parsed(json!({ "action": "read", "after": 120, "grep": "a+", "max": 5000 })) else {
1733            panic!("read")
1734        };
1735        assert_eq!((after, query.max, query.grep.unwrap().as_str()), (120, MAX_MATCHES as usize, "a+"));
1736        assert!(matches!(parsed(json!({ "action": "stop" })), Ok(Request::Stop(None))));
1737        let Ok(Request::Stop(Some(q))) = parsed(json!({ "action": "stop", "grep": "a+", "max": 5000 })) else {
1738            panic!("stop with grep")
1739        };
1740        assert_eq!(q.max, MAX_MATCHES as usize);
1741        let Ok(Request::Stop(Some(q))) = parsed(json!({ "action": "stop", "max": 0 })) else { panic!("stop to count") };
1742        assert_eq!(q.max, 0);
1743        assert!(matches!(parsed(json!({ "action": "status" })), Ok(Request::Status)));
1744    }
1745
1746    #[test]
1747    fn each_action_takes_only_its_own_arguments() {
1748        for bad in [
1749            json!({}),
1750            json!({ "action": "pause" }),
1751            json!({ "action": "stop", "process": "A" }),
1752            json!({ "action": "stop", "after": 3 }),
1753            json!({ "action": "read", "process": "A" }),
1754            json!({ "action": "read", "output": absolute("x.jsonl") }),
1755            json!({ "action": "start", "after": 3 }),
1756            json!({ "action": "start", "grep": "a" }),
1757            json!({ "action": "status", "grep": "a" }),
1758            json!({ "action": "read", "after": "three" }),
1759            json!({ "action": "read", "after": -1 }),
1760            json!({ "action": "read", "max": 0 }),
1761            json!({ "action": "read", "grep": "(" }),
1762            json!({ "action": "stop", "grep": "(" }),
1763            json!({ "action": "start", "output": "relative.jsonl" }),
1764            json!({ "action": "start", "level": "loud" }),
1765            json!({ "action": "start", "process": "/Applications/Preferences.app/Preferences" }),
1766        ] {
1767            let err = parsed(bad.clone()).expect_err(&bad.to_string());
1768            assert_eq!(err.code, "invalid_argument", "{bad}");
1769        }
1770    }
1771
1772    #[test]
1773    fn sizes_are_bounded_and_a_file_size_needs_a_file() {
1774        let file = absolute("z.jsonl");
1775        for bad in [
1776            json!({ "action": "start", "output": file, "max_mb": 0 }),
1777            json!({ "action": "start", "output": file, "max_mb": MAX_FILE_MB + 1 }),
1778            json!({ "action": "start", "output": file, "max_mb": u64::MAX }),
1779            json!({ "action": "start", "max_mb": 8 }),
1780            json!({ "action": "start", "buffer_entries": 0 }),
1781            json!({ "action": "start", "buffer_entries": MAX_BUFFER_ENTRIES + 1 }),
1782            json!({ "action": "start", "buffer_mb": 0 }),
1783            json!({ "action": "start", "buffer_mb": MAX_BUFFER_MB + 1 }),
1784            json!({ "action": "start", "buffer_mb": u64::MAX }),
1785        ] {
1786            let err = parsed(bad.clone()).expect_err(&bad.to_string());
1787            assert_eq!(err.code, "invalid_argument", "{bad}");
1788        }
1789        assert!(parsed(json!({ "action": "start", "buffer_entries": MAX_BUFFER_ENTRIES, "buffer_mb": MAX_BUFFER_MB })).is_ok());
1790    }
1791}