Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

fix(site): debounce alert saves per alert so enabling two alerts quickly keeps both (#2781)

Karanvir Khannac98608030405
diff --git a/internal/site/src/components/alerts/alerts-sheet.tsx b/internal/site/src/components/alerts/alerts-sheet.tsx
index d97d061fa..72505a901 100644
--- a/internal/site/src/components/alerts/alerts-sheet.tsx
+++ b/internal/site/src/components/alerts/alerts-sheet.tsx
@@ -17,7 +17,7 @@ import { toast } from "@/components/ui/use-toast"
import { alertInfo } from "@/lib/alerts"
import { pb } from "@/lib/api"
import { $alerts, $systems } from "@/lib/stores"
-import { cn, debounce } from "@/lib/utils"
+import { cn, debounceByKey } from "@/lib/utils"
import type { AlertInfo, AlertRecord, AlertUnit, SystemRecord } from "@/types"
const Slider = lazy(() => import("@/components/ui/slider"))
@@ -58,14 +58,16 @@ const failedUpdateToast = (error: unknown) => {
})
}
-/** Create or update alerts for a given name and systems */
-const upsertAlerts = debounce(
+/** Create or update alerts for a given name and systems (debounced per alert name) */
+const upsertAlerts = debounceByKey(
async ({ name, value, min, systems }: { name: string; value: number; min: number; systems: string[] }) => {
try {
await pb.send<{ success: boolean }>(endpoint, {
method: "POST",
// overwrite is always true because we've done filtering client side
body: { name, value, min, systems, overwrite: true },
+ // scope auto-cancellation per alert so a request for one alert doesn't abort another's
+ requestKey: `POST:${name}`,
})
} catch (error) {
failedUpdateToast(error)
@@ -74,12 +76,13 @@ const upsertAlerts = debounce(
alertDebounce
)
-/** Delete alerts for a given name and systems */
-const deleteAlerts = debounce(async ({ name, systems }: { name: string; systems: string[] }) => {
+/** Delete alerts for a given name and systems (debounced per alert name) */
+const deleteAlerts = debounceByKey(async ({ name, systems }: { name: string; systems: string[] }) => {
try {
await pb.send<{ success: boolean }>(endpoint, {
method: "DELETE",
body: { name, systems },
+ requestKey: `DELETE:${name}`,
})
} catch (error) {
failedUpdateToast(error)
@@ -302,7 +305,7 @@ export function AlertContent({
function sendUpsert(min: number, value: number, valueFactor = factor) {
const systems = getSystemIds()
systems.length &&
- upsertAlerts({
+ upsertAlerts(alertKey, {
name: alertKey,
value: Number((value * valueFactor).toFixed(6)),
min,
@@ -336,7 +339,7 @@ export function AlertContent({
sendUpsert(min, value)
} else {
// if unchecked, delete alert (unless global and overwriteExisting is false)
- deleteAlerts({ name: alertKey, systems: getSystemIds() })
+ deleteAlerts(alertKey, { name: alertKey, systems: getSystemIds() })
// when force deleting all alerts of a type, also remove them from initialAlertsState
if (overwriteExisting) {
for (const curAlerts of Object.values(initialAlertsState)) {
diff --git a/internal/site/src/lib/utils.ts b/internal/site/src/lib/utils.ts
index 86d9433ad..00f8e8782 100644
--- a/internal/site/src/lib/utils.ts
+++ b/internal/site/src/lib/utils.ts
@@ -444,6 +444,25 @@ export function debounce<T extends (...args: any[]) => any>(func: T, wait: numbe
}
}
+/** Debounce separately per key, so a pending call for one key is never replaced by a call for another */
+// biome-ignore lint/suspicious/noExplicitAny: any is used to allow any function to be passed in
+export function debounceByKey<T extends (...args: any[]) => any>(
+ func: T,
+ wait: number
+): (key: string, ...args: Parameters<T>) => void {
+ const timeouts = new Map<string, ReturnType<typeof setTimeout>>()
+ return (key: string, ...args: Parameters<T>) => {
+ clearTimeout(timeouts.get(key))
+ timeouts.set(
+ key,
+ setTimeout(() => {
+ timeouts.delete(key)
+ func(...args)
+ }, wait)
+ )
+ }
+}
+
// Cache for runOnce
// biome-ignore lint/complexity/noBannedTypes: Function is used to allow any function to be passed in
const runOnceCache = new WeakMap<Function, { done: boolean; result: unknown }>()
diff --git a/internal/site/tests/utils.test.ts b/internal/site/tests/utils.test.ts
index 0533c964f..f901d9943 100644
--- a/internal/site/tests/utils.test.ts
+++ b/internal/site/tests/utils.test.ts
@@ -5,7 +5,7 @@ mock.module("@lingui/core/macro", () => ({
plural: (count: number, forms: any) => forms.other ?? "",
}))
-const { formatMicroseconds } = await import("../src/lib/utils")
+const { debounceByKey, formatMicroseconds } = await import("../src/lib/utils")
describe("formatMicroseconds", () => {
test("formats with fixedDigits = true (default)", () => {
@@ -63,3 +63,25 @@ describe("formatMicroseconds", () => {
expect(formatMicroseconds(Number.NEGATIVE_INFINITY)).toBe("-")
})
})
+
+describe("debounceByKey", () => {
+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms))
+
+ test("calls for different keys within the wait are all delivered", async () => {
+ const calls: string[] = []
+ const send = debounceByKey((name: string) => calls.push(name), 20)
+ send("CPU", "CPU")
+ send("Memory", "Memory")
+ await wait(60)
+ expect(calls).toEqual(["CPU", "Memory"])
+ })
+
+ test("repeated calls for the same key keep only the last", async () => {
+ const calls: number[] = []
+ const send = debounceByKey((value: number) => calls.push(value), 20)
+ send("CPU", 80)
+ send("CPU", 90)
+ await wait(60)
+ expect(calls).toEqual([90])
+ })
+})