Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/notifications.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,30 @@ scheduler --RunReport--> NotifySink --(send)--> channel --> one consumer task
queue messages, the heartbeat and test messages), and every **email subject** is
`🐧 [pingwin] <first line of the message>`, cut at 150 characters. The email body
has no prefix. The prefix counts towards Telegram's 4096-character limit.
- **Bold in Telegram.** The target name and the status words are bold; reasons,
durations, times and notes are regular. In Telegram `db-1: ssh OFFLINE (refused)
since 14:02 UTC` looks like **db-1: ssh OFFLINE** (refused) since 14:02 UTC, sent
as `<b>db-1: ssh OFFLINE</b> (refused) since 14:02 UTC`. The first status shares
its bold run with the name (`<b>web-1: host RECOVERED</b> after 12m ...`), every
further status is bold on its own (`<b>web-1: ping OK</b>, <b>https OFFLINE</b>
(timeout) ...`). The headline of the "Telegram restored after X" / "rate limit
ended after X" line, the title line of the heartbeat and "pingwin test message"
are bold too.
- **How it works.** Telegram messages are sent with `parse_mode: "HTML"`. The
alert text is built once with invisible bold markers (private-use characters,
`message::render`, `notify::markup`) and stored like that in the queue. Only
when it is sent: Telegram gets everything **HTML-escaped** (`&`, `<`, `>`) with
the markers turned into `<b>...</b>`; email gets the markers removed. Names,
error texts and any other dynamic text can therefore never inject a tag, and
unbalanced bold is closed automatically. Telegram answers malformed HTML with a
400 "can't parse entities", so nothing unescaped may reach it.
- **Email stays plain text**: no `<b>`, no entities, also for delayed queue rows
and the failover test.
- **Queue rows from before this change** have no markers: they are sent escaped
and not bold.
- **Truncation** (4000 visible characters including the prefix, below Telegram's
4096 limit) happens on the marked text, before the HTML is built, so a cut never
splits a tag or an entity and an open bold part is closed.
- "since" is the time of the first failed probe of the outage. Times are shown in
the `display_tz` setting (default `UTC`); the date is added only when it differs
from the message's own date.
Expand Down
4 changes: 3 additions & 1 deletion src/dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use jiff::tz::TimeZone;
use crate::admin;
use crate::export::{self, RunsCsv, csv_text, csv_writer, format_local, format_utc, opt};
use crate::notify::config::load_display_tz;
use crate::notify::markup;
use crate::store::{Store, Target};

/// Rows read from the store per page.
Expand Down Expand Up @@ -353,7 +354,8 @@ async fn write_files(
n.email_attempts.to_string(),
n.delivered_ms.map(format_utc).unwrap_or_default(),
csv_text(n.last_error.as_deref().unwrap_or_default()),
csv_text(&n.message),
// Stored with invisible bold markers (notify::markup): drop them.
csv_text(&markup::plain(&n.message)),
])?;
summary.notifications += 1;
}
Expand Down
1 change: 1 addition & 0 deletions src/notify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
pub mod config;
pub mod dispatch;
pub mod heartbeat;
pub mod markup;
pub mod message;
pub mod smtp;
pub mod telegram;
Expand Down
21 changes: 15 additions & 6 deletions src/notify/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ use super::config::{
self, ConfigStoreError, SecretField, SmtpConfig, TelegramConfig, keys, load_display_tz,
load_telegram,
};
use super::markup;
use super::message::{self, TargetChange, format_time_full, human_duration};
use super::smtp::{self, SMTP_OVERALL_TIMEOUT, SmtpError};
use super::telegram::{ChatInfo, DEFAULT_BASE_URL, TelegramClient, TelegramError};
Expand Down Expand Up @@ -1022,8 +1023,11 @@ impl Notifier {
let (name, result) = match &channel {
TestChannel::Telegram(cfg) => (
"Telegram",
self.send_telegram(cfg, &format!("pingwin test message ({now})"))
.await,
self.send_telegram(
cfg,
&format!("{} ({now})", markup::bold("pingwin test message")),
)
.await,
),
TestChannel::Email(cfg) => {
let text = format!("pingwin test message ({now})");
Expand Down Expand Up @@ -1149,13 +1153,16 @@ impl Notifier {
Ok(())
}

/// Email is plain text: the bold markers of the shared message text are dropped
/// here, the one path every email takes.
async fn send_email(&self, cfg: &SmtpConfig, text: &str, body: &str) -> Result<(), String> {
let (text, body) = (markup::plain(text), markup::plain(body));
let first_line = text.lines().next().unwrap_or("");
let subject: String = format!("{PREFIX}[pingwin] {first_line}")
.chars()
.take(150)
.collect();
smtp::send_email_with_timeout(cfg, &subject, body, self.inner.smtp_timeout)
smtp::send_email_with_timeout(cfg, &subject, &body, self.inner.smtp_timeout)
.await
.map_err(|e: SmtpError| e.to_string())
}
Expand Down Expand Up @@ -1327,12 +1334,13 @@ fn new_row(text: &str, created_ms: i64, tg_enabled: bool, email_enabled: bool) -
}

/// `Telegram restored after 2h 13m (unreachable since 14:02 UTC)`, or after a 429
/// `Telegram rate limit ended after 2h 13m (rate limited since 14:02 UTC)`, if
/// `Telegram rate limit ended after 2h 13m (rate limited since 14:02 UTC)` (the
/// headline before the parenthesis is bold, see [`markup`]), if
/// `health` still records an outage. Must be computed **before** the send that ends
/// the outage, and sent inside that send's text (a successful send clears the outage).
pub(super) fn restored_header(health: &Health, now_ms: i64, tz: &TimeZone) -> Option<String> {
let since = format_time_full(health.unreachable_since_ms?, tz);
let line = restored_text(Channel::Telegram, health, now_ms)?;
let line = markup::bold(&restored_text(Channel::Telegram, health, now_ms)?);
Some(match health.outage {
Outage::RateLimited { .. } => format!("{line} (rate limited since {since})"),
Outage::Unreachable => format!("{line} (unreachable since {since})"),
Expand All @@ -1359,7 +1367,8 @@ fn email_body(text: &str, note: Option<&str>) -> String {
}
}

/// `[delayed (originally <time>)] <message>`: a queued row sent late.
/// `[delayed (originally <time>)] <message>`: a queued row sent late. The stored
/// message may carry bold markers (rows queued before bold existed have none).
fn delayed(row: &NotificationV1, tz: &TimeZone) -> String {
format!(
"[delayed (originally {})] {}",
Expand Down
197 changes: 196 additions & 1 deletion src/notify/dispatch/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ async fn fixture_with_token(tg_enabled: bool, email_enabled: bool, token: &str)
fx
}

/// Telegram HTML back to plain text (bold tags dropped, entities decoded), so the
/// older tests can keep comparing against the plain wording.
fn unhtml(html: &str) -> String {
html.replace("<b>", "")
.replace("</b>", "")
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&amp;", "&")
}

impl Fx {
async fn tg_up(&self) {
self.tg.reset().await;
Expand Down Expand Up @@ -137,10 +147,11 @@ impl Fx {
self.tg_raw_texts()
.await
.into_iter()
.map(|t| t.strip_prefix(PREFIX).unwrap_or(&t).to_owned())
.map(|t| unhtml(t.strip_prefix(PREFIX).unwrap_or(&t)))
.collect()
}

/// `sendMessage` bodies as the bot API received them (HTML, prefix included).
async fn tg_raw_texts(&self) -> Vec<String> {
self.tg
.received_requests()
Expand Down Expand Up @@ -1481,3 +1492,187 @@ async fn expiry_needs_age_and_an_attempt_and_ignores_future_rows() {
assert_eq!(status(old_untried).await, ChannelStatus::Pending);
assert_eq!(status(future).await, ChannelStatus::Pending);
}

// ------------------------------------------------------- Telegram bold (HTML mode)

#[tokio::test]
async fn telegram_alert_is_html_with_bold_name_and_status_and_escaped_names() {
let fx = fixture(true, false).await;
fx.notifier.handle(fx.change("a<b&c")).await.unwrap();

assert_eq!(
fx.tg_raw_texts().await,
vec![
"🐧 <b>a&lt;b&amp;c: ping OK</b>, <b>https OFFLINE</b> (handshake_reset) since 14:00 UTC"
]
);
// Telegram is told to parse HTML.
let requests = fx.tg.received_requests().await.unwrap();
let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
assert_eq!(body["parse_mode"], "HTML");
}

#[tokio::test]
async fn email_stays_plain_text() {
let fx = fixture(false, true).await;
fx.notifier.handle(fx.change("a<b&c")).await.unwrap();

let mails = fx.smtp.messages();
assert_eq!(mails.len(), 1);
let mail = &mails[0];
assert!(
mail.contains("a<b&c: ping OK, https OFFLINE (handshake_reset)"),
"{mail}"
);
for forbidden in ["<b>", "</b>", "&lt;", "&amp;", "\u{E000}", "\u{E001}"] {
assert!(!mail.contains(forbidden), "{forbidden:?} in {mail}");
}
}

#[tokio::test]
async fn stored_message_keeps_bold_markers_and_the_queue_view_text_is_plain() {
let fx = fixture(true, false).await;
fx.notifier.handle(fx.change("web-1")).await.unwrap();
let message = fx.rows().await[0].1.message.clone();
assert!(message.contains(markup::BOLD_ON), "{message:?}");
assert_eq!(
markup::plain(&message),
"web-1: ping OK, https OFFLINE (handshake_reset) since 14:00 UTC"
);
}

#[tokio::test]
async fn delayed_flush_escapes_old_plain_rows_and_bolds_new_ones() {
let fx = fixture(true, false).await;
// Stored before bold existed: plain text, with characters that need escaping.
fx.store
.insert_notification(pending_row("old<1>: ping OK & https OFFLINE", T0 - 60_000))
.await
.unwrap();
// Stored after: bold markers.
let marked = format!(
"{} (timeout) since 14:00 UTC",
markup::bold("db<1>: HOST OFFLINE")
);
fx.store
.insert_notification(pending_row(&marked, T0 - 30_000))
.await
.unwrap();
fx.notifier.tick().await.unwrap();

assert_eq!(
fx.tg_raw_texts().await,
vec![
"🐧 [delayed (originally 2026-11-30 13:59 UTC)] old&lt;1&gt;: ping OK &amp; https OFFLINE",
"🐧 [delayed (originally 2026-11-30 13:59 UTC)] <b>db&lt;1&gt;: HOST OFFLINE</b> (timeout) since 14:00 UTC",
]
);
}

#[tokio::test]
async fn delayed_row_goes_out_by_email_as_plain_text() {
let fx = fixture(false, true).await;
let marked = format!("{} (timeout)", markup::bold("db<1>: HOST OFFLINE"));
fx.store
.insert_notification(NotificationV1 {
email_status: ChannelStatus::Pending.code(),
telegram_status: ChannelStatus::NotUsed.code(),
..pending_row(&marked, T0 - 30_000)
})
.await
.unwrap();
fx.notifier.tick().await.unwrap();
let mails = fx.smtp.messages();
assert_eq!(mails.len(), 1);
assert!(
mails[0].contains("db<1>: HOST OFFLINE (timeout)"),
"{}",
mails[0]
);
assert!(!mails[0].contains("<b>") && !mails[0].contains('\u{E000}'));
}

#[test]
fn restored_header_has_a_bold_headline_and_regular_details() {
let health = Health {
unreachable_since_ms: Some(T0 - 120_000),
..Health::default()
};
let header = restored_header(&health, T0, &TimeZone::UTC).unwrap();
assert_eq!(
markup::html(&header),
"<b>Telegram restored after 2m</b> (unreachable since 2026-11-30 13:58 UTC)"
);
let limited = Health {
outage: Outage::RateLimited { retry_after_s: 5 },
..health
};
let header = restored_header(&limited, T0, &TimeZone::UTC).unwrap();
assert_eq!(
markup::html(&header),
"<b>Telegram rate limit ended after 2m</b> (rate limited since 2026-11-30 13:58 UTC)"
);
}

#[tokio::test]
async fn test_message_has_a_bold_title() {
let fx = fixture(false, false).await;
let outcome = fx
.notifier
.send_test(TestChannel::Telegram(tg_config(false)))
.await;
assert!(outcome.ok, "{outcome:?}");
let raw = fx.tg_raw_texts().await;
assert!(
raw[0].starts_with("🐧 <b>pingwin test message</b> (2026-11-30 14:00 UTC)"),
"{raw:?}"
);
}

#[tokio::test]
async fn very_long_messages_are_cut_before_the_html_is_built() {
let fx = fixture(true, false).await;
// A bold part that straddles the cut, full of characters that become entities.
let long = format!("{}{}", markup::bold(&"<&>".repeat(3000)), "tail");
fx.store
.insert_notification(pending_row(&long, T0 - 1000))
.await
.unwrap();
fx.notifier.tick().await.unwrap();
let raw = fx.tg_raw_texts().await;
assert_eq!(raw.len(), 1);
let html = &raw[0];
assert_eq!(html.matches("<b>").count(), 1, "bold opened once");
assert_eq!(html.matches("</b>").count(), 1, "and closed");
assert!(html.ends_with("</b>"));
// Every `&` starts a whole entity, so nothing was cut in the middle of one.
let body = html.trim_end_matches("</b>");
assert!(body.ends_with("&lt;") || body.ends_with("&amp;") || body.ends_with("&gt;"));
// The visible text, with entities decoded, is exactly the limit (prefix included).
assert_eq!(unhtml(html).chars().count(), 4000);
}

#[tokio::test]
async fn heartbeat_title_is_bold() {
use crate::notify::config::keys;
let fx = fixture(true, false).await;
let source = FakeSource {
calls: Mutex::new(0),
};
fx.store
.set_setting(keys::HEARTBEAT_ENABLED, "true")
.await
.unwrap();
fx.store
.set_setting(keys::HEARTBEAT_TIME, "14:00")
.await
.unwrap();
fx.notifier.heartbeat_tick(&source).await.unwrap();
let raw = fx.tg_raw_texts().await;
assert!(
raw[0].starts_with(
"🐧 <b>pingwin daily summary, 2026-11-30 14:00 UTC</b>\n<b>ie-node: ping OK</b>\n"
),
"{raw:?}"
);
}
Loading