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
7 changes: 7 additions & 0 deletions .changeset/webhook-tags-variable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/common-utils': minor
'@hyperdx/api': minor
'@hyperdx/app': minor
---

feat: Expose alert tags to Generic and incident.io webhook bodies as `{{tags}}` (comma-separated, or iterate with `{{#each tags}}`), and include them in the default incident.io body's `metadata.tags`, so one shared webhook can route alerts by owning team
15 changes: 13 additions & 2 deletions docs/alert-webhook-template-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ a HyperDX alert without parsing the human-readable message body.
| `{{sourceQuery}}` | string | The condition behind the alert — search expression or SQL (see below). |
| `{{teamId}}` | string | Team the alert belongs to. |
| `{{note}}` | string | The alert's freeform note — commonly a runbook link. |
| `{{tags}}` | list of strings | The alert's tags. `{{tags}}` renders them comma-separated (`team-payments,prod`); iterate with `{{#each tags}}` to emit a JSON array (see below). Empty when the alert has no tags. |

Strings are JSON-escaped, so they are safe to drop into a quoted slot.
Numbers (`startTime`, `endTime`, `threshold`, `thresholdMax`, `value`) are
Expand Down Expand Up @@ -54,6 +55,16 @@ builder condition can each be Lucene or SQL, so the joined string is not
necessarily valid in either. It is truncated at 2000 characters. PromQL charts
do not support alerts, so no webhook carries a PromQL expression.

Tags let one shared webhook route alerts by owner: tag each alert with its
team and read the tag in the receiver. To send them as a JSON array rather
than one comma-separated string:

```
{
"tags": [{{#each tags}}"{{this}}"{{#unless @last}}, {{/unless}}{{/each}}]
}
```

An empty string is not valid JSON in an unquoted numeric slot, so guard any
number that may be absent. Compare against `undefined` rather than using
`{{#if}}`, which treats a legitimate bound of `0` as absent:
Expand Down Expand Up @@ -86,8 +97,8 @@ which is what the guard above is for.

incident.io accepts only `firing` or `resolved` in `status`, so the default
body maps HyperDX's state onto those two and carries `{{status}}` in
`metadata.hyperdx_status`, alongside the alert id, condition and evaluation
window. Only a firing and a resolve are delivered today, so that key reads
`metadata.hyperdx_status`, alongside the alert id, condition, evaluation
window and the alert's tags (comma-separated, in `metadata.tags`). Only a firing and a resolve are delivered today, so that key reads
`firing` or `resolved` as well. `metadata` is free-form, but incident.io only
surfaces the keys its alert source is configured to parse.

Expand Down
1 change: 1 addition & 0 deletions packages/api/src/routers/api/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,7 @@ router.post(
sourceQuery: 'SeverityText: "error"',
teamId: teamId.toString(),
note: 'Test webhook — no runbook',
tags: ['test-tag'],
};

const testChannel = { type: 'webhook' as const, channel: testWebhook };
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/tasks/checkAlerts/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,7 @@ export const renderAlertTemplate = async ({
),
teamId,
note: alert.note ?? '',
tags: alert.tags ?? [],

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — No test checks that an alert's tags reach the dispatched message

Add a case to the renderWithWebhook suite in packages/api/src/tasks/checkAlerts/__tests__/renderAlertTemplate.int.test.ts: give base.alert some tags and assert dispatched[0].message.tags equals them, plus a case for an alert with no tags that expects []. Today the new unit test only feeds a hand-built Message into buildWebhookTemplateVariables. If this line were deleted, every test would still pass and the customer's original bug ("tags": "") would come back.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

},
});
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,33 @@ describe('buildWebhookTemplateVariables', () => {
expect(buildWebhookTemplateVariables(message).var).toEqual({});
});

it('exposes tags as a comma-joined string and as a JSON-escaped list', () => {
const vars = buildWebhookTemplateVariables({
...message,
tags: ['team-payments', 'say "hi"'],
});
const render = (template: string) =>
JSON.parse(
createHandlebarsWithHelpers().compile(template, { noEscape: true })(
vars,
),
);

expect(render('{"tags": "{{tags}}"}').tags).toBe('team-payments,say "hi"');
// The array form published in docs/alert-webhook-template-variables.md.
expect(
render(
'{"tags": [{{#each tags}}"{{this}}"{{#unless @last}}, {{/unless}}{{/each}}]}',
).tags,
).toEqual(['team-payments', 'say "hi"']);
});

it('renders enriched fields as empty strings (never "undefined") when absent', () => {
const vars = buildWebhookTemplateVariables(message);
expect(vars.alertId).toBe('');
expect(vars.status).toBe('');
expect(vars.note).toBe('');
expect(vars.tags).toEqual([]);
expect(vars.startTimeISO).toBe(new Date(0).toISOString());
// A raw number renders as an empty slot when absent, not "undefined".
expect(vars.thresholdMax).toBeUndefined();
Expand Down Expand Up @@ -220,6 +242,9 @@ describe('the default incident.io body', () => {
value: '42',
group_key: 'checkout',
});
expect(render({ tags: ['team-payments', 'prod'] }).metadata.tags).toBe(
'team-payments,prod',
);
});

it('stays valid JSON when the alert carries no optional values', () => {
Expand All @@ -237,6 +262,7 @@ describe('the default incident.io body', () => {
hyperdx_status: 'no_data',
threshold_max: '',
value: '',
tags: '',
});
});
});
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/tasks/checkAlerts/transports/generic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,15 @@ export const buildWebhookTemplateVariables = (message: Message) =>
note: escapeJsonString(message.note ?? ''),
sourceQuery: escapeJsonString(message.sourceQuery ?? ''),
status: escapeJsonString(message.status ?? ''),
// An array so `{{tags}}` renders comma-joined and `{{#each tags}}` works.
tags: (message.tags ?? []).map(escapeJsonString),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 minor — Comma-joined {{tags}} is ambiguous because tags can contain commas

alertTagsSchema/tagsSchema in packages/common-utils/src/types.ts:1076 only limits length (z.string().max(32)), so a single tag team-a,prod renders the same as the two tags team-a and prod. That matters for comma-split routing and for the default incident.io metadata.tags. Either reject commas in alert tags, or switch the default body to the {{#each}} JSON-array form and note in the docs and the form description that the joined form is lossy.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

teamId: escapeJsonString(message.teamId ?? ''),
threshold: message.threshold,
thresholdMax: message.thresholdMax,
value: message.value,
}) satisfies Record<
WebhookTemplateVariable,
string | number | undefined | Record<string, string>
string | number | undefined | string[] | Record<string, string>
>;

/**
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/tasks/checkAlerts/transports/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export interface Message {
sourceQuery?: string; // the search expr / SQL that defines the alert
teamId?: string;
note?: string; // freeform alert note (markdown); commonly holds a runbook link
tags?: string[];
}

export type WebhookChannel = Extract<
Expand Down
1 change: 1 addition & 0 deletions packages/app/src/components/TeamSettings/WebhookForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ const describeTemplateVariable = (
endTimeISO: 'Window end, ISO-8601',
teamId: 'Team the alert belongs to',
note: "Alert's note, commonly a runbook link",
tags: "Alert's tags, comma-separated; iterate with {{#each tags}}",
});

export const getWebhookTemplateVariables = (
Expand Down
4 changes: 3 additions & 1 deletion packages/common-utils/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,7 @@ export const WEBHOOK_TEMPLATE_VARIABLES = [
'sourceQuery',
'teamId',
'note',
'tags',
] as const;

export type WebhookTemplateVariable =
Expand Down Expand Up @@ -778,7 +779,8 @@ export const DEFAULT_INCIDENT_IO_WEBHOOK_BODY = `{
"value": "{{value}}",
"group_key": "{{groupKey}}",
"window_start": "{{startTimeISO}}",
"window_end": "{{endTimeISO}}"
"window_end": "{{endTimeISO}}",
"tags": "{{tags}}"
}
}`;

Expand Down
Loading