Skip to content

Commit 3a4ae2a

Browse files
charlieparkbenjaminleonardhawkwfakemonsterdavid-crespo
authored
Add webhooks to the UI (#3320)
This PR adds the Alerting sidebar and the two tabs that nest under it, Alerts and Receivers. It also then shows the list of Receivers, all of which are Webhook Receivers for the present and near-term future. The webhook receiver creation form uses a richer input for the alert subscriptions that Ben created in #3326. There's an Alerts list that @fakemonster is working on separately. <img width="1458" height="824" alt="alerting - receivers" src="https://github.com/user-attachments/assets/5bb29096-486c-4c2c-ab57-2f17bb5b9bef" /> <img width="1450" height="813" alt="alerting - receiver-new-1" src="https://github.com/user-attachments/assets/afe7a087-30e7-49e8-9db2-fdf169f5a272" /> <img width="1460" height="827" alt="alerting - receiver-new-2" src="https://github.com/user-attachments/assets/03472d41-2dc4-4fdc-961a-b437e38738a3" /> <img width="1457" height="820" alt="alerting - alerts" src="https://github.com/user-attachments/assets/1babdd91-428d-49dd-898c-fed7ee7b2179" /> --------- Co-authored-by: benjaminleonard <[email protected]> Co-authored-by: Eliza Weisman <[email protected]> Co-authored-by: Joe Thel <[email protected]> Co-authored-by: David Crespo <[email protected]>
1 parent 4d1215e commit 3a4ae2a

48 files changed

Lines changed: 4915 additions & 236 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎app/api/__tests__/safety.spec.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@ it('mock-api is only referenced in test files', () => {
6868
[
6969
"AGENTS.md",
7070
"app/api/__tests__/client.browser.spec.ts",
71+
"app/components/form/fields/SubscriptionsField.browser.spec.tsx",
7172
"mock-api/msw/db.ts",
73+
"test/e2e/alerts.e2e.ts",
7274
"test/e2e/fleet-access.e2e.ts",
7375
"test/e2e/instance-create.e2e.ts",
7476
"test/e2e/inventory.e2e.ts",

‎app/api/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ export * from './client'
1414
export * from './roles'
1515
export * from './util'
1616
export * from './__generated__/Api'
17+
export { snakeify } from './__generated__/util'
1718
// export * as ZVal from './__generated__/validate'
1819

1920
export type { ApiTypes }

‎app/api/selectors.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export type SshKey = Readonly<{ sshKey: string }>
3333
export type Sled = Readonly<{ sledId?: string }>
3434
export type IpPool = Readonly<{ pool?: string }>
3535
export type SubnetPool = Readonly<{ subnetPool?: string }>
36+
export type AlertReceiver = Readonly<{ receiver?: string }>
3637
export type ExternalSubnet = Readonly<Merge<Project, { externalSubnet?: string }>>
3738
export type FloatingIp = Readonly<Merge<Project, { floatingIp?: string }>>
3839

‎app/api/util.spec.ts‎

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,70 @@
77
*/
88
import { describe, expect, it, test } from 'vitest'
99

10-
import { diskCan, genName, instanceCan, parsePortRange, synthesizeData } from './util'
10+
import {
11+
diskCan,
12+
genName,
13+
instanceCan,
14+
parsePortRange,
15+
resendableAlertIds,
16+
subscriptionRegex,
17+
synthesizeData,
18+
} from './util'
19+
20+
describe('subscriptionRegex', () => {
21+
it('matches exact class names', () => {
22+
expect(subscriptionRegex('instance.create').test('instance.create')).toBe(true)
23+
expect(subscriptionRegex('instance.create').test('instance.created')).toBe(false)
24+
})
25+
26+
it('* matches exactly one segment', () => {
27+
const re = subscriptionRegex('disk.*')
28+
expect(re.test('disk.create')).toBe(true)
29+
expect(re.test('disk.snapshot.create')).toBe(false)
30+
expect(re.test('disk')).toBe(false)
31+
})
32+
33+
it('* can appear at the head', () => {
34+
const re = subscriptionRegex('*.create')
35+
expect(re.test('disk.create')).toBe(true)
36+
expect(re.test('instance.create')).toBe(true)
37+
expect(re.test('instance.ephemeral_ip.create')).toBe(false)
38+
})
39+
40+
it('* can appear mid-string', () => {
41+
const re = subscriptionRegex('hardware.*.insert')
42+
expect(re.test('hardware.sled.insert')).toBe(true)
43+
expect(re.test('hardware.power_shelf.psu.insert')).toBe(false)
44+
expect(re.test('hardware.insert')).toBe(false)
45+
})
46+
47+
it('** matches one or more segments', () => {
48+
const re = subscriptionRegex('hardware.**')
49+
expect(re.test('hardware.power_shelf.psu.insert')).toBe(true)
50+
expect(re.test('hardware.psu')).toBe(true)
51+
expect(re.test('hardware')).toBe(false)
52+
53+
const suffix = subscriptionRegex('**.delete')
54+
expect(suffix.test('project.delete')).toBe(true)
55+
expect(suffix.test('instance.ephemeral_ip.delete')).toBe(true)
56+
expect(suffix.test('delete')).toBe(false)
57+
58+
const infix = subscriptionRegex('hardware.**.insert')
59+
expect(infix.test('hardware.sled.insert')).toBe(true)
60+
expect(infix.test('hardware.power_shelf.psu.insert')).toBe(true)
61+
expect(infix.test('hardware.insert')).toBe(false)
62+
})
63+
64+
it('does not match substrings within a segment', () => {
65+
expect(subscriptionRegex('instance.**').test('silo.instance_quota.hit')).toBe(false)
66+
expect(subscriptionRegex('disk.*').test('bigdisk.create')).toBe(false)
67+
})
68+
69+
it('does not match leading/trailing segments without a star pattern', () => {
70+
expect(subscriptionRegex('instance.**').test('silo.instance.hit')).toBe(false)
71+
expect(subscriptionRegex('**.power_shelf').test('hardware.power_shelf.psu')).toBe(false)
72+
})
73+
})
1174

1275
describe('parsePortRange', () => {
1376
describe('parses', () => {
@@ -197,3 +260,76 @@ test('diskCan', () => {
197260
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
198261
diskCan.abc
199262
})
263+
264+
describe('resendableAlertIds', () => {
265+
// the rule only reads these four fields, so build them directly
266+
type Delivery = Parameters<typeof resendableAlertIds>[0][number]
267+
268+
const d = (
269+
alertId: string,
270+
state: Delivery['state'],
271+
trigger: Delivery['trigger'],
272+
alertClass = 'hardware.sled.fault'
273+
): Delivery => ({ alertId, state, trigger, alertClass })
274+
275+
const ids = (deliveries: Delivery[]) => [...resendableAlertIds(deliveries)].sort()
276+
277+
it('is empty when there are no deliveries', () => {
278+
expect(ids([])).toEqual([])
279+
})
280+
281+
it('includes an alert whose only delivery failed', () => {
282+
expect(ids([d('a', 'failed', 'alert')])).toEqual(['a'])
283+
})
284+
285+
it('excludes delivered and pending alerts', () => {
286+
expect(ids([d('a', 'delivered', 'alert'), d('b', 'pending', 'alert')])).toEqual([])
287+
})
288+
289+
// the bug this rule replaced: it counted failed delivery records, so an
290+
// alert that had already been resent successfully was requeued forever
291+
it('excludes an alert that has a failed record but also a successful resend', () => {
292+
const deliveries = [d('a', 'failed', 'alert'), d('a', 'delivered', 'resend')]
293+
expect(ids(deliveries)).toEqual([])
294+
})
295+
296+
// a resend in flight takes the alert out of the set, so a second probe does
297+
// not double-queue it
298+
it('excludes an alert with a resend still pending', () => {
299+
const deliveries = [d('a', 'failed', 'alert'), d('a', 'pending', 'resend')]
300+
expect(ids(deliveries)).toEqual([])
301+
})
302+
303+
it('counts an alert once no matter how many times it failed', () => {
304+
const deliveries = [d('a', 'failed', 'alert'), d('a', 'failed', 'resend')]
305+
expect(ids(deliveries)).toEqual(['a'])
306+
})
307+
308+
it('ignores probe deliveries entirely', () => {
309+
const deliveries = [
310+
d('probe-alert', 'delivered', 'probe', 'probe'),
311+
d('probe-alert', 'failed', 'probe', 'probe'),
312+
d('a', 'failed', 'alert'),
313+
]
314+
expect(ids(deliveries)).toEqual(['a'])
315+
})
316+
317+
// a successful probe of an alert does not mean the alert itself landed, so it
318+
// must not settle the alert. matches omicron's triggered_by != probe filter
319+
it('does not let a probe-triggered success settle a real alert', () => {
320+
const deliveries = [d('a', 'failed', 'alert'), d('a', 'delivered', 'probe')]
321+
expect(ids(deliveries)).toEqual(['a'])
322+
})
323+
324+
it('handles several alerts at once', () => {
325+
const deliveries = [
326+
d('w', 'failed', 'alert'),
327+
d('x', 'delivered', 'alert'),
328+
d('y', 'failed', 'alert'),
329+
d('y', 'failed', 'resend'),
330+
d('z', 'failed', 'alert'),
331+
d('z', 'pending', 'resend'),
332+
]
333+
expect(ids(deliveries)).toEqual(['w', 'y'])
334+
})
335+
})

‎app/api/util.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { match } from 'ts-pattern'
1212
import { bytesToGiB } from '~/util/units'
1313

1414
import type {
15+
AlertDelivery,
1516
Disk,
1617
DiskState,
1718
DiskType,
@@ -40,6 +41,69 @@ export const INSTANCE_MAX_CPU = 254
4041
export const INSTANCE_MIN_RAM_GiB = 1
4142
export const INSTANCE_MAX_RAM_GiB = 1536
4243

44+
// Webhook endpoint URL column width. The API does no length validation, so a
45+
// longer URL fails with a database error rather than a 400.
46+
// https://github.com/oxidecomputer/omicron/blob/6db4c7e/schema/crdb/dbinit.sql#L7192
47+
export const WEBHOOK_ENDPOINT_MAX_LENGTH = 512
48+
49+
// Valid alert subscription: an alert class or a glob pattern matching multiple
50+
// classes. https://github.com/oxidecomputer/omicron/blob/32615a35/nexus/types/versions/src/initial/alert.rs#L22-L23
51+
export const ALERT_SUBSCRIPTION_REGEX =
52+
/^([a-zA-Z0-9_]+|\*|\*\*)(\.([a-zA-Z0-9_]+|\*|\*\*))*$/
53+
54+
/** A subscription with a `*` or `**` segment, as opposed to an exact class */
55+
export const isGlobPattern = (subscription: string) => subscription.includes('*')
56+
57+
/**
58+
* The `probe` class is synthetic: it exists for webhook receiver liveness
59+
* probes only.
60+
* The API lists it in `alertClassList` but rejects exact subscriptions to it
61+
* with a 400, so keep it out of anything the user can pick. Globs are exempt
62+
* because the API returns from its glob branch before reaching this check.
63+
* https://github.com/oxidecomputer/omicron/blob/6db4c7e/nexus/db-model/src/alert_subscription.rs#L91-L98
64+
*/
65+
export const PROBE_ALERT_CLASS = 'probe'
66+
67+
/** Alert classes a receiver can actually subscribe to */
68+
export const isSubscribableClass = (c: { name: string }) => c.name !== PROBE_ALERT_CLASS
69+
70+
/**
71+
* Convert an alert subscription to a regex matching the class names it covers:
72+
* a `*` segment matches exactly one segment, `**` matches one or more.
73+
* https://github.com/oxidecomputer/omicron/blob/32615a35/nexus/db-model/src/alert_subscription.rs
74+
*/
75+
export function subscriptionRegex(subscription: string) {
76+
const pattern = subscription
77+
.split('.')
78+
.map((seg) => (seg === '**' ? '.+' : seg === '*' ? '[^.]+' : seg))
79+
.join('\\.')
80+
return new RegExp(`^${pattern}$`)
81+
}
82+
83+
/**
84+
* IDs of the alerts a probe with `resend=true` would requeue: the receiver has
85+
* a delivery for the alert and no non-probe delivery of that alert has left the
86+
* failed state. Note this is per alert, not per delivery — delivery records are
87+
* immutable history, so a failed one stays failed forever and a resend inserts
88+
* a new record. The API has no endpoint for this, so we derive it from the
89+
* delivery list to preview the count before the user commits to a resend.
90+
* https://github.com/oxidecomputer/omicron/blob/6db4c7e/nexus/db-queries/src/db/datastore/webhook_delivery.rs#L205-L240
91+
*
92+
* The mock backend applies the same rule in its own `resendableAlerts`, which
93+
* works on snake_case records, so the two have to be changed together.
94+
*/
95+
export function resendableAlertIds(
96+
deliveries: Pick<AlertDelivery, 'alertId' | 'alertClass' | 'state' | 'trigger'>[]
97+
): Set<string> {
98+
const relevant = deliveries.filter((d) => d.alertClass !== PROBE_ALERT_CLASS)
99+
const settled = new Set(
100+
relevant
101+
.filter((d) => d.trigger !== 'probe' && d.state !== 'failed')
102+
.map((d) => d.alertId)
103+
)
104+
return new Set(relevant.filter((d) => !settled.has(d.alertId)).map((d) => d.alertId))
105+
}
106+
43107
export const MIN_DISK_SIZE_GiB = 1
44108
/**
45109
* Disk size limited to 1023 as that's the maximum we can safely allocate right now

‎app/components/AlertClassBadge.tsx‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
9+
import { useRef, useState } from 'react'
10+
11+
import { Badge } from '@oxide/design-system/ui'
12+
13+
import { Tooltip } from '~/ui/lib/Tooltip'
14+
15+
/**
16+
* Badge for an alert class or subscription glob. Badges uppercase their text
17+
* by default, but alert classes are lowercase in the API and someone who copies
18+
* one out of the UI needs it to work as a subscription, so keep the case.
19+
*
20+
* Long classes truncate to fit their container, with the full name in a
21+
* tooltip when that happens.
22+
*/
23+
export const AlertClassBadge = ({ children }: { children: string }) => {
24+
const ref = useRef<HTMLSpanElement>(null)
25+
const [truncated, setTruncated] = useState(false)
26+
27+
// Checked lazily on hover, like `Truncate`, so there's no per-badge
28+
// ResizeObserver and the answer can't go stale between resize and hover
29+
const checkTruncation = () => {
30+
const el = ref.current
31+
if (el) setTruncated(el.scrollWidth > el.clientWidth)
32+
}
33+
34+
return (
35+
// Badge doesn't forward refs or event handlers, so the tooltip anchors to a
36+
// wrapper and the overflow check lives on our own span inside the badge
37+
<Tooltip content={truncated ? children : undefined} delay={300}>
38+
<span className="inline-flex max-w-full min-w-0">
39+
<Badge color="neutral" className="max-w-full min-w-0 normal-case! *:min-w-0">
40+
<span ref={ref} className="block truncate" onPointerEnter={checkTruncation}>
41+
{children}
42+
</span>
43+
</Badge>
44+
</span>
45+
</Tooltip>
46+
)
47+
}

‎app/components/AlertPayload.tsx‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* This Source Code Form is subject to the terms of the Mozilla Public
3+
* License, v. 2.0. If a copy of the MPL was not distributed with this
4+
* file, you can obtain one at https://mozilla.org/MPL/2.0/.
5+
*
6+
* Copyright Oxide Computer Company
7+
*/
8+
import { useMemo } from 'react'
9+
10+
import { snakeify } from '@oxide/api'
11+
12+
import { HighlightJSON } from '~/components/HighlightJSON'
13+
import { CopyToClipboard } from '~/ui/lib/CopyToClipboard'
14+
15+
/**
16+
* Highlighted, copyable view of an alert's payload for side modals. Keys
17+
* are snake_case to match the alert as the API and the webhook payload present
18+
* it.
19+
*/
20+
export function AlertPayload({ payload }: { payload: Record<string, unknown> }) {
21+
// recomputing on every render would hand HighlightJSON a new object each
22+
// time and defeat its memo
23+
const snakeJson = useMemo(() => snakeify(payload), [payload])
24+
const stringified = useMemo(() => JSON.stringify(snakeJson, null, 2), [snakeJson])
25+
return (
26+
<div className="space-y-2">
27+
{/* labeled like a properties table row rather than a section heading,
28+
since this is one field of the alert shown alongside the others */}
29+
<div className="flex items-center justify-between">
30+
<span className="text-mono-sm text-secondary uppercase">Payload</span>
31+
<CopyToClipboard text={stringified} ariaLabel="Copy alert payload" />
32+
</div>
33+
<div className="bg-raise border-secondary overflow-x-auto rounded border px-3 py-2">
34+
<pre className="text-mono-code [font-size:13px]! [line-height:18px]!">
35+
<HighlightJSON json={snakeJson} />
36+
</pre>
37+
</div>
38+
</div>
39+
)
40+
}

0 commit comments

Comments
 (0)