fix(alerts): ship the rich prebuilt templates in release images (#16974)

This commit is contained in:
Loakesh Indiran authored and GitHub committed 2026-11-19 14:03:41 +00:00
1 parent 11dcc1e73a
commit f288e0bcac
9 files changed
+425 -472

No files matched your search

+3 -3
View File
@@ -1,5 +1,5 @@
{
"revision": 3,
"revision": 4,
"destinations": [
{
"id": "slack",
@@ -21,7 +21,7 @@
},
"template": {
"name": "prebuilt_slack",
"body": "{\n \"text\": \"[{alert_status}] {alert_name}\",\n \"blocks\": [\n {\n \"type\": \"header\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"[{alert_status}] {alert_name}\"\n }\n },\n {\n \"type\": \"section\",\n \"fields\": [\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Stream:*\\n{stream_name}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Type:*\\n{stream_type}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Count:*\\n{alert_count}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Threshold:*\\n{alert_operator} {alert_threshold}\"\n }\n ]\n },\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"*Status:* {alert_status}\\n*Time:* {alert_trigger_time_str}\"\n }\n },\n {\n \"type\": \"actions\",\n \"elements\": [\n {\n \"type\": \"button\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"View in OpenObserve\"\n },\n \"url\": \"{alert_url}\"\n }\n ]\n }\n ]\n}"
"body": "{\n \"text\": \"[{alert_status}] {alert_name}\",\n \"blocks\": [\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"*[{alert_status}] {alert_name}*\"\n }\n },\n {\n \"type\": \"section\",\n \"fields\": [\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Stream:*\\n{stream_name}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Type:*\\n{stream_type}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Count:*\\n{alert_count}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Threshold:*\\n{alert_operator} {alert_threshold}\"\n }\n ]\n },\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"*Status:* {alert_status}\\n*Time:* {alert_trigger_time_str}\"\n }\n },\n {\n \"type\": \"actions\",\n \"elements\": [\n {\n \"type\": \"button\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"View in OpenObserve\"\n },\n \"url\": \"{alert_url}\"\n }\n ]\n }\n ]\n}"
},
"credential_fields": [
{
@@ -203,7 +203,7 @@
},
"template": {
"name": "prebuilt_opsgenie",
"body": "{\n \"message\": \"OpenObserve [{alert_status}]: {alert_name}\",\n \"alias\": \"{alert_name}_{stream_name}\",\n \"description\": \"Alert triggered from OpenObserve\",\n \"priority\": \"{credential_priority}\",\n \"details\": {\n \"alert_name\": \"{alert_name}\",\n \"stream_name\": \"{stream_name}\",\n \"stream_type\": \"{stream_type}\",\n \"alert_count\": \"{alert_count}\",\n \"alert_threshold\": \"{alert_operator} {alert_threshold}\",\n \"alert_time\": \"{alert_trigger_time_str}\",\n \"alert_url\": \"{alert_url}\"\n },\n \"source\": \"OpenObserve\",\n \"tags\": [\"openobserve\", \"{stream_type}\"]\n}"
"body": "{\n \"message\": \"OpenObserve [{alert_status}]: {alert_name}\",\n \"description\": \"Alert triggered from OpenObserve\",\n \"priority\": \"{credential_priority}\",\n \"details\": {\n \"alert_name\": \"{alert_name}\",\n \"stream_name\": \"{stream_name}\",\n \"stream_type\": \"{stream_type}\",\n \"alert_count\": \"{alert_count}\",\n \"alert_threshold\": \"{alert_operator} {alert_threshold}\",\n \"alert_time\": \"{alert_trigger_time_str}\",\n \"alert_url\": \"{alert_url}\"\n },\n \"source\": \"OpenObserve\",\n \"tags\": [\"openobserve\", \"{stream_type}\"]\n}"
},
"credential_fields": [
{
+275 -458
View File
@@ -135,9 +135,11 @@ pub fn is_prebuilt_template_name(name: &str) -> bool {
/// Get a specific prebuilt template by type (e.g., "slack", "teams", "email")
pub fn get_prebuilt_template(prebuilt_type: &str) -> Option<Template> {
let config = load_prebuilt_config();
find_template(&load_prebuilt_config(), prebuilt_type)
}
for dest_config in config.destinations {
fn find_template(config: &PrebuiltDestinationsConfig, prebuilt_type: &str) -> Option<Template> {
for dest_config in &config.destinations {
// Match by ID or destination_type in endpoint
let matches = dest_config.id == prebuilt_type
|| dest_config
@@ -188,224 +190,128 @@ fn convert_template_config(config: &TemplateConfig, dest_type: &str) -> Template
}
}
/// Load built-in config (fallback when JSON file is not available)
fn load_builtin_config() -> PrebuiltDestinationsConfig {
// Return built-in configuration with templates embedded
// This ensures the system works even if the JSON file is missing
PrebuiltDestinationsConfig {
revision: 3,
destinations: vec![
PrebuiltDestinationConfig {
id: "slack".to_string(),
name: "Slack".to_string(),
description: "Send notifications to Slack channels".to_string(),
destination_type: "http".to_string(),
icon: "slack-icon".to_string(),
popular: true,
category: "messaging".to_string(),
endpoint: Some(EndpointConfig {
url: "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "slack".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_slack".to_string(),
body: r#"{"text": "[{alert_status}] {alert_name}"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "email".to_string(),
name: "Email".to_string(),
description: "Send email notifications".to_string(),
destination_type: "email".to_string(),
icon: "email-icon".to_string(),
popular: true,
category: "email".to_string(),
endpoint: None,
template: TemplateConfig {
name: "prebuilt_email".to_string(),
body: "<h2>[{alert_status}] {alert_name}</h2>".to_string(),
title: Some("OpenObserve Alert: {alert_name}".to_string()),
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "msteams".to_string(),
name: "Microsoft Teams".to_string(),
description: "Send notifications to Teams".to_string(),
destination_type: "http".to_string(),
icon: "teams-icon".to_string(),
popular: true,
category: "messaging".to_string(),
endpoint: Some(EndpointConfig {
url: "https://webhook.office.com/webhookb2/YOUR-TEAMS-WEBHOOK".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "teams".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_msteams".to_string(),
body: r#"{"@type": "MessageCard", "text": "[{alert_status}] {alert_name}"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "pagerduty".to_string(),
name: "PagerDuty".to_string(),
description: "Create incidents in PagerDuty".to_string(),
destination_type: "http".to_string(),
icon: "pagerduty-icon".to_string(),
popular: true,
category: "incident".to_string(),
endpoint: Some(EndpointConfig {
url: "https://events.pagerduty.com/v2/enqueue".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "pagerduty".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_pagerduty".to_string(),
body: r#"{"payload": {"summary": "OpenObserve [{alert_status}]: {alert_name}", "severity": "{severity}", "source": "{source}"}, "routing_key": "{routing_key}", "event_action": "trigger"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "discord".to_string(),
name: "Discord".to_string(),
description: "Send notifications to Discord".to_string(),
destination_type: "http".to_string(),
icon: "discord-icon".to_string(),
popular: true,
category: "messaging".to_string(),
endpoint: Some(EndpointConfig {
url: "https://discord.com/api/webhooks/YOUR/DISCORD/WEBHOOK".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "discord".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_discord".to_string(),
body: r#"{"content": "[{alert_status}] {alert_name}"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "webhook".to_string(),
name: "Generic Webhook".to_string(),
description: "Generic webhook for any HTTP endpoint".to_string(),
destination_type: "http".to_string(),
icon: "webhook-icon".to_string(),
popular: false,
category: "generic".to_string(),
endpoint: Some(EndpointConfig {
url: "https://your-service.com/webhook".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "webhook".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_webhook".to_string(),
body: r#"{"alert": {"name": "{alert_name}", "status": "{alert_status}"}}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "opsgenie".to_string(),
name: "Opsgenie".to_string(),
description: "Create alerts in Opsgenie".to_string(),
destination_type: "http".to_string(),
icon: "opsgenie-icon".to_string(),
popular: true,
category: "incident".to_string(),
endpoint: Some(EndpointConfig {
url: "https://api.opsgenie.com/v2/alerts".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "opsgenie".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_opsgenie".to_string(),
body: r#"{"message": "[{alert_status}] {alert_name}", "priority": "{credential_priority}"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "servicenow".to_string(),
name: "ServiceNow".to_string(),
description: "Create incidents in ServiceNow".to_string(),
destination_type: "http".to_string(),
icon: "servicenow-icon".to_string(),
popular: true,
category: "incident".to_string(),
endpoint: Some(EndpointConfig {
url: "https://YOUR_INSTANCE.service-now.com/api/now/table/incident".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "servicenow".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_servicenow".to_string(),
body: r#"{"short_description": "[{alert_status}] {alert_name}", "assignment_group": "{credential_assignmentGroup}"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
PrebuiltDestinationConfig {
id: "jira".to_string(),
name: "Jira".to_string(),
description: "Create Jira issues and comment on them".to_string(),
destination_type: "http".to_string(),
icon: "jira-icon".to_string(),
popular: true,
category: "incident".to_string(),
endpoint: Some(EndpointConfig {
url: "https://YOUR_SITE.atlassian.net".to_string(),
method: "POST".to_string(),
skip_tls_verify: false,
headers: HashMap::from([("Content-Type".to_string(), "application/json".to_string())]),
output_format: "JSON".to_string(),
destination_type: "jira".to_string(),
}),
template: TemplateConfig {
name: "prebuilt_jira".to_string(),
body: r#"{"note": "The Jira destination builds the issue text from the alert data and does not render this template.", "alert_name": "{alert_name}", "alert_status": "{alert_status}"}"#.to_string(),
title: None,
},
credential_fields: vec![],
metadata: HashMap::new(),
},
],
/// The shipped `config/prebuilt-destinations.json`, compiled into the binary.
///
/// Release images copy only the binary into a distroless runtime, so the
/// relative path that `load_prebuilt_config` reads never exists there. Before
/// this was embedded, every real deployment fell back to a hand-written copy
/// whose bodies were one line (`[{alert_status}] {alert_name}`).
const EMBEDDED_CONFIG: &str = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../config/prebuilt-destinations.json"
));
/// Bodies the old hand-written fallback shipped for the chat and email templates, as
/// `(template name, body)`. These templates only change how a message looks, so a row that still
/// holds one of these bodies is sent with the shipped body.
pub const LEGACY_BUILTIN_BODIES: &[(&str, &str)] = &[
(
"prebuilt_slack",
r#"{"text": "[{alert_status}] {alert_name}"}"#,
),
("prebuilt_email", "<h2>[{alert_status}] {alert_name}</h2>"),
(
"prebuilt_msteams",
r#"{"@type": "MessageCard", "text": "[{alert_status}] {alert_name}"}"#,
),
// A destination of type `teams` saves its copy under the endpoint type's name.
(
"prebuilt_teams",
r#"{"@type": "MessageCard", "text": "[{alert_status}] {alert_name}"}"#,
),
(
"prebuilt_discord",
r#"{"content": "[{alert_status}] {alert_name}"}"#,
),
];
/// Bodies the old hand-written fallback shipped for templates that open tickets or feed other
/// systems. The shipped bodies add fields (urgency, impact, caller, links) that change what the
/// receiving system creates, so a row that holds one of these bodies keeps it: it is not upgraded
/// on read and the startup reseed does not overwrite it.
pub const KEPT_LEGACY_BODIES: &[(&str, &str)] = &[
(
"prebuilt_pagerduty",
r#"{"payload": {"summary": "OpenObserve [{alert_status}]: {alert_name}", "severity": "{severity}", "source": "{source}"}, "routing_key": "{routing_key}", "event_action": "trigger"}"#,
),
(
"prebuilt_webhook",
r#"{"alert": {"name": "{alert_name}", "status": "{alert_status}"}}"#,
),
(
"prebuilt_opsgenie",
r#"{"message": "[{alert_status}] {alert_name}", "priority": "{credential_priority}"}"#,
),
(
"prebuilt_servicenow",
r#"{"short_description": "[{alert_status}] {alert_name}", "assignment_group": "{credential_assignmentGroup}"}"#,
),
];
/// Chat and email bodies that earlier versions of `config/prebuilt-destinations.json` shipped,
/// keyed by template name. Deployments that had the file on disk saved rows with these bodies.
const PREVIOUS_SHIPPED_BODIES: &str = include_str!("prebuilt_previous_bodies.json");
fn previous_shipped_bodies() -> &'static HashMap<String, Vec<String>> {
static BODIES: std::sync::OnceLock<HashMap<String, Vec<String>>> = std::sync::OnceLock::new();
BODIES.get_or_init(|| {
serde_json::from_str(PREVIOUS_SHIPPED_BODIES)
.expect("prebuilt_previous_bodies.json is valid; a test parses it")
})
}
/// True when `body` is a body that the system once shipped for the chat or email template `name`
/// and that the read path replaces with the shipped body.
pub fn is_legacy_builtin_body(name: &str, body: &str) -> bool {
LEGACY_BUILTIN_BODIES
.iter()
.any(|(n, b)| *n == name && *b == body)
|| previous_shipped_bodies()
.get(name)
.is_some_and(|bodies| bodies.iter().any(|b| b == body))
}
/// True when `body` is the old fallback body of a ticketing or webhook template `name`, which the
/// startup reseed must leave in place.
pub fn is_kept_legacy_body(name: &str, body: &str) -> bool {
KEPT_LEGACY_BODIES
.iter()
.any(|(n, b)| *n == name && *b == body)
}
/// Replaces `body` with the shipped body when it is an earlier system body of the chat or email
/// template `name`. Every stored row goes through this on read, so a row an old node or a lagging
/// replica still holds is sent with the shipped body. Returns true when it changed `body`.
pub fn upgrade_legacy_body(name: &str, body: &mut String) -> bool {
if !is_legacy_builtin_body(name, body) {
return false;
}
let Some(shipped) = name
.strip_prefix(PREBUILT_TEMPLATE_PREFIX)
.and_then(get_prebuilt_template)
else {
return false;
};
if shipped.body == *body {
return false;
}
*body = shipped.body;
true
}
/// True when `body` is exactly the body this binary ships for the system template `name`, so the
/// system, not a user or an operator's override file, wrote every placeholder in it.
pub fn is_shipped_prebuilt_body(name: &str, body: &str) -> bool {
let Some(prebuilt_type) = name.strip_prefix(PREBUILT_TEMPLATE_PREFIX) else {
return false;
};
find_template(&load_builtin_config(), prebuilt_type).is_some_and(|t| t.body == body)
}
/// Built-in config: the embedded copy of the shipped JSON.
fn load_builtin_config() -> PrebuiltDestinationsConfig {
serde_json::from_str(EMBEDDED_CONFIG)
.expect("config/prebuilt-destinations.json is valid; a test parses it")
}
fn convert_to_destination(config: PrebuiltDestinationConfig) -> Result<Destination, String> {
@@ -523,246 +429,13 @@ fn convert_to_destination(config: PrebuiltDestinationConfig) -> Result<Destinati
})
}
/// Built-in fallback destinations in case config file is not available
/// Built-in destinations, from the embedded config.
fn load_builtin_destinations() -> Vec<Destination> {
use hashbrown::HashMap;
use crate::meta::destinations::{
DestinationType, Email, Endpoint, HTTPOutputFormat, HTTPType, Module,
};
vec![
Destination {
id: None,
org_id: String::new(),
name: "Slack Webhook".to_string(),
module: Module::Alert {
template: Some("prebuilt_slack".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([(
"Content-Type".to_string(),
"application/json".to_string(),
)])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("slack".to_string()),
metadata: HashMap::from([
("service".to_string(), "slack".to_string()),
(
"description".to_string(),
"Slack webhook for team notifications".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "Microsoft Teams Webhook".to_string(),
module: Module::Alert {
template: Some("prebuilt_msteams".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://your-tenant.webhook.office.com/webhookb2/YOUR-TEAMS-WEBHOOK-URL"
.to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([(
"Content-Type".to_string(),
"application/json".to_string(),
)])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("teams".to_string()),
metadata: HashMap::from([
("service".to_string(), "teams".to_string()),
(
"description".to_string(),
"Microsoft Teams webhook for team notifications".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "PagerDuty Events API".to_string(),
module: Module::Alert {
template: Some("prebuilt_pagerduty".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://events.pagerduty.com/v2/enqueue".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([
("Content-Type".to_string(), "application/json".to_string()),
(
"Authorization".to_string(),
"Token YOUR_INTEGRATION_KEY".to_string(),
),
])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("pagerduty".to_string()),
metadata: HashMap::from([
("service".to_string(), "pagerduty".to_string()),
(
"description".to_string(),
"PagerDuty incident management".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "Discord Webhook".to_string(),
module: Module::Alert {
template: Some("prebuilt_discord".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://discord.com/api/webhooks/YOUR/DISCORD/WEBHOOK".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([(
"Content-Type".to_string(),
"application/json".to_string(),
)])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("discord".to_string()),
metadata: HashMap::from([
("service".to_string(), "discord".to_string()),
(
"description".to_string(),
"Discord webhook for community notifications".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "Generic Webhook".to_string(),
module: Module::Alert {
template: Some("prebuilt_webhook".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://your-service.com/webhook".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([(
"Content-Type".to_string(),
"application/json".to_string(),
)])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("webhook".to_string()),
metadata: HashMap::from([
("service".to_string(), "webhook".to_string()),
(
"description".to_string(),
"Generic webhook destination".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "Opsgenie".to_string(),
module: Module::Alert {
template: Some("prebuilt_opsgenie".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://api.opsgenie.com/v2/alerts".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([
("Content-Type".to_string(), "application/json".to_string()),
(
"Authorization".to_string(),
"GenieKey YOUR_API_KEY".to_string(),
),
])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("opsgenie".to_string()),
metadata: HashMap::from([
("service".to_string(), "opsgenie".to_string()),
(
"description".to_string(),
"Opsgenie incident management and alerting".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "ServiceNow".to_string(),
module: Module::Alert {
template: Some("prebuilt_servicenow".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://YOUR_INSTANCE.service-now.com/api/now/table/incident".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([
("Content-Type".to_string(), "application/json".to_string()),
(
"Authorization".to_string(),
"Basic YOUR_AUTH_TOKEN".to_string(),
),
])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("servicenow".to_string()),
metadata: HashMap::from([
("service".to_string(), "servicenow".to_string()),
(
"description".to_string(),
"ServiceNow incident management".to_string(),
),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "Jira".to_string(),
module: Module::Alert {
template: Some("prebuilt_jira".to_string()),
destination_type: DestinationType::Http(Endpoint {
url: "https://YOUR_SITE.atlassian.net".to_string(),
method: HTTPType::POST,
skip_tls_verify: false,
headers: Some(HashMap::from([
("Content-Type".to_string(), "application/json".to_string()),
("Accept".to_string(), "application/json".to_string()),
(
"Authorization".to_string(),
"Basic YOUR_AUTH_TOKEN".to_string(),
),
])),
output_format: Some(HTTPOutputFormat::JSON),
destination_type: Some("jira".to_string()),
metadata: HashMap::from([
("service".to_string(), "jira".to_string()),
("description".to_string(), "Jira issue tracking".to_string()),
]),
}),
},
},
Destination {
id: None,
org_id: String::new(),
name: "Email Notification".to_string(),
module: Module::Alert {
template: Some("prebuilt_email".to_string()),
destination_type: DestinationType::Email(Email {
recipients: vec!["admin@your-domain.com".to_string()],
}),
},
},
]
load_builtin_config()
.destinations
.into_iter()
.filter_map(|dest| convert_to_destination(dest).ok())
.collect()
}
#[cfg(test)]
@@ -1048,4 +721,148 @@ mod tests {
_ => panic!("Expected Email template type"),
}
}
/// Tests run from the crate dir, where `config/prebuilt-destinations.json` does not exist,
/// which is the same as a release image: the template must still be the shipped one.
#[test]
fn slack_template_without_a_config_dir_is_the_shipped_blocks_body() {
assert!(!std::path::Path::new("config/prebuilt-destinations.json").exists());
let body = get_prebuilt_template("slack").unwrap().body;
assert!(body.contains("\"blocks\""), "{body}");
assert!(body.contains("{alert_url}"), "{body}");
assert!(!is_legacy_builtin_body("prebuilt_slack", &body));
}
/// Slack rejects a header block over 150 characters, and an alert name has no such limit.
#[test]
fn slack_body_has_no_header_block() {
let body = get_prebuilt_template("slack").unwrap().body;
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
for block in v["blocks"].as_array().unwrap() {
assert_ne!(block["type"], "header", "{block}");
}
}
#[test]
fn legacy_bodies_upgrade_and_other_bodies_stay() {
let mut slack = r#"{"text": "[{alert_status}] {alert_name}"}"#.to_string();
assert!(upgrade_legacy_body("prebuilt_slack", &mut slack));
assert!(slack.contains("\"blocks\""), "{slack}");
let mut teams =
r#"{"@type": "MessageCard", "text": "[{alert_status}] {alert_name}"}"#.to_string();
assert!(upgrade_legacy_body("prebuilt_teams", &mut teams));
assert_eq!(teams, get_prebuilt_template("msteams").unwrap().body);
let mut email = "<h2>[{alert_status}] {alert_name}</h2>".to_string();
assert!(upgrade_legacy_body("prebuilt_email", &mut email));
assert_ne!(email, "<h2>[{alert_status}] {alert_name}</h2>");
let mut edited = r#"{"text": "custom {alert_status}"}"#.to_string();
assert!(!upgrade_legacy_body("prebuilt_slack", &mut edited));
let mut other_name = r#"{"text": "[{alert_status}] {alert_name}"}"#.to_string();
assert!(!upgrade_legacy_body("my_slack", &mut other_name));
assert_eq!(other_name, r#"{"text": "[{alert_status}] {alert_name}"}"#);
let mut shipped = get_prebuilt_template("slack").unwrap().body;
assert!(!upgrade_legacy_body("prebuilt_slack", &mut shipped));
}
#[test]
fn ticketing_and_webhook_legacy_bodies_are_kept() {
for (name, body) in KEPT_LEGACY_BODIES {
let mut stored = body.to_string();
assert!(!upgrade_legacy_body(name, &mut stored), "{name}");
assert_eq!(stored, *body);
assert!(is_kept_legacy_body(name, body), "{name}");
assert!(!is_legacy_builtin_body(name, body), "{name}");
}
let servicenow = get_prebuilt_template("servicenow").unwrap().body;
assert!(!is_kept_legacy_body("prebuilt_servicenow", &servicenow));
}
#[test]
fn earlier_shipped_chat_bodies_upgrade_to_the_shipped_body() {
let previous = previous_shipped_bodies();
let old_slack = &previous["prebuilt_slack"];
assert!(
old_slack.iter().any(|b| b.contains("\"header\"")),
"the rich Slack body with a header block is listed"
);
let shipped = get_prebuilt_template("slack").unwrap().body;
for body in old_slack {
let mut stored = body.clone();
assert!(upgrade_legacy_body("prebuilt_slack", &mut stored));
assert_eq!(stored, shipped);
}
for (name, bodies) in previous {
let prebuilt_type = name.strip_prefix(PREBUILT_TEMPLATE_PREFIX).unwrap();
assert!(
matches!(
prebuilt_type,
"slack" | "msteams" | "teams" | "discord" | "email"
),
"only chat and email bodies upgrade, found {name}"
);
let shipped = get_prebuilt_template(prebuilt_type).unwrap().body;
assert!(!bodies.contains(&shipped), "{name} lists its shipped body");
}
}
#[test]
fn only_an_unchanged_shipped_body_counts_as_shipped() {
let body = get_prebuilt_template("slack").unwrap().body;
assert!(is_shipped_prebuilt_body("prebuilt_slack", &body));
assert!(!is_shipped_prebuilt_body(
"prebuilt_slack",
r#"{"text": "x"}"#
));
assert!(!is_shipped_prebuilt_body("my_slack", &body));
// An operator's override file is not the body this binary ships.
assert!(!is_shipped_prebuilt_body(
"prebuilt_webhook",
r#"{"payload":{alert_description}}"#
));
let teams = get_prebuilt_template("teams").unwrap().body;
assert!(is_shipped_prebuilt_body("prebuilt_teams", &teams));
}
#[test]
fn opsgenie_body_leaves_the_alias_to_the_episode_stamp() {
let body = get_prebuilt_template("opsgenie").unwrap().body;
let v: serde_json::Value = serde_json::from_str(&body).unwrap();
assert!(v.get("alias").is_none(), "{body}");
}
#[test]
fn teams_alias_resolves_to_the_msteams_template() {
let teams = get_prebuilt_template("teams").unwrap();
assert_eq!(teams.body, get_prebuilt_template("msteams").unwrap().body);
}
#[test]
fn builtin_config_is_the_shipped_json() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../config/prebuilt-destinations.json"
);
let file: PrebuiltDestinationsConfig =
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let builtin = load_builtin_config();
assert_eq!(builtin.revision, file.revision);
assert_eq!(
serde_json::to_value(&builtin.destinations).unwrap(),
serde_json::to_value(&file.destinations).unwrap()
);
}
#[test]
fn no_shipped_body_is_a_legacy_one_liner() {
for d in load_builtin_config().destinations {
assert!(
!is_legacy_builtin_body(&d.template.name, &d.template.body),
"'{}' still ships the old one-line body, so the reseed would loop",
d.id
);
}
}
}
@@ -0,0 +1,23 @@
{
"prebuilt_slack": [
"{\n \"text\": \"🚨 Alert: {alert_name}\",\n \"blocks\": [\n {\n \"type\": \"header\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"🚨 Alert: {alert_name}\"\n }\n },\n {\n \"type\": \"section\",\n \"fields\": [\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Stream:*\\n{stream_name}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Type:*\\n{stream_type}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Count:*\\n{alert_count}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Threshold:*\\n{alert_operator} {alert_threshold}\"\n }\n ]\n },\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"*Status:* 🔴 Firing\\n*Time:* {alert_time}\"\n }\n },\n {\n \"type\": \"actions\",\n \"elements\": [\n {\n \"type\": \"button\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"View in OpenObserve\"\n },\n \"url\": \"{alert_url}\"\n }\n ]\n }\n ]\n}",
"{\n \"text\": \"🚨 Alert: {alert_name}\",\n \"blocks\": [\n {\n \"type\": \"header\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"🚨 Alert: {alert_name}\"\n }\n },\n {\n \"type\": \"section\",\n \"fields\": [\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Stream:*\\n{stream_name}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Type:*\\n{stream_type}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Count:*\\n{alert_count}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Threshold:*\\n{alert_operator} {alert_threshold}\"\n }\n ]\n },\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"*Status:* 🔴 Firing\\n*Time:* {alert_trigger_time_str}\"\n }\n },\n {\n \"type\": \"actions\",\n \"elements\": [\n {\n \"type\": \"button\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"View in OpenObserve\"\n },\n \"url\": \"{alert_url}\"\n }\n ]\n }\n ]\n}",
"{\n \"text\": \"[{alert_status}] {alert_name}\",\n \"blocks\": [\n {\n \"type\": \"header\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"[{alert_status}] {alert_name}\"\n }\n },\n {\n \"type\": \"section\",\n \"fields\": [\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Stream:*\\n{stream_name}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Type:*\\n{stream_type}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Count:*\\n{alert_count}\"\n },\n {\n \"type\": \"mrkdwn\",\n \"text\": \"*Threshold:*\\n{alert_operator} {alert_threshold}\"\n }\n ]\n },\n {\n \"type\": \"section\",\n \"text\": {\n \"type\": \"mrkdwn\",\n \"text\": \"*Status:* {alert_status}\\n*Time:* {alert_trigger_time_str}\"\n }\n },\n {\n \"type\": \"actions\",\n \"elements\": [\n {\n \"type\": \"button\",\n \"text\": {\n \"type\": \"plain_text\",\n \"text\": \"View in OpenObserve\"\n },\n \"url\": \"{alert_url}\"\n }\n ]\n }\n ]\n}"
],
"prebuilt_msteams": [
"{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"D63638\",\n \"summary\": \"Alert: {alert_name}\",\n \"sections\": [\n {\n \"activityTitle\": \"🚨 Alert: {alert_name}\",\n \"activitySubtitle\": \"OpenObserve Alert Notification\",\n \"activityImage\": \"https://openobserve.ai/favicon.ico\",\n \"facts\": [\n {\n \"name\": \"Stream\",\n \"value\": \"{stream_name}\"\n },\n {\n \"name\": \"Type\",\n \"value\": \"{stream_type}\"\n },\n {\n \"name\": \"Status\",\n \"value\": \"🔴 Firing\"\n },\n {\n \"name\": \"Count\",\n \"value\": \"{alert_count}\"\n },\n {\n \"name\": \"Threshold\",\n \"value\": \"{alert_operator} {alert_threshold}\"\n },\n {\n \"name\": \"Time\",\n \"value\": \"{alert_time}\"\n }\n ],\n \"markdown\": true\n }\n ],\n \"potentialActions\": [\n {\n \"@type\": \"OpenUri\",\n \"name\": \"View in OpenObserve\",\n \"targets\": [\n {\n \"os\": \"default\",\n \"uri\": \"{alert_url}\"\n }\n ]\n }\n ]\n}",
"{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"D63638\",\n \"summary\": \"Alert: {alert_name}\",\n \"sections\": [\n {\n \"activityTitle\": \"🚨 Alert: {alert_name}\",\n \"activitySubtitle\": \"OpenObserve Alert Notification\",\n \"activityImage\": \"https://openobserve.ai/favicon.ico\",\n \"facts\": [\n {\n \"name\": \"Stream\",\n \"value\": \"{stream_name}\"\n },\n {\n \"name\": \"Type\",\n \"value\": \"{stream_type}\"\n },\n {\n \"name\": \"Status\",\n \"value\": \"🔴 Firing\"\n },\n {\n \"name\": \"Count\",\n \"value\": \"{alert_count}\"\n },\n {\n \"name\": \"Threshold\",\n \"value\": \"{alert_operator} {alert_threshold}\"\n },\n {\n \"name\": \"Time\",\n \"value\": \"{alert_trigger_time_str}\"\n }\n ],\n \"markdown\": true\n }\n ],\n \"potentialActions\": [\n {\n \"@type\": \"OpenUri\",\n \"name\": \"View in OpenObserve\",\n \"targets\": [\n {\n \"os\": \"default\",\n \"uri\": \"{alert_url}\"\n }\n ]\n }\n ]\n}"
],
"prebuilt_teams": [
"{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"D63638\",\n \"summary\": \"Alert: {alert_name}\",\n \"sections\": [\n {\n \"activityTitle\": \"🚨 Alert: {alert_name}\",\n \"activitySubtitle\": \"OpenObserve Alert Notification\",\n \"activityImage\": \"https://openobserve.ai/favicon.ico\",\n \"facts\": [\n {\n \"name\": \"Stream\",\n \"value\": \"{stream_name}\"\n },\n {\n \"name\": \"Type\",\n \"value\": \"{stream_type}\"\n },\n {\n \"name\": \"Status\",\n \"value\": \"🔴 Firing\"\n },\n {\n \"name\": \"Count\",\n \"value\": \"{alert_count}\"\n },\n {\n \"name\": \"Threshold\",\n \"value\": \"{alert_operator} {alert_threshold}\"\n },\n {\n \"name\": \"Time\",\n \"value\": \"{alert_time}\"\n }\n ],\n \"markdown\": true\n }\n ],\n \"potentialActions\": [\n {\n \"@type\": \"OpenUri\",\n \"name\": \"View in OpenObserve\",\n \"targets\": [\n {\n \"os\": \"default\",\n \"uri\": \"{alert_url}\"\n }\n ]\n }\n ]\n}",
"{\n \"@type\": \"MessageCard\",\n \"@context\": \"http://schema.org/extensions\",\n \"themeColor\": \"D63638\",\n \"summary\": \"Alert: {alert_name}\",\n \"sections\": [\n {\n \"activityTitle\": \"🚨 Alert: {alert_name}\",\n \"activitySubtitle\": \"OpenObserve Alert Notification\",\n \"activityImage\": \"https://openobserve.ai/favicon.ico\",\n \"facts\": [\n {\n \"name\": \"Stream\",\n \"value\": \"{stream_name}\"\n },\n {\n \"name\": \"Type\",\n \"value\": \"{stream_type}\"\n },\n {\n \"name\": \"Status\",\n \"value\": \"🔴 Firing\"\n },\n {\n \"name\": \"Count\",\n \"value\": \"{alert_count}\"\n },\n {\n \"name\": \"Threshold\",\n \"value\": \"{alert_operator} {alert_threshold}\"\n },\n {\n \"name\": \"Time\",\n \"value\": \"{alert_trigger_time_str}\"\n }\n ],\n \"markdown\": true\n }\n ],\n \"potentialActions\": [\n {\n \"@type\": \"OpenUri\",\n \"name\": \"View in OpenObserve\",\n \"targets\": [\n {\n \"os\": \"default\",\n \"uri\": \"{alert_url}\"\n }\n ]\n }\n ]\n}"
],
"prebuilt_discord": [
"{\n \"content\": \"🚨 Alert: {alert_name}\",\n \"embeds\": [\n {\n \"title\": \"Alert Details\",\n \"color\": 15158332,\n \"fields\": [\n {\n \"name\": \"Stream\",\n \"value\": \"{stream_name}\",\n \"inline\": true\n },\n {\n \"name\": \"Type\",\n \"value\": \"{stream_type}\",\n \"inline\": true\n },\n {\n \"name\": \"Count\",\n \"value\": \"{alert_count}\",\n \"inline\": true\n },\n {\n \"name\": \"Threshold\",\n \"value\": \"{alert_operator} {alert_threshold}\",\n \"inline\": true\n }\n ],\n \"footer\": {\n \"text\": \"OpenObserve Alert\",\n \"icon_url\": \"https://openobserve.ai/favicon.ico\"\n },\n \"timestamp\": \"{alert_time}\"\n }\n ]\n}",
"{\n \"content\": \"🚨 Alert: {alert_name}\",\n \"embeds\": [\n {\n \"title\": \"Alert Details\",\n \"color\": 15158332,\n \"fields\": [\n {\n \"name\": \"Stream\",\n \"value\": \"{stream_name}\",\n \"inline\": true\n },\n {\n \"name\": \"Type\",\n \"value\": \"{stream_type}\",\n \"inline\": true\n },\n {\n \"name\": \"Count\",\n \"value\": \"{alert_count}\",\n \"inline\": true\n },\n {\n \"name\": \"Threshold\",\n \"value\": \"{alert_operator} {alert_threshold}\",\n \"inline\": true\n }\n ],\n \"footer\": {\n \"text\": \"OpenObserve Alert\",\n \"icon_url\": \"https://openobserve.ai/favicon.ico\"\n },\n \"timestamp\": \"{alert_trigger_time_str}\"\n }\n ]\n}"
],
"prebuilt_email": [
"<h2>🚨 Alert Notification: {alert_name}</h2><p><strong>Stream:</strong> {stream_name}<br><strong>Type:</strong> {stream_type}<br><strong>Status:</strong> 🔴 Firing<br><strong>Count:</strong> {alert_count}<br><strong>Threshold:</strong> {alert_operator} {alert_threshold}<br><strong>Time:</strong> {alert_time}</p><p><a href='{alert_url}'>View in OpenObserve</a></p>",
"<h2>🚨 Alert Notification: {alert_name}</h2><p><strong>Stream:</strong> {stream_name}<br><strong>Type:</strong> {stream_type}<br><strong>Status:</strong> 🔴 Firing<br><strong>Count:</strong> {alert_count}<br><strong>Threshold:</strong> {alert_operator} {alert_threshold}<br><strong>Time:</strong> {alert_trigger_time_str}</p><p><a href='{alert_url}'>View in OpenObserve</a></p>"
]
}
+55 -1
View File
@@ -28,9 +28,31 @@ use super::context::NotificationContext;
/// Render `tpl` against `ctx`. Pure: no I/O, no clock, no DB.
pub fn apply_custom_template(tpl: &str, ctx: &NotificationContext, is_email: bool) -> String {
render_custom(tpl, ctx, is_email, false)
}
/// Render a stored Custom template. An unchanged shipped prebuilt body also escapes alert values,
/// so an alert named `cpu "high"` still sends valid JSON. Any body a user wrote or edited keeps
/// the raw insert, because it may place a value outside a JSON string.
pub fn apply_template_body(
template: &config::meta::destinations::Template,
ctx: &NotificationContext,
is_email: bool,
) -> String {
let shipped = config::prebuilt_loader::is_shipped_prebuilt_body(&template.name, &template.body);
render_custom(&template.body, ctx, is_email, shipped)
}
fn render_custom(
tpl: &str,
ctx: &NotificationContext,
is_email: bool,
escape_alert: bool,
) -> String {
// Another kind's names and text are free (a downtime "deploy" <db>), so a JSON body escapes
// them as it escapes attributes; plain text such as an SNS message gets them as written.
let json_body = ctx.kind != NotificationKind::Alert && !is_email && looks_like_json(tpl);
let json_body =
(ctx.kind != NotificationKind::Alert || escape_alert) && !is_email && looks_like_json(tpl);
let prepared = super::modifiers::prepare_modifiers(
tpl,
|field| {
@@ -674,6 +696,38 @@ mod golden {
);
}
#[test]
fn a_shipped_prebuilt_body_escapes_alert_values_and_an_edited_one_does_not() {
let ctx = NotificationContext {
alert_name: "cpu \"high\"\nnow".into(),
alert_description: r#"{"cpu":99}"#.into(),
..Default::default()
};
for kind in [
"slack",
"msteams",
"discord",
"webhook",
"opsgenie",
"pagerduty",
] {
let template = config::prebuilt_loader::get_prebuilt_template(kind).unwrap();
let body = apply_template_body(&template, &ctx, false);
let json: serde_json::Value =
serde_json::from_str(&body).unwrap_or_else(|e| panic!("{kind}: {e}: {body}"));
assert!(
json.to_string().contains(r#"cpu \"high\"\nnow"#),
"{kind}: {body}"
);
}
let mut edited = config::prebuilt_loader::get_prebuilt_template("webhook").unwrap();
edited.body = r#"{"data": {alert_description}}"#.into();
assert_eq!(
apply_template_body(&edited, &ctx, false),
r#"{"data": {"cpu":99}}"#
);
}
#[test]
fn a_synthetics_email_body_html_escapes_the_scalars() {
let mut ctx = NotificationContext {
+1 -1
View File
@@ -39,7 +39,7 @@ pub mod send;
pub mod test_send;
pub use context::{LegacyPayload, NotificationContext, build_row_columns};
pub use custom::apply_custom_template;
pub use custom::{apply_custom_template, apply_template_body};
pub use format::{ChannelFormat, derive_channel_format, teams_format_for_url};
pub use preview::{PreviewError, PreviewRequest, PreviewResponse, preview};
pub use render::{RenderError, RenderedMessage, render, severity_color};
+3 -2
View File
@@ -20,7 +20,8 @@ use std::time::Duration;
use config::meta::destinations::{DestinationType, Email, Template, TemplateKind, TemplateType};
use super::{
NotificationContext, RenderedMessage, apply_custom_template, derive_channel_format,
NotificationContext, RenderedMessage, apply_custom_template, apply_template_body,
derive_channel_format,
format::ChannelFormat,
jira,
platform::{self, platform_of},
@@ -131,7 +132,7 @@ pub async fn send_to_destination(
match template.kind {
TemplateKind::Custom => {
// Unchanged legacy path — byte-identical output.
let msg = apply_custom_template(&template.body, ctx, is_email);
let msg = apply_template_body(template, ctx, is_email);
let msg = stamp_platform_key(dest_type, ctx, msg);
let title = custom_title(template, ctx, is_email);
let (email_subject, sns_subject) = custom_subjects(subject, title);
+26 -4
View File
@@ -37,7 +37,7 @@ use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::alerts::notifications::{
apply_custom_template,
apply_template_body,
context::NotificationContext,
render::{
DEFAULT_LINK_LABEL,
@@ -399,7 +399,7 @@ pub async fn send_form_test(
pub fn render_wire(template: &Template, ctx: &NotificationContext) -> anyhow::Result<RenderedWire> {
match template.kind {
TemplateKind::Custom => Ok(wire_from_custom(
&apply_custom_template(&template.body, ctx, false),
&apply_template_body(template, ctx, false),
ctx,
)),
TemplateKind::Content => {
@@ -510,7 +510,15 @@ pub fn wire_from_custom(msg: &str, ctx: &NotificationContext) -> RenderedWire {
.filter(|t| !t.is_empty());
let has_header = wire.title != ctx.alert_name;
match text {
Some(t) if !has_header => wire.title = t.to_string(),
Some(t) if !has_header => {
wire.title = t.to_string();
// A body that opens with its own bold title line, as the prebuilt Slack body does,
// would show the title twice.
let bold = format!("*{t}*");
if body.first().is_some_and(|b| b.trim() == bold) {
body.remove(0);
}
}
Some(t) if body.is_empty() && t != wire.title => body.push(t.to_string()),
_ => {}
}
@@ -944,7 +952,7 @@ mod tests {
use serde_json::json;
use super::*;
use crate::alerts::notifications::resolve::Link;
use crate::alerts::notifications::{apply_custom_template, resolve::Link};
const PREBUILT_SLACK: &str = r#"{
"text": "[{alert_status}] {alert_name}",
@@ -1289,6 +1297,20 @@ mod tests {
wire.body, wire.title,
"the text is not repeated as the body"
);
assert!(
!wire.body.contains("[firing] checkout-errors"),
"the bold title line is not repeated in the body: {wire:?}"
);
let starred = NotificationContext {
alert_name: "cpu_high*".into(),
..ctx.clone()
};
let wire = render_wire(&built_in, &starred).unwrap();
assert_eq!(wire.title, "[firing] cpu_high*");
assert!(
!wire.body.contains("[firing] cpu_high*"),
"a name ending in * is not shown twice: {wire:?}"
);
}
#[test]
+8 -2
View File
@@ -627,8 +627,14 @@ pub async fn ensure_system_templates() -> Result<(), anyhow::Error> {
// body/title) so existing installs pick up the correction —
// but only when the reseed gate says to (revision-gated, see
// `should_apply_prebuilt`).
let drifted = existing.body != template.body
|| existing.template_type != template.template_type;
// A ticketing or webhook row that still holds the old fallback body keeps it:
// the shipped body adds fields that change what the receiving system creates.
let drifted = (existing.body != template.body
|| existing.template_type != template.template_type)
&& !config::prebuilt_loader::is_kept_legacy_body(
&template.name,
&existing.body,
);
if should_apply_prebuilt(shipped_rev, applied_rev, drifted) && drifted {
// Preserve the stored id so this is an update, not an insert.
template.id = existing.id;
+31 -1
View File
@@ -50,13 +50,17 @@ impl TryFrom<Model> for Template {
};
let id = svix_ksuid::Ksuid::from_str(&value.id)
.map_err(|e| TemplateError::ConvertingId(e.to_string()))?;
// A row saved from the old one-line prebuilt fallback reads as the shipped body, on every
// path: cache seed, watch reload, a lagging replica, an old node's late write.
let mut body = value.body;
config::prebuilt_loader::upgrade_legacy_body(&value.name, &mut body);
Ok(Self {
id: Some(id),
org_id: value.org,
name: value.name,
is_default: value.is_default,
template_type,
body: value.body,
body,
kind: TemplateKind::from(value.kind.as_str()),
applies_to: applies_to_from_column(&value.applies_to),
})
@@ -985,6 +989,32 @@ mod tests {
);
}
#[test]
fn a_row_with_the_old_one_line_body_reads_as_the_shipped_body() {
let id = svix_ksuid::Ksuid::new(None, None).to_string();
let mut model = make_model(&id, None, "http");
model.name = "prebuilt_slack".to_string();
model.body = r#"{"text": "[{alert_status}] {alert_name}"}"#.to_string();
let tmpl = Template::try_from(model.clone()).unwrap();
assert_eq!(
tmpl.body,
config::prebuilt_loader::get_prebuilt_template("slack")
.unwrap()
.body
);
assert_eq!(tmpl.name, "prebuilt_slack");
assert_eq!(tmpl.id.unwrap().to_string(), id);
model.body = r#"{"text": "edited {alert_name}"}"#.to_string();
let edited = Template::try_from(model.clone()).unwrap();
assert_eq!(edited.body, r#"{"text": "edited {alert_name}"}"#);
model.name = "my_slack".to_string();
model.body = r#"{"text": "[{alert_status}] {alert_name}"}"#.to_string();
let other = Template::try_from(model).unwrap();
assert_eq!(other.body, r#"{"text": "[{alert_status}] {alert_name}"}"#);
}
#[test]
fn test_try_from_model_sns_template() {
let id = svix_ksuid::Ksuid::new(None, None).to_string();