use std::{
collections::HashSet,
fmt,
sync::{Mutex, OnceLock},
};
use subc_protocol::session::HEALTH_SUMMARY_MAX_CHARS;
use tracing::warn;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum SummaryProblem {
Empty,
TooLong,
LineBreak,
ControlCharacter,
Json,
Backtick,
}
impl SummaryProblem {
fn label(self) -> &'static str {
match self {
Self::Empty => "empty",
Self::TooLong => "too_long",
Self::LineBreak => "line_break",
Self::ControlCharacter => "control_character",
Self::Json => "json",
Self::Backtick => "backtick",
}
}
}
impl fmt::Display for SummaryProblem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.label())
}
}
pub(crate) fn health_summary_problem(summary: &str) -> Option<SummaryProblem> {
if summary.trim().is_empty() {
return Some(SummaryProblem::Empty);
}
if summary.chars().count() > HEALTH_SUMMARY_MAX_CHARS {
return Some(SummaryProblem::TooLong);
}
if summary
.chars()
.any(|ch| matches!(ch, '\n' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}'))
{
return Some(SummaryProblem::LineBreak);
}
if summary.chars().any(char::is_control) {
return Some(SummaryProblem::ControlCharacter);
}
if summary.contains(['{', '[']) {
return Some(SummaryProblem::Json);
}
if summary.contains('`') && !ends_with_one_ck_command(summary) {
return Some(SummaryProblem::Backtick);
}
None
}
fn ends_with_one_ck_command(summary: &str) -> bool {
let body = summary.strip_suffix(['.', '!', '?']).unwrap_or(summary);
let Some(before_close) = body.strip_suffix('`') else {
return false;
};
let Some((before, command)) = before_close.rsplit_once('`') else {
return false;
};
!before.contains('`')
&& command
.strip_prefix("ck ")
.is_some_and(|rest| !rest.trim().is_empty())
}
pub(crate) fn relayed_health_summary(module_id: &str, summary: Option<String>) -> Option<String> {
let summary = summary?;
let Some(problem) = health_summary_problem(&summary) else {
return Some(summary);
};
if first_report(module_id, problem) {
warn!(
module_id,
problem = %problem,
chars = summary.chars().count(),
"dropped a module's health summary that breaks the summary rule; the rest of its health answer still counts"
);
}
None
}
fn first_report(module_id: &str, problem: SummaryProblem) -> bool {
static REPORTED: OnceLock<Mutex<HashSet<(String, SummaryProblem)>>> = OnceLock::new();
REPORTED
.get_or_init(Default::default)
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert((module_id.to_owned(), problem))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::router::test_log::{captured_logs, log_capture};
#[test]
fn health_summary_rule_accepts_plain_sentences_and_one_final_ck_command() {
for summary in [
"Running normally.",
"Two logins need signing in again",
"Backups are paused until the disk has space. Run `ck health engram`.",
"Sign in again with `ck auth login --provider anthropic`",
"Sign in again: `ck auth login`!",
"Grüße, 日本語 and emoji 🚀 count as one character each.",
] {
assert_eq!(health_summary_problem(summary), None, "{summary}");
}
let exactly_max = "a".repeat(HEALTH_SUMMARY_MAX_CHARS);
assert_eq!(health_summary_problem(&exactly_max), None);
let multibyte_max = "é".repeat(HEALTH_SUMMARY_MAX_CHARS);
assert!(multibyte_max.len() > HEALTH_SUMMARY_MAX_CHARS);
assert_eq!(health_summary_problem(&multibyte_max), None);
}
#[test]
fn health_summary_rule_names_each_problem() {
let too_long = "a".repeat(HEALTH_SUMMARY_MAX_CHARS + 1);
for (summary, problem) in [
("", SummaryProblem::Empty),
(" ", SummaryProblem::Empty),
(too_long.as_str(), SummaryProblem::TooLong),
("First line\nsecond line", SummaryProblem::LineBreak),
("Carriage\rreturn", SummaryProblem::LineBreak),
("Line\u{2028}separator", SummaryProblem::LineBreak),
("Tab\tinside", SummaryProblem::ControlCharacter),
("Escape \u{1b}[31m red", SummaryProblem::ControlCharacter),
("Bus {\"connected\":true}", SummaryProblem::Json),
("Lanes [1, 2] busy", SummaryProblem::Json),
("Check the `work` login", SummaryProblem::Backtick),
("Run `ck health` then rest.", SummaryProblem::Backtick),
(
"Run `ck auth login`. Then `ck health claustrum`.",
SummaryProblem::Backtick,
),
("Run `ck-auth login`.", SummaryProblem::Backtick),
("Run `ck `.", SummaryProblem::Backtick),
("Run `ck auth login", SummaryProblem::Backtick),
("Run ``ck health``.", SummaryProblem::Backtick),
] {
assert_eq!(
health_summary_problem(summary),
Some(problem),
"{summary:?}"
);
}
}
#[test]
fn relayed_health_summary_keeps_a_passing_summary_unchanged() {
let summary = "Backups are paused. Run `ck health engram`.".to_string();
assert_eq!(
relayed_health_summary("summary-test-pass", Some(summary.clone())),
Some(summary)
);
assert_eq!(relayed_health_summary("summary-test-pass", None), None);
}
#[test]
fn relayed_health_summary_drops_and_logs_each_problem_once_without_text() {
let (output, _guard) = log_capture(tracing::Level::WARN);
let module = "summary-test-drop";
let json = "Bus {\"secret\":1}".to_string();
let line_break = "First\nsecond".to_string();
assert_eq!(relayed_health_summary(module, Some(json.clone())), None);
assert_eq!(relayed_health_summary(module, Some(json.clone())), None);
assert_eq!(relayed_health_summary(module, Some(line_break)), None);
assert_eq!(
relayed_health_summary("summary-test-drop-other", Some(json)),
None
);
let logs = captured_logs(&output);
let warnings: Vec<_> = logs.lines().filter(|line| line.contains("WARN")).collect();
assert_eq!(warnings.len(), 3, "{logs}");
assert_eq!(
warnings
.iter()
.filter(|line| line.contains("module_id=\"summary-test-drop\"")
&& line.contains("problem=json"))
.count(),
1,
"{logs}"
);
assert!(logs.contains("problem=line_break"), "{logs}");
assert!(
logs.contains("module_id=\"summary-test-drop-other\""),
"{logs}"
);
assert!(
!logs.contains("secret"),
"the dropped text must not be logged: {logs}"
);
assert!(
!logs.contains("First"),
"the dropped text must not be logged: {logs}"
);
}
}