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
21 changes: 21 additions & 0 deletions dashboard/e2e/integrations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ async function mockApi(page: Page, init: Partial<Backend> = {}): Promise<Backend
if (p === "/api/alerts") return at("member") ? json(r, { alerts: db.alerts, next: null }) : forbidden();
if (p === "/api/alert-notify" && method === "GET") return at("admin") ? json(r, { enabled: true, webhooks: { teams: { set: true, hint: TEAMS_HINT }, slack: { set: false, hint: "" } } }) : forbidden();
if (p === "/api/alert-notify" && method === "PUT") return at("admin") ? json(r, { ok: true }) : forbidden();
if (p === "/api/updates-notify" && method === "GET") return at("admin") ? json(r, { enabled: false, kinds: ["action", "update"], webhooks: { teams: { set: false, hint: "" }, slack: { set: false, hint: "" } } }) : forbidden();
if (p === "/api/updates-notify" && method === "PUT") return at("admin") ? json(r, { ok: true }) : forbidden();
if (p === "/api/notify/test") return at("admin") ? json(r, { ok: true }) : forbidden();
if (p === "/api/alert-budget" && method === "GET") return at("admin") ? json(r, { daily_tokens: 2_000_000, used_24h_tokens: 600_000, open_runs: 1, open_run_reserve_tokens: 50_000, max_runs_per_rule_per_day: 5 }) : forbidden();
if (p === "/api/alert-budget" && method === "PUT") return at("admin") ? json(r, { ok: true }) : forbidden();
Expand Down Expand Up @@ -656,6 +658,25 @@ test.describe("Where alerts post", () => {
await shot(page, "alerts-team-channel-both");
});

test("the alert channel takes alerts only unless ticked; updates and requests for a person have their own channel", async ({ page }) => {
const db = await mockApi(page);
await page.goto("/settings/alerts");
const kinds = page.getByTestId("team-channel-kinds");
await expect(kinds.getByRole("checkbox", { name: /Requests for a person/ })).not.toBeChecked();
await expect(kinds.getByRole("checkbox", { name: /Updates/ })).not.toBeChecked();
await kinds.getByRole("checkbox", { name: /Requests for a person/ }).check();
const updates = page.getByTestId("updates-channel-row");
await updates.getByRole("switch").click();
const picker = page.getByTestId("updates-channels");
await picker.getByRole("checkbox", { name: "Slack" }).check();
await picker.getByRole("textbox", { name: "Slack webhook address" }).fill(SLACK_HOOK);
const bar = page.getByRole("region", { name: "Save changes" });
await bar.getByRole("button", { name: "Save changes" }).click();
await expect(page.getByText("Alert settings saved")).toBeVisible();
expect(callsTo(db, "PUT", /\/api\/alert-notify$/).at(-1)!.body).toEqual({ enabled: true, kinds: ["alert", "action"] });
expect(callsTo(db, "PUT", /\/api\/updates-notify$/).at(-1)!.body).toEqual({ enabled: true, slack_webhook: { url: SLACK_HOOK } });
});

test("a route can post to its own Slack channel and test it", async ({ page }) => {
const db = await mockApi(page);
await page.goto("/settings/alerts");
Expand Down
4 changes: 4 additions & 0 deletions dashboard/e2e/settings-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ export async function mockApi(page: Page, init: Partial<Backend> = {}): Promise<
return at("admin") ? json(r, { enabled: true, webhooks: { teams: { set: true, hint: TEAMS_HINT }, slack: { set: false, hint: "" } } }) : json(r, { error: "Forbidden" }, 403);
}
if (p === "/api/alert-notify" && method === "PUT") return json(r, { ok: true });
if (p === "/api/updates-notify" && method === "GET") {
return at("admin") ? json(r, { enabled: false, kinds: ["action", "update"], webhooks: { teams: { set: false, hint: "" }, slack: { set: false, hint: "" } } }) : json(r, { error: "Forbidden" }, 403);
}
if (p === "/api/updates-notify" && method === "PUT") return json(r, { ok: true });
if (p === "/api/notify/test") return json(r, { ok: true });
if (p === "/api/alert-budget" && method === "GET") {
return at("admin") ? json(r, { daily_tokens: 2_000_000, used_24h_tokens: 600_000, open_runs: 1, open_run_reserve_tokens: 50_000, max_runs_per_rule_per_day: 5 }) : json(r, { error: "Forbidden" }, 403);
Expand Down
1 change: 1 addition & 0 deletions dashboard/e2e/settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ async function mockApi(page: Page, init: Partial<Backend> = {}): Promise<Backend
if (p === "/api/alert-routes") return atLeast(db.role, "member") ? json(route, { endpoint_path: "/webhooks/alerts/sns", routes: [] }) : forbidden(route);
if (p === "/api/alerts") return atLeast(db.role, "member") ? json(route, { alerts: [], next: null }) : forbidden(route);
if (p === "/api/alert-budget") return admin ? json(route, { daily_tokens: 2_000_000, used_24h_tokens: 0, open_runs: 0, open_run_reserve_tokens: 0, max_runs_per_rule_per_day: 3 }) : forbidden(route);
if (p === "/api/updates-notify") return admin ? json(route, { enabled: false, kinds: ["action", "update"], webhooks: { teams: { set: false, hint: "" }, slack: { set: false, hint: "" } } }) : forbidden(route);
if (p === "/api/alert-notify") return admin ? json(route, { enabled: false, webhooks: { teams: { set: false, hint: "" }, slack: { set: false, hint: "" } } }) : forbidden(route);
if (p === "/api/data-sources") return json(route, { sources: [] });
if (p === "/api/data-sources/activity") return json(route, { events: [] });
Expand Down
1 change: 1 addition & 0 deletions dashboard/e2e/wide-data/review.ts
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,7 @@ export const reviewData: Handler = ({ method, path, url }) => {
if (path === "/api/alert-routes") return ALERT_ROUTES;
if (path === "/api/alert-routes/alarms") return { alarms: [{ name: "production-payments-reconciliation-service-5xx-rate-above-threshold", state: "ALARM" }], messages: [] };
if (path === "/api/alert-budget") return { daily_tokens: 2_000_000, used_24h_tokens: 600_000, open_runs: 1, open_run_reserve_tokens: 50_000, max_runs_per_rule_per_day: 5 };
if (path === "/api/updates-notify") return { enabled: false, kinds: ["action", "update"], webhooks: { teams: { set: false, hint: "" }, slack: { set: false, hint: "" } } };
if (path === "/api/alert-notify") return { enabled: true, webhooks: { teams: { set: true, hint: "example.environment.api.powerplatform.com …ab12" }, slack: { set: false, hint: "" } } };

// Support
Expand Down
165 changes: 150 additions & 15 deletions dashboard/src/app/settings/alerts/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
type AlertBudget,
type AlertEvent,
type AlertNotifySettings,
type NotifyKind,
type AlertRepeat,
type AlertRoute,
type AlertRule,
Expand Down Expand Up @@ -670,7 +671,38 @@ function fmtTokens(n: number): string {
return String(n);
}

type AlertForm = { enabled: boolean; budget: string };
type AlertForm = {
enabled: boolean;
budget: string;
/** What the alert channel takes beyond alerts: "", "action", "update" or "action,update". */
alertExtra: string;
updatesEnabled: boolean;
};

const EXTRA_KINDS: { kind: NotifyKind; label: string; help: string }[] = [
{
kind: "action",
label: "Requests for a person",
help: "A merge conflict that needs a call, a sign-in to renew, a plugin to approve.",
},
{
kind: "update",
label: "Updates",
help: "Fix pull requests opened or merged, new log findings, security findings below critical.",
},
];

/** The alert channel's kinds beyond alerts, as the form keeps them. */
function extraOf(kinds?: NotifyKind[]): string {
return EXTRA_KINDS.filter((k) => kinds?.includes(k.kind))
.map((k) => k.kind)
.join(",");
}

/** The alert channel always takes alerts; the rest is the team's choice. */
function alertKinds(extra: string): NotifyKind[] {
return ["alert", ...(extra.split(",").filter(Boolean) as NotifyKind[])];
}

/** A budget typed as "2M" and saved as 2000000 are the same; text that isn't a number is a change. */
const sameAlertField = (a: unknown, b: unknown, key: keyof AlertForm) => {
Expand All @@ -681,20 +713,26 @@ const sameAlertField = (a: unknown, b: unknown, key: keyof AlertForm) => {
};

/**
* The team channel (Teams, Slack or both) and the daily token budget for
* alert runs: two settings rows saved by one bar. Each still saves through
* its own request, as before.
* The team's two channels (alerts, and updates with requests for a person)
* and the daily token budget for alert runs: settings rows saved by one bar.
* Each still saves through its own request.
*/
function AlertSettings() {
const { toast } = useToast();
const [notify, setNotify] = useState<AlertNotifySettings | null>(null);
const [notifyError, setNotifyError] = useState(false);
const [updates, setUpdates] = useState<AlertNotifySettings | null>(null);
const [updatesError, setUpdatesError] = useState(false);
const [budget, setBudget] = useState<AlertBudget | null>(null);
const [budgetError, setBudgetError] = useState(false);
const [draft, setDraft] = useState<ChannelsDraft>(draftFrom(NO_WEBHOOKS));
const [updatesDraft, setUpdatesDraft] = useState<ChannelsDraft>(draftFrom(NO_WEBHOOKS));
const [saving, setSaving] = useState(false);
const [problem, setProblem] = useState<string | null>(null);
const form = useDirtyForm<AlertForm>({ enabled: false, budget: "" }, { same: sameAlertField, disabled: !notify && !budget });
const form = useDirtyForm<AlertForm>(
{ enabled: false, budget: "", alertExtra: "", updatesEnabled: false },
{ same: sameAlertField, disabled: !notify && !budget && !updates },
);
const { reset } = form;

/** Re-reads the saved channels (they come back as hints, never as addresses). */
Expand All @@ -706,22 +744,35 @@ function AlertSettings() {
setDraft(draftFrom(s.webhooks));
})
.catch(() => {});
api
.getUpdatesNotify()
.then((s) => {
setUpdates(s);
setUpdatesDraft(draftFrom(s.webhooks));
})
.catch(() => {});
}, []);

useEffect(() => {
let live = true;
Promise.allSettled([api.getAlertNotify(), api.getAlertBudget()]).then(([n, b]) => {
Promise.allSettled([api.getAlertNotify(), api.getAlertBudget(), api.getUpdatesNotify()]).then(([n, b, u]) => {
if (!live) return;
const next: AlertForm = { enabled: false, budget: "" };
const next: AlertForm = { enabled: false, budget: "", alertExtra: "", updatesEnabled: false };
if (n.status === "fulfilled") {
setNotify(n.value);
setDraft(draftFrom(n.value.webhooks));
next.enabled = n.value.enabled;
next.alertExtra = extraOf(n.value.kinds);
} else setNotifyError(true);
if (b.status === "fulfilled") {
setBudget(b.value);
next.budget = fmtTokens(b.value.daily_tokens);
} else setBudgetError(true);
if (u.status === "fulfilled") {
setUpdates(u.value);
setUpdatesDraft(draftFrom(u.value.webhooks));
next.updatesEnabled = u.value.enabled;
} else setUpdatesError(true);
reset(next);
});
return () => {
Expand All @@ -730,19 +781,29 @@ function AlertSettings() {
}, [reset]);

const channelsDirty = !!notify && draftDirty(draft, notify.webhooks);
const notifyDirty = !!notify && (form.isDirty("enabled") || channelsDirty);
const kindsDirty = !!notify && form.isDirty("alertExtra");
const notifyDirty = !!notify && (form.isDirty("enabled") || channelsDirty || kindsDirty);
const updatesChannelsDirty = !!updates && draftDirty(updatesDraft, updates.webhooks);
const updatesDirty = !!updates && (form.isDirty("updatesEnabled") || updatesChannelsDirty);
const budgetDirty = !!budget && form.isDirty("budget");
const count = (notify && form.isDirty("enabled") ? 1 : 0) + (channelsDirty ? 1 : 0) + (budgetDirty ? 1 : 0);
const count =
(notify && form.isDirty("enabled") ? 1 : 0) +
(channelsDirty ? 1 : 0) +
(kindsDirty ? 1 : 0) +
(updates && form.isDirty("updatesEnabled") ? 1 : 0) +
(updatesChannelsDirty ? 1 : 0) +
(budgetDirty ? 1 : 0);
const n = parseTokens(form.values.budget);
const budgetValid = n !== null && n <= 100_000_000;
const channelsValid = draftValid(draft, notify?.webhooks, form.values.enabled);
const updatesValid = draftValid(updatesDraft, updates?.webhooks, form.values.updatesEnabled);

const save = async () => {
if (budgetDirty && !budgetValid) {
setProblem("Enter a daily budget such as 500k or 2M, up to 100M.");
return;
}
if (notifyDirty && !channelsValid) {
if ((notifyDirty && !channelsValid) || (updatesDirty && !updatesValid)) {
setProblem("Check the webhook addresses. A channel that is ticked needs a working address.");
return;
}
Expand All @@ -751,11 +812,25 @@ function AlertSettings() {
const failed: string[] = [];
if (notifyDirty && notify) {
try {
await api.saveAlertNotify({ enabled: form.values.enabled, ...channelsPayload(draft, notify.webhooks) });
await api.saveAlertNotify({
enabled: form.values.enabled,
...(kindsDirty ? { kinds: alertKinds(form.values.alertExtra) } : {}),
...channelsPayload(draft, notify.webhooks),
});
} catch {
failed.push("the team channel (check the webhook address)");
}
}
if (updatesDirty && updates) {
try {
await api.saveUpdatesNotify({
enabled: form.values.updatesEnabled,
...channelsPayload(updatesDraft, updates.webhooks),
});
} catch {
failed.push("the updates channel (check the webhook address)");
}
}
if (budgetDirty && n !== null) {
try {
await api.saveAlertBudget(n);
Expand All @@ -765,8 +840,12 @@ function AlertSettings() {
}
}
const edited = form.values;
const teamSaved = notifyDirty && !failed.some((f) => f.startsWith("the team"));
const updatesSaved = updatesDirty && !failed.some((f) => f.startsWith("the updates"));
const next: AlertForm = {
enabled: notifyDirty && !failed.some((f) => f.startsWith("the team")) ? edited.enabled : form.saved.enabled,
enabled: teamSaved ? edited.enabled : form.saved.enabled,
alertExtra: teamSaved ? edited.alertExtra : form.saved.alertExtra,
updatesEnabled: updatesSaved ? edited.updatesEnabled : form.saved.updatesEnabled,
budget: budgetDirty && !failed.includes("the budget") && n !== null ? fmtTokens(n) : form.saved.budget,
};
reset(next);
Expand All @@ -777,27 +856,34 @@ function AlertSettings() {
} else {
toast("Alert settings saved");
}
if (notifyDirty && !failed.some((f) => f.startsWith("the team"))) reloadChannels();
if (teamSaved || updatesSaved) reloadChannels();
setSaving(false);
};

const discard = () => {
form.discard();
if (notify) setDraft(draftFrom(notify.webhooks));
if (updates) setUpdatesDraft(draftFrom(updates.webhooks));
setProblem(null);
};

const extra = form.values.alertExtra.split(",").filter(Boolean);
const toggleExtra = (kind: NotifyKind, on: boolean) => {
const next = EXTRA_KINDS.map((k) => k.kind).filter((k) => (k === kind ? on : extra.includes(k)));
form.set("alertExtra", next.join(","));
};

const used = budget ? Math.min(100, (budget.used_24h_tokens / Math.max(budget.daily_tokens, 1)) * 100) : 0;

return (
<>
<SettingsSection id="alert-settings" title="Team channel and budget">
<SettingsSection id="alert-settings" title="Team channels and budget">
<SettingsRow
label="Post alerts to the team channel"
layout="toggle"
testId="team-channel-row"
unsaved={notifyDirty}
help="Routes set to the team channel post here: a red message when an alarm fires, a follow up with the pull request link, and green recoveries on routes that post them."
help="Only alerts post here: a red message when an alarm fires, a follow up with the pull request link, green recoveries on routes that post them, critical security findings. Pull request status, findings and requests for a person go to the updates channel below, unless you tick them here."
control={(ids) => (
<Switch
id={ids.inputId}
Expand All @@ -821,6 +907,55 @@ function AlertSettings() {
destination={{ destination: "alerts" }}
/>
)}
{notify && (
<fieldset className="mt-3" data-testid="team-channel-kinds">
<legend className="text-xs text-zinc-400">Also post here (off by default)</legend>
{EXTRA_KINDS.map((k) => (
<label key={k.kind} className="mt-1.5 flex items-start gap-2 text-sm text-zinc-200">
<input
type="checkbox"
className="mt-0.5"
checked={extra.includes(k.kind)}
onChange={(e) => toggleExtra(k.kind, e.target.checked)}
/>
<span>
{k.label}
<span className="block text-xs text-zinc-400">{k.help}</span>
</span>
</label>
))}
</fieldset>
)}
</SettingsRow>
<SettingsRow
label="Post updates and requests for a person"
layout="toggle"
testId="updates-channel-row"
unsaved={updatesDirty}
help="A separate channel for things that are not alerts: a merge conflict that needs a person's call, a sign-in to renew, fix pull requests opened or merged, new log findings. Waiting on a review is never posted: it shows on the pull request. Leave it off and these stay on the pull request, the run page and email."
control={(ids) => (
<Switch
id={ids.inputId}
checked={form.values.updatesEnabled}
onChange={(on) => form.set("updatesEnabled", on)}
labelledBy={ids.labelId}
describedBy={ids.helpId}
disabled={!updates}
/>
)}
>
{updatesError ? (
<Callout variant="error"><p>Could not load the updates channel. Reload the page to try again.</p></Callout>
) : (
<ChannelPicker
idPrefix="updates"
draft={updatesDraft}
saved={updates?.webhooks}
onChange={setUpdatesDraft}
disabled={!updates}
destination={{ destination: "updates" }}
/>
)}
</SettingsRow>
<SettingsRow
label="Daily token budget for alert runs"
Expand Down
Loading
Loading