Skip to main content

pitchfork_cli/cli/
log_sink.rs

1use crate::Result;
2use crate::daemon_id::DaemonId;
3use crate::log_parse::ParsedLog;
4use crate::log_store::LogStore;
5use crate::log_store::sqlite::LOG_STORE;
6use tokio::io::AsyncReadExt;
7
8/// Number of parsed lines to accumulate before writing them as one batch.
9const BATCH_SIZE: usize = 100;
10
11/// Longest a parsed line waits in the batch before being written.
12const FLUSH_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);
13
14/// How many parsed lines may be queued for writing before reading slows down.
15///
16/// Reading and writing run separately so a slow write cannot stop the pipe being
17/// drained, but the queue is bounded: output that sustainably outpaces the store
18/// has to push back on the daemon eventually, which is preferable to growing
19/// without limit.
20const QUEUE_DEPTH: usize = 8192;
21
22/// Bytes read from the pipe at a time.
23const READ_CHUNK: usize = 8192;
24
25/// Longest run of bytes treated as a single line.
26///
27/// Output containing no newline must not accumulate indefinitely: a daemon
28/// emitting an endless stream, or binary data, would otherwise grow the buffer
29/// until the sink was killed for using too much memory — whereupon the
30/// supervisor would start another sink and repeat it.
31const MAX_LINE_BYTES: usize = 64 * 1024;
32
33/// Reads a daemon's output on stdin and writes it to the log store
34///
35/// Spawned by the supervisor as a sibling of the daemon, holding the read end
36/// of the daemon's output pipe. Keeping the reader in its own process is what
37/// makes logging survive a supervisor crash: the pipe still has a reader, so
38/// the daemon is neither killed by SIGPIPE nor blocked, and no output is lost.
39/// Exits when the pipe reaches end of file, which happens once the daemon and
40/// every descendant holding the write end have gone.
41#[derive(Debug, usage_rs::Args)]
42#[usage(verbatim_doc_comment)]
43pub struct LogSink {
44    /// Qualified id of the daemon whose output this is
45    #[usage(long)]
46    daemon_id: String,
47
48    /// Log format to parse lines with (`json`, `logfmt`, `auto`, or `text`)
49    #[usage(long, default = "text")]
50    log_format: String,
51
52    /// Regex whose first match means the daemon is ready
53    ///
54    /// Set for a daemon configured with `ready_output`. The supervisor cannot
55    /// match it itself — this process holds the output — so the match is
56    /// reported back over IPC.
57    #[usage(long)]
58    ready_pattern: Option<String>,
59
60    /// Token identifying the start attempt this sink belongs to
61    ///
62    /// Quoted back when reporting a match. The supervisor drops reports whose
63    /// token is no longer current, so a sink still draining a failed attempt
64    /// cannot mark that daemon's retry ready.
65    #[usage(long, default_value_t = 0, default = "0")]
66    relay_token: u64,
67
68    /// Report lines so the supervisor can fire the daemon's `on_output` hook
69    ///
70    /// Without `--output-filter` or `--output-regex` every line qualifies,
71    /// which is what a hook with no pattern asks for.
72    #[usage(long)]
73    report_output: bool,
74
75    /// Only report lines containing this substring
76    #[usage(long)]
77    output_filter: Option<String>,
78
79    /// Only report lines matching this regex
80    #[usage(long)]
81    output_regex: Option<String>,
82
83    /// Shortest gap between reported lines, in milliseconds
84    #[usage(long, default_value_t = 1000, default = "1000")]
85    output_debounce_ms: u64,
86}
87
88impl LogSink {
89    pub async fn run(&self) -> Result<()> {
90        let id = DaemonId::parse(&self.daemon_id)?;
91
92        // A pattern that does not compile is reported and then ignored, rather
93        // than failing the sink: refusing to start would leave the daemon's
94        // output unread, which is far worse than a readiness check that never
95        // fires. The supervisor validates patterns too, so this is a backstop.
96        let compile = |what: &str, pattern: &str| {
97            regex::Regex::new(pattern)
98                .map_err(|e| error!("log sink for {id} ignoring unparsable {what}: {e}"))
99                .ok()
100        };
101        let ready_pattern = self
102            .ready_pattern
103            .as_deref()
104            .and_then(|p| compile("ready pattern", p));
105        let hook = self.report_output.then(|| HookMatcher {
106            filter: self.output_filter.clone(),
107            regex: self
108                .output_regex
109                .as_deref()
110                .and_then(|p| compile("output pattern", p)),
111            debounce: std::time::Duration::from_millis(self.output_debounce_ms),
112            last_reported: None,
113        });
114
115        // Reading and writing are separate tasks. A write to SQLite can block —
116        // for as long as the store's busy timeout, if another writer holds the
117        // lock — and this process is the only reader of the daemon's pipe, so a
118        // write must never stop it being drained.
119        let (tx, rx) = tokio::sync::mpsc::channel::<SinkEvent>(QUEUE_DEPTH);
120        let writer = tokio::spawn(write_batches(id.clone(), self.relay_token, rx));
121
122        let read_result =
123            read_lines(tx, &self.log_format, ReadyMatcher::new(ready_pattern, hook)).await;
124
125        // The sender has been dropped by now, so the writer drains its queue and
126        // returns; wait for it so nothing queued is lost on exit.
127        let _ = writer.await;
128
129        read_result.map_err(|e| {
130            miette::miette!("log sink for {id} could not read the daemon's output: {e}")
131        })
132    }
133}
134
135/// Something for the writer task to do, in the order the reader saw it.
136///
137/// Reporting a readiness match travels the same queue as the lines rather than
138/// jumping ahead of them, so the line that triggered the match is always in the
139/// log store by the time the supervisor hears about it — `collect_startup_logs`
140/// and `pitchfork logs` would otherwise be able to miss it.
141enum SinkEvent {
142    Line(ParsedLog),
143    Report(Report),
144    /// A Program Status Protocol (OSC 7501) report; `None` clears the status.
145    Status(Option<crate::program_status::ProgramStatus>),
146}
147
148/// A line the supervisor needs to see, and why.
149#[derive(Debug, PartialEq, Eq)]
150struct Report {
151    text: String,
152    /// Whether it passed the `on_output` hook's filter and debounce. False for
153    /// a line reported only because it matched the readiness pattern — firing a
154    /// hook that filters for something else would be wrong.
155    fires_hook: bool,
156}
157
158/// How much of a capped line is carried forward for matching.
159///
160/// A line longer than [`MAX_LINE_BYTES`] is emitted in pieces, and a readiness
161/// pattern straddling a split would match none of them — the daemon would then
162/// be killed at its readiness timeout despite having announced itself. Keeping
163/// the tail of the previous piece closes that for any pattern shorter than this
164/// while still bounding what is held.
165const MATCH_CARRY_BYTES: usize = 4 * 1024;
166
167/// Watches a daemon's output for the things the supervisor would look for if it
168/// could still read the stream: the readiness pattern, and whatever fires the
169/// `on_output` hook.
170///
171/// What the supervisor does about a reported line — mark the daemon ready, run
172/// the hook — remains its own business.
173struct ReadyMatcher {
174    /// Readiness pattern, cleared once it has matched: readiness happens once.
175    pattern: Option<regex::Regex>,
176    /// The `on_output` hook's filter and rate limit, if the daemon has one.
177    hook: Option<HookMatcher>,
178    /// Tail of the previous piece of a line split at the length cap. Empty
179    /// whenever the last piece ended at a real newline.
180    carried: String,
181}
182
183/// The `on_output` hook's line filter and its rate limit.
184struct HookMatcher {
185    filter: Option<String>,
186    regex: Option<regex::Regex>,
187    debounce: std::time::Duration,
188    last_reported: Option<std::time::Instant>,
189}
190
191impl HookMatcher {
192    /// Whether this line should fire the hook, consuming the debounce window.
193    ///
194    /// The debounce is applied here rather than by the supervisor because this
195    /// process is the one that sees every line: enforcing it here means one IPC
196    /// message per window instead of one per line, which matters for a hook
197    /// with no filter, where every line qualifies.
198    fn matches(&mut self, clean: &str) -> bool {
199        let matched = match (&self.filter, &self.regex) {
200            // Mutually exclusive, and a hook setting both is rejected before it
201            // ever reaches this process.
202            (Some(substr), _) => clean.contains(substr.as_str()),
203            (None, Some(re)) => re.is_match(clean),
204            // A hook with neither fires on every line.
205            (None, None) => true,
206        };
207        if !matched {
208            return false;
209        }
210        let now = std::time::Instant::now();
211        if self
212            .last_reported
213            .is_some_and(|last| now.duration_since(last) < self.debounce)
214        {
215            return false;
216        }
217        self.last_reported = Some(now);
218        true
219    }
220}
221
222impl ReadyMatcher {
223    fn new(pattern: Option<regex::Regex>, hook: Option<HookMatcher>) -> Self {
224        Self {
225            pattern,
226            hook,
227            carried: String::new(),
228        }
229    }
230
231    /// Whether anything is still being watched for. Once nothing is, matching is
232    /// skipped: stripping ANSI from every line of a chatty daemon is not free.
233    fn is_watching(&self) -> bool {
234        self.pattern.is_some() || self.hook.is_some()
235    }
236
237    /// Test `text` — one whole line, or one piece of an over-long one — and
238    /// return what matched, which is what the supervisor is told about.
239    ///
240    /// `split_at_cap` says another piece of the same logical line follows.
241    fn consider(&mut self, text: &str, split_at_cap: bool) -> Option<Report> {
242        if !self.is_watching() {
243            self.carried.clear();
244            return None;
245        }
246        let clean = console::strip_ansi_codes(text);
247        let candidate = if self.carried.is_empty() {
248            clean.into_owned()
249        } else {
250            format!("{}{clean}", self.carried)
251        };
252
253        self.carried = if split_at_cap {
254            let start = candidate.len().saturating_sub(MATCH_CARRY_BYTES);
255            // Never split a character in half; walk forward to a boundary.
256            let start = (start..candidate.len())
257                .find(|i| candidate.is_char_boundary(*i))
258                .unwrap_or(candidate.len());
259            candidate[start..].to_string()
260        } else {
261            String::new()
262        };
263
264        // A line can qualify for either reason, or both. The supervisor
265        // re-checks the readiness pattern on what it is sent, but it cannot
266        // re-check the hook without redoing the debounce, so that answer is
267        // carried explicitly.
268        let mut ready_matched = false;
269        if self
270            .pattern
271            .as_ref()
272            .is_some_and(|re| re.is_match(&candidate))
273        {
274            self.pattern = None;
275            ready_matched = true;
276        }
277        let fires_hook = self
278            .hook
279            .as_mut()
280            .is_some_and(|hook| hook.matches(&candidate));
281
282        // Send the text the patterns actually matched against, not just this
283        // piece of it: the supervisor re-matches it, and hands it to the hook.
284        (ready_matched || fires_hook).then_some(Report {
285            text: candidate,
286            fires_hook,
287        })
288    }
289}
290
291/// Split the daemon's output into lines and queue them for writing.
292///
293/// Returns once the pipe reaches end of file. A read error is propagated so the
294/// process can exit non-zero: exiting cleanly would tell the supervisor the
295/// stream had finished and it would stop replacing this sink.
296async fn read_lines(
297    tx: tokio::sync::mpsc::Sender<SinkEvent>,
298    log_format: &str,
299    mut matcher: ReadyMatcher,
300) -> std::io::Result<()> {
301    let mut stdin = tokio::io::stdin();
302    let mut chunk = vec![0u8; READ_CHUNK];
303    let mut line: Vec<u8> = Vec::with_capacity(256);
304    // Whether the last line was emitted because it reached the cap rather than
305    // because it ended. A newline arriving straight afterwards terminates the
306    // line already written, so it must not produce an empty one.
307    let mut split_at_cap = false;
308    // Looks at the raw bytes, not the lines: a report ends with a terminator
309    // rather than a newline, and need not wait for one to be seen.
310    let mut scanner = crate::program_status::OscScanner::default();
311
312    loop {
313        let read = stdin.read(&mut chunk).await?;
314        if read == 0 {
315            break;
316        }
317        for update in scanner.feed(&chunk[..read]) {
318            let status = match update {
319                crate::program_status::StatusUpdate::Set(s) => Some(s),
320                crate::program_status::StatusUpdate::Clear => None,
321            };
322            tx.send(SinkEvent::Status(status))
323                .await
324                .map_err(|_| std::io::Error::other("log writer stopped"))?;
325        }
326        for &byte in &chunk[..read] {
327            if byte == b'\n' {
328                if split_at_cap && line.is_empty() {
329                    split_at_cap = false;
330                    continue;
331                }
332                split_at_cap = false;
333                queue(&tx, &mut line, log_format, &mut matcher).await?;
334            } else {
335                line.push(byte);
336                split_at_cap = false;
337                // Emit an over-long run as its own line rather than letting the
338                // buffer grow without bound.
339                if line.len() >= MAX_LINE_BYTES {
340                    queue_capped(&tx, &mut line, log_format, &mut matcher).await?;
341                    split_at_cap = true;
342                }
343            }
344        }
345    }
346
347    // Anything written without a trailing newline is still output.
348    if !line.is_empty() {
349        queue(&tx, &mut line, log_format, &mut matcher).await?;
350    }
351    Ok(())
352}
353
354/// Emit a line that has reached the length cap, keeping any trailing bytes that
355/// form an incomplete character.
356///
357/// Splitting purely by byte count would cut a multi-byte character in half, and
358/// converting each half on its own turns one valid character into two
359/// replacement characters.
360async fn queue_capped(
361    tx: &tokio::sync::mpsc::Sender<SinkEvent>,
362    line: &mut Vec<u8>,
363    log_format: &str,
364    matcher: &mut ReadyMatcher,
365) -> std::io::Result<()> {
366    let split = split_before_incomplete_char(line);
367    let tail = line.split_off(split);
368    let result = queue_piece(tx, line, log_format, matcher).await;
369    *line = tail;
370    result
371}
372
373/// Queue one piece of a line that hit the length cap, telling the matcher that
374/// the rest of the logical line is still to come.
375async fn queue_piece(
376    tx: &tokio::sync::mpsc::Sender<SinkEvent>,
377    line: &mut Vec<u8>,
378    log_format: &str,
379    matcher: &mut ReadyMatcher,
380) -> std::io::Result<()> {
381    let text = decode_line(line);
382    let text = text.trim_end_matches('\r');
383    let parsed = crate::log_parse::parse(text, log_format);
384    let report = matcher.consider(text, true);
385    line.clear();
386
387    tx.send(SinkEvent::Line(parsed))
388        .await
389        .map_err(|_| std::io::Error::other("log writer stopped"))?;
390    if let Some(report) = report {
391        tx.send(SinkEvent::Report(report))
392            .await
393            .map_err(|_| std::io::Error::other("log writer stopped"))?;
394    }
395    Ok(())
396}
397
398/// Length to cut `bytes` at so no character is left half-written, in whichever
399/// encoding [`decode_line`] will read the piece in.
400fn split_before_incomplete_char(bytes: &[u8]) -> usize {
401    #[cfg(windows)]
402    return split_before_incomplete_char_in(bytes, console_code_page());
403    #[cfg(not(windows))]
404    split_before_incomplete_utf8(bytes)
405}
406
407/// [`split_before_incomplete_char`] for a console using `code_page`.
408#[cfg(windows)]
409fn split_before_incomplete_char_in(bytes: &[u8], code_page: u32) -> usize {
410    let split = split_before_incomplete_utf8(bytes);
411    if uses_code_page(&bytes[..split]) {
412        // The piece is read in the code page, so the cut must fall between
413        // its characters. Within that, also hold back an unfinished UTF-8
414        // character: a line read in the code page can still carry UTF-8 — a
415        // stray byte decides how it is read, not what it contains — and a
416        // byte carried over to the next piece is decoded there, so holding
417        // one back loses nothing. A UTF-8 cut inside a double-byte character
418        // the code page reads as whole is not taken.
419        let dbcs_split = split_before_incomplete_dbcs(bytes, code_page);
420        if split < dbcs_split && is_dbcs_boundary(bytes, split, code_page) {
421            return split;
422        }
423        return dbcs_split;
424    }
425    split
426}
427
428/// Length to cut `bytes` at so no UTF-8 character is left half-written.
429///
430/// Decided by inspecting the final bytes rather than by asking `from_utf8` where
431/// the string stops being valid: that reports the *first* problem, so a single
432/// invalid byte earlier in the line would hide an unfinished character at the
433/// end, and the character would be split after all.
434fn split_before_incomplete_utf8(bytes: &[u8]) -> usize {
435    let len = bytes.len();
436    // A character is at most four bytes, so only the last few can be unfinished.
437    for i in (len.saturating_sub(4)..len).rev() {
438        let byte = bytes[i];
439        if byte & 0b1100_0000 == 0b1000_0000 {
440            continue; // a continuation byte; keep looking back for its lead
441        }
442        let expected = match byte {
443            0x00..=0x7f => 1,
444            b if b >> 5 == 0b110 => 2,
445            b if b >> 4 == 0b1110 => 3,
446            b if b >> 3 == 0b11110 => 4,
447            // Not a valid lead byte at all, so nothing is pending; the lossy
448            // conversion will render it.
449            _ => 1,
450        };
451        return if i + expected > len && i > 0 { i } else { len };
452    }
453    len
454}
455
456/// Text of one line of daemon output.
457///
458/// UTF-8 is taken as it is. Anything else is not assumed to be damaged UTF-8:
459/// on Windows, console programs — `cmd` among them — write in the console's
460/// code page, so a Japanese system hands over Shift_JIS, and reading that as
461/// UTF-8 would store nothing but replacement characters.
462pub(crate) fn decode_line(bytes: &[u8]) -> std::borrow::Cow<'_, str> {
463    if let Ok(text) = std::str::from_utf8(bytes) {
464        return std::borrow::Cow::Borrowed(text);
465    }
466    #[cfg(windows)]
467    if uses_code_page(bytes)
468        && let Some(text) = decode_in_code_page(bytes, console_code_page())
469    {
470        return std::borrow::Cow::Owned(text);
471    }
472    String::from_utf8_lossy(bytes)
473}
474
475/// Whether [`decode_line`] reads `bytes` in the console code page.
476///
477/// Only when they are not UTF-8, and not mostly UTF-8 either: a UTF-8 line with
478/// a stray invalid byte — or with another stream's output spliced into it —
479/// would have all of its text garbled by decoding it in the code page, where
480/// the lossy conversion loses just the stray bytes.
481///
482/// Mostly means more characters read as multi-byte UTF-8 than runs of bytes
483/// that cannot. Code page text does sometimes form a valid UTF-8 character by
484/// chance, but around it are far more bytes that do not.
485#[cfg(windows)]
486fn uses_code_page(bytes: &[u8]) -> bool {
487    if std::str::from_utf8(bytes).is_ok() {
488        return false;
489    }
490    let (mut multi_byte, mut invalid) = (0usize, 0usize);
491    for chunk in bytes.utf8_chunks() {
492        multi_byte += chunk.valid().chars().filter(|c| !c.is_ascii()).count();
493        invalid += usize::from(!chunk.invalid().is_empty());
494    }
495    multi_byte <= invalid
496}
497
498/// Code page the daemon's console programs write in.
499///
500/// This process is started the same way as the daemon, so it shares the
501/// daemon's console or gets one set up alike. Without a console at all, the
502/// OEM code page is what a new console would have used.
503#[cfg(windows)]
504fn console_code_page() -> u32 {
505    match unsafe { windows_sys::Win32::System::Console::GetConsoleOutputCP() } {
506        0 => unsafe { windows_sys::Win32::Globalization::GetOEMCP() },
507        code_page => code_page,
508    }
509}
510
511/// Decode `bytes` from `code_page`, or `None` when Windows cannot.
512///
513/// A UTF-8 code page gets `None` too: the bytes are already known not to be
514/// valid UTF-8, and the lossy conversion handles them just as well.
515#[cfg(windows)]
516fn decode_in_code_page(bytes: &[u8], code_page: u32) -> Option<String> {
517    use windows_sys::Win32::Globalization::{CP_UTF8, MultiByteToWideChar};
518
519    if code_page == CP_UTF8 {
520        return None;
521    }
522    let len = i32::try_from(bytes.len()).ok()?;
523    // The first call measures, the second converts.
524    let wide_len =
525        unsafe { MultiByteToWideChar(code_page, 0, bytes.as_ptr(), len, std::ptr::null_mut(), 0) };
526    if wide_len <= 0 {
527        return None;
528    }
529    let mut wide = vec![0u16; wide_len as usize];
530    let written = unsafe {
531        MultiByteToWideChar(
532            code_page,
533            0,
534            bytes.as_ptr(),
535            len,
536            wide.as_mut_ptr(),
537            wide_len,
538        )
539    };
540    if written <= 0 {
541        return None;
542    }
543    wide.truncate(written as usize);
544    Some(String::from_utf16_lossy(&wide))
545}
546
547/// Length to cut `bytes` at so no double-byte character of `code_page` is left
548/// half-written.
549///
550/// A trail byte can have the same value as a lead byte, so looking at the last
551/// byte alone cannot tell which it is; only walking from the start of the line
552/// can. Single-byte code pages have no lead bytes, so they never cut short.
553#[cfg(windows)]
554fn split_before_incomplete_dbcs(bytes: &[u8], code_page: u32) -> usize {
555    use windows_sys::Win32::Globalization::IsDBCSLeadByteEx;
556
557    let mut i = 0;
558    while i < bytes.len() {
559        let lead = unsafe { IsDBCSLeadByteEx(code_page, bytes[i]) } != 0;
560        i += if lead { 2 } else { 1 };
561    }
562    // Stepping past the end means the last byte opened a character.
563    if i > bytes.len() && bytes.len() > 1 {
564        bytes.len() - 1
565    } else {
566        bytes.len()
567    }
568}
569
570/// Whether `at` falls between two characters of `bytes` read in `code_page`,
571/// rather than inside a double-byte one. Walks from the start, for the same
572/// reason as [`split_before_incomplete_dbcs`].
573#[cfg(windows)]
574fn is_dbcs_boundary(bytes: &[u8], at: usize, code_page: u32) -> bool {
575    use windows_sys::Win32::Globalization::IsDBCSLeadByteEx;
576
577    let mut i = 0;
578    while i < at {
579        let lead = unsafe { IsDBCSLeadByteEx(code_page, bytes[i]) } != 0;
580        i += if lead { 2 } else { 1 };
581    }
582    i == at
583}
584
585/// Parse `line` and hand it to the writer, clearing it either way.
586///
587/// A closed queue means the writer task is gone, which is a failure rather than
588/// the end of the stream: reporting it as success would tell the supervisor this
589/// sink had reached end of file, and it would stop replacing it while the daemon
590/// was still writing.
591async fn queue(
592    tx: &tokio::sync::mpsc::Sender<SinkEvent>,
593    line: &mut Vec<u8>,
594    log_format: &str,
595    matcher: &mut ReadyMatcher,
596) -> std::io::Result<()> {
597    // Never fails: a daemon emitting a stray non-UTF-8 byte must not be able to
598    // stop its own logging.
599    let text = decode_line(line);
600    let text = text.trim_end_matches('\r');
601    let parsed = crate::log_parse::parse(text, log_format);
602    // Strip ANSI before matching so a pattern works whether or not the daemon
603    // colours its output, matching what in-process capture did.
604    let report = matcher.consider(text, false);
605    line.clear();
606
607    tx.send(SinkEvent::Line(parsed))
608        .await
609        .map_err(|_| std::io::Error::other("log writer stopped"))?;
610    if let Some(report) = report {
611        tx.send(SinkEvent::Report(report))
612            .await
613            .map_err(|_| std::io::Error::other("log writer stopped"))?;
614    }
615    Ok(())
616}
617
618/// Write queued lines in batches until the queue closes.
619async fn write_batches(
620    id: DaemonId,
621    relay_token: u64,
622    mut rx: tokio::sync::mpsc::Receiver<SinkEvent>,
623) {
624    let mut events: Vec<SinkEvent> = Vec::with_capacity(BATCH_SIZE);
625    let mut batch: Vec<ParsedLog> = Vec::with_capacity(BATCH_SIZE);
626    let mut flush_interval = tokio::time::interval(FLUSH_INTERVAL);
627    flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
628
629    loop {
630        let closed = tokio::select! {
631            received = rx.recv_many(&mut events, BATCH_SIZE) => received == 0,
632            _ = flush_interval.tick() => false,
633        };
634        // Only the newest status in a batch is worth telling the supervisor.
635        let mut status: Option<Option<crate::program_status::ProgramStatus>> = None;
636        for event in events.drain(..) {
637            match event {
638                SinkEvent::Status(s) => status = Some(s),
639                SinkEvent::Line(parsed) => batch.push(parsed),
640                SinkEvent::Report(report) => {
641                    // Everything up to and including the reported line goes to
642                    // the store before the supervisor is told, so whatever it
643                    // does next can already read it.
644                    flush(&id, &mut batch).await;
645                    report_line(&id, relay_token, report).await;
646                }
647            }
648        }
649        flush(&id, &mut batch).await;
650        if let Some(status) = status {
651            report_status(&id, relay_token, status).await;
652        }
653        if closed {
654            break;
655        }
656    }
657}
658
659/// Hand the supervisor a line it needs to act on.
660///
661/// Failure is logged and dropped. There is no supervisor to retry against if it
662/// has crashed — and if it has, nothing is waiting on this daemon's readiness or
663/// hooks — while the daemon's output keeps being captured either way.
664async fn report_line(id: &DaemonId, relay_token: u64, report: Report) {
665    // `autostart: false` — a sink must never bring a supervisor into being.
666    match crate::ipc::client::IpcClient::connect(false).await {
667        Ok(client) => {
668            if let Err(e) = client
669                .sink_output_line(id.clone(), relay_token, report.fires_hook, report.text)
670                .await
671            {
672                warn!("log sink for {id} could not report a line of output: {e}");
673            }
674        }
675        Err(e) => {
676            warn!("log sink for {id} could not reach the supervisor to report output: {e}");
677        }
678    }
679}
680
681/// Tell the supervisor what the daemon says it is doing. Like `report_line`,
682/// a failure is logged and dropped.
683async fn report_status(
684    id: &DaemonId,
685    relay_token: u64,
686    status: Option<crate::program_status::ProgramStatus>,
687) {
688    // Without a token the supervisor cannot tell which run this belongs to.
689    if relay_token == 0 {
690        return;
691    }
692    match crate::ipc::client::IpcClient::connect(false).await {
693        Ok(client) => {
694            if let Err(e) = client
695                .sink_program_status(id.clone(), relay_token, status)
696                .await
697            {
698                warn!("log sink for {id} could not report program status: {e}");
699            }
700        }
701        Err(e) => {
702            warn!("log sink for {id} could not reach the supervisor to report program status: {e}");
703        }
704    }
705}
706
707/// Write one batch, off the runtime so the SQLite call cannot stall other tasks.
708async fn flush(id: &DaemonId, batch: &mut Vec<ParsedLog>) {
709    if batch.is_empty() {
710        return;
711    }
712    let daemon_id = id.clone();
713    let entries = std::mem::take(batch);
714    let written = tokio::task::spawn_blocking(move || {
715        LOG_STORE.append_structured_batch(&daemon_id, &entries)
716    })
717    .await;
718    if let Ok(Err(e)) = written {
719        // Nothing useful to do but report it: the supervisor is not necessarily
720        // alive to be told, and dropping a batch is preferable to stalling the
721        // daemon behind a pipe nobody is draining.
722        error!("log sink failed to write batch for {id}: {e}");
723    }
724}
725
726#[cfg(test)]
727mod tests {
728    use super::{HookMatcher, MATCH_CARRY_BYTES, ReadyMatcher};
729
730    fn matcher(pattern: &str) -> ReadyMatcher {
731        ReadyMatcher::new(Some(regex::Regex::new(pattern).unwrap()), None)
732    }
733
734    fn hook_matcher(filter: Option<&str>, debounce_ms: u64) -> ReadyMatcher {
735        ReadyMatcher::new(
736            None,
737            Some(HookMatcher {
738                filter: filter.map(str::to_string),
739                regex: None,
740                debounce: std::time::Duration::from_millis(debounce_ms),
741                last_reported: None,
742            }),
743        )
744    }
745
746    #[test]
747    fn reports_the_first_match_and_then_stops_looking() {
748        let mut m = matcher("READY");
749        assert_eq!(m.consider("starting up", false), None);
750        assert_eq!(
751            m.consider("READY to serve", false)
752                .map(|r| r.text)
753                .as_deref(),
754            Some("READY to serve")
755        );
756        // Readiness happens once; later matches are somebody else's business.
757        assert_eq!(m.consider("READY again", false), None);
758    }
759
760    #[test]
761    fn matches_a_pattern_split_across_the_line_cap() {
762        // The daemon emitted one enormous line whose announcement straddles the
763        // point where the sink had to cut it.
764        let mut m = matcher("SERVER READY");
765        assert_eq!(m.consider("....SERVER ", true), None);
766        let report = m
767            .consider("READY....", false)
768            .expect("should match across the split");
769        assert!(
770            report.text.contains("SERVER READY"),
771            "reported {:?}",
772            report.text
773        );
774    }
775
776    #[test]
777    fn does_not_match_across_a_completed_line() {
778        // Two separate lines are not one line: a pattern spanning them must not
779        // match, or "SERVER" at the end of one line plus "READY" at the start of
780        // the next would look like an announcement.
781        let mut m = matcher("SERVER READY");
782        assert_eq!(m.consider("SERVER ", false), None);
783        assert_eq!(m.consider("READY", false), None);
784    }
785
786    #[test]
787    fn carries_a_bounded_amount_of_a_capped_line() {
788        let mut m = matcher("nothing-matches-this");
789        m.consider(&"x".repeat(MATCH_CARRY_BYTES * 3), true);
790        assert!(m.carried.len() <= MATCH_CARRY_BYTES);
791    }
792
793    #[test]
794    fn carrying_never_splits_a_character() {
795        // A carry boundary landing mid-character would panic on the slice, or
796        // corrupt the text a pattern is matched against.
797        let mut m = matcher("nothing-matches-this");
798        m.consider(&"é".repeat(MATCH_CARRY_BYTES), true);
799        assert!(m.carried.chars().all(|c| c == 'é'));
800    }
801
802    #[test]
803    fn hook_reports_matching_lines_within_the_debounce_window() {
804        let mut m = hook_matcher(Some("ALERT"), 0);
805        assert_eq!(m.consider("nothing here", false), None);
806        let report = m.consider("ALERT disk full", false).expect("should report");
807        assert_eq!(report.text, "ALERT disk full");
808        assert!(report.fires_hook);
809        // Unlike readiness, a hook keeps firing.
810        assert!(m.consider("ALERT again", false).is_some());
811    }
812
813    #[test]
814    fn hook_debounce_suppresses_a_second_line_in_the_same_window() {
815        let mut m = hook_matcher(None, 60_000);
816        assert!(m.consider("first", false).is_some());
817        // Every line matches a hook with no filter, so only the window stops it.
818        assert_eq!(m.consider("second", false), None);
819    }
820
821    #[test]
822    fn a_readiness_only_line_does_not_fire_the_hook() {
823        // A daemon can have both, filtered differently. The line that announces
824        // readiness is nothing to do with the hook, and reporting it must not
825        // be taken as permission to run the hook's command.
826        let mut m = ReadyMatcher::new(
827            Some(regex::Regex::new("READY").unwrap()),
828            Some(HookMatcher {
829                filter: Some("ALERT".to_string()),
830                regex: None,
831                debounce: std::time::Duration::from_millis(0),
832                last_reported: None,
833            }),
834        );
835        let report = m.consider("READY to serve", false).expect("should report");
836        assert!(!report.fires_hook, "readiness line must not fire the hook");
837        // ...and a line matching both says so.
838        let mut m = ReadyMatcher::new(
839            Some(regex::Regex::new("READY").unwrap()),
840            Some(HookMatcher {
841                filter: Some("READY".to_string()),
842                regex: None,
843                debounce: std::time::Duration::from_millis(0),
844                last_reported: None,
845            }),
846        );
847        assert!(
848            m.consider("READY", false)
849                .expect("should report")
850                .fires_hook
851        );
852    }
853
854    #[test]
855    fn strips_ansi_before_matching() {
856        let mut m = matcher("^READY$");
857        assert!(m.consider("\x1b[32mREADY\x1b[0m", false).is_some());
858    }
859
860    #[test]
861    fn decodes_utf8_unchanged() {
862        assert_eq!(
863            super::decode_line("起動しました".as_bytes()),
864            "起動しました"
865        );
866    }
867
868    /// What `cmd /C exec` writes on a Japanese system: "'exec' は、内部コマンド".
869    const CP932_CMD_ERROR: &[u8] =
870        b"'exec' \x82\xcd\x81\x41\x93\xe0\x95\x94\x83\x52\x83\x7d\x83\x93\x83\x68";
871
872    #[cfg(windows)]
873    #[test]
874    fn decodes_the_console_code_page() {
875        assert_eq!(
876            super::decode_in_code_page(CP932_CMD_ERROR, 932).as_deref(),
877            Some("'exec' は、内部コマンド")
878        );
879    }
880
881    #[cfg(windows)]
882    #[test]
883    fn leaves_a_utf8_code_page_to_the_lossy_conversion() {
884        assert_eq!(super::decode_in_code_page(b"\xff", 65001), None);
885    }
886
887    #[cfg(not(windows))]
888    #[test]
889    fn replaces_non_utf8_outside_windows() {
890        assert_eq!(super::decode_line(b"ok \xff"), "ok \u{fffd}");
891    }
892
893    /// The second line of the same message: "操作可能なプログラムまたはバッチ
894    /// ファイルとして認識されていません。" Only the Windows tests decode it.
895    #[cfg(windows)]
896    const CP932_CMD_ERROR_2: &[u8] = b"\x91\x80\x8d\xec\x89\xc2\x94\x5c\x82\xc8\x83\x76\x83\x8d\x83\x4f\x83\x89\x83\x80\x82\xdc\x82\xbd\x82\xcd\x83\x6f\x83\x62\x83\x60\x20\x83\x74\x83\x40\x83\x43\x83\x8b\x82\xc6\x82\xb5\x82\xc4\x94\x46\x8e\xaf\x82\xb3\x82\xea\x82\xc4\x82\xa2\x82\xdc\x82\xb9\x82\xf1\x81\x42";
897
898    #[test]
899    fn keeps_utf8_text_around_a_stray_byte() {
900        // Decoding this in a code page would garble every character; only the
901        // stray byte should be lost.
902        let mut line = "起動しました ".as_bytes().to_vec();
903        line.push(0xff);
904        assert_eq!(super::decode_line(&line), "起動しました \u{fffd}");
905    }
906
907    #[cfg(windows)]
908    #[test]
909    fn reads_code_page_text_in_the_code_page() {
910        // The first line happens to contain a valid UTF-8 character (0xCD 0x81).
911        assert!(super::uses_code_page(CP932_CMD_ERROR));
912        assert!(super::uses_code_page(CP932_CMD_ERROR_2));
913        assert_eq!(
914            super::decode_in_code_page(CP932_CMD_ERROR_2, 932).as_deref(),
915            Some("操作可能なプログラムまたはバッチ ファイルとして認識されていません。")
916        );
917    }
918
919    #[cfg(windows)]
920    #[test]
921    fn splits_before_an_unfinished_double_byte_character() {
922        // "aaaあ" in CP932, cut by the length cap between あ's two bytes.
923        let line = b"aaa\x82\xa0";
924        let split = super::split_before_incomplete_dbcs(&line[..4], 932);
925        assert_eq!(split, 3);
926        let first = super::decode_in_code_page(&line[..split], 932).unwrap();
927        let rest = super::decode_in_code_page(&line[split..], 932).unwrap();
928        assert_eq!(first + &rest, "aaaあ");
929    }
930
931    #[cfg(windows)]
932    #[test]
933    fn a_line_read_in_the_code_page_keeps_an_unfinished_utf8_character() {
934        // A stray byte sends the piece to the code page, but the line ends in
935        // the first byte of "é" (0xC3 0xA9), which is a whole character in
936        // CP932. Cutting there would still split the UTF-8 character.
937        let line = b"ab\xffcd\xc3";
938        assert!(super::uses_code_page(&line[..5]));
939        assert_eq!(super::split_before_incomplete_char_in(line, 932), 5);
940        // A double-byte character left unfinished is still held back too.
941        assert_eq!(
942            super::split_before_incomplete_char_in(b"ab\xffcd\x82", 932),
943            5
944        );
945    }
946
947    #[cfg(windows)]
948    #[test]
949    fn a_complete_double_byte_character_is_not_cut_for_utf8() {
950        // "づ" is 0x82 0xC3 in CP932. Its second byte looks like the start of
951        // a UTF-8 character, but cutting before it would split a character
952        // the code page reads as whole.
953        let line = b"ab\xffcd\x82\xc3";
954        assert_eq!(super::split_before_incomplete_char_in(line, 932), 7);
955        let line = b"aa\xe0\xc3";
956        assert_eq!(super::split_before_incomplete_char_in(line, 932), 4);
957    }
958
959    #[cfg(windows)]
960    #[test]
961    fn a_trail_byte_that_looks_like_a_lead_byte_is_not_cut() {
962        // 0x82 is a lead byte, but here the second one completes the first.
963        assert_eq!(super::split_before_incomplete_dbcs(b"a\x82\x82", 932), 3);
964        // ...and here the first pair is whole, leaving the last 0x82 unfinished.
965        assert_eq!(super::split_before_incomplete_dbcs(b"\x82\x9f\x82", 932), 2);
966        // A single-byte code page has nothing to finish.
967        assert_eq!(super::split_before_incomplete_dbcs(b"aa\x82", 1252), 3);
968    }
969
970    #[test]
971    fn never_fails_on_non_utf8() {
972        // Whatever the code page, the line is still stored.
973        assert!(super::decode_line(CP932_CMD_ERROR).starts_with("'exec' "));
974    }
975}