forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotification-delivery.test.ts
More file actions
255 lines (212 loc) · 10.7 KB
/
Copy pathnotification-delivery.test.ts
File metadata and controls
255 lines (212 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// src/lib/__tests__/notification-delivery.test.ts
//
// Tests for the notification delivery circuit breaker in deliver.ts.
// Covers: circuit state transitions, cooldown expiry, rate limiting,
// Retry-After parsing (including NaN guard), error sanitization,
// and successful delivery reset.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type { DiscordEmbed } from "@/lib/notifications/payload"
vi.mock("@/lib/logger", () => ({
log: { warn: vi.fn(), error: vi.fn(), info: vi.fn() },
}))
// Use vi.mock with importOriginal so the real function still runs, but the
// export is wrappable by a spy. A full module replacement was removed here
// because it prevented the real sanitization logic from executing.
vi.mock("@/lib/error-utils", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/error-utils")>()
return { ...actual }
})
const TARGET_ID = 42
const WEBHOOK_URL = "https://discord.com/api/webhooks/123/abc"
const EMBEDS: DiscordEmbed[] = [
{ title: "test", description: "test description", color: 0, timestamp: new Date().toISOString() },
]
function mockFetchOk() {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, status: 200, statusText: "OK" }))
}
function mockFetchError(status: number, statusText: string, headers?: Record<string, string>) {
const headerMap = new Map(Object.entries(headers ?? {}))
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: false,
status,
statusText,
headers: { get: (k: string) => headerMap.get(k) ?? null },
})
)
}
function mockFetchThrow(message: string) {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error(message)))
}
describe("notification delivery circuit breaker", () => {
let deliverDiscordWebhook: typeof import("@/lib/notifications/deliver").deliverDiscordWebhook
let getCircuitState: typeof import("@/lib/notifications/deliver").getCircuitState
let resetCircuitBreaker: typeof import("@/lib/notifications/deliver").resetCircuitBreaker
beforeEach(async () => {
vi.resetModules()
// Clear globalThis circuit breaker state
const g = globalThis as typeof globalThis & { __notificationCircuits?: unknown }
delete g.__notificationCircuits
const mod = await import("@/lib/notifications/deliver")
deliverDiscordWebhook = mod.deliverDiscordWebhook
getCircuitState = mod.getCircuitState
resetCircuitBreaker = mod.resetCircuitBreaker
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
// ─── Successful delivery ─────────────────────────────────────────────
it("returns delivered on successful fetch", async () => {
mockFetchOk()
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(result).toEqual({ success: true, status: "delivered" })
})
it("resets circuit breaker after successful delivery", async () => {
// Record 2 failures first
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(getCircuitState(TARGET_ID).failures).toBe(2)
// Successful delivery resets
mockFetchOk()
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(getCircuitState(TARGET_ID).failures).toBe(0)
})
// ─── Failure tracking ────────────────────────────────────────────────
it("increments failure count on non-ok response", async () => {
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(getCircuitState(TARGET_ID).failures).toBe(1)
expect(getCircuitState(TARGET_ID).openUntil).toBeNull()
})
it("opens circuit after 3 consecutive failures", async () => {
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
const state = getCircuitState(TARGET_ID)
expect(state.failures).toBe(3)
expect(state.openUntil).toBeInstanceOf(Date)
expect(state.openUntil?.getTime()).toBeGreaterThan(Date.now())
})
it("returns failed with circuit breaker error when breaker is open", async () => {
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
// 4th attempt should be blocked
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(result.status).toBe("failed")
expect(result.error).toContain("Circuit breaker open")
expect(result.success).toBe(false)
// fetch should NOT have been called for the 4th attempt
expect(vi.mocked(fetch)).toHaveBeenCalledTimes(3)
})
it("auto-resets circuit after cooldown expires", async () => {
vi.useFakeTimers()
vi.setSystemTime(new Date("2025-01-01T00:00:00Z"))
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
// Advance past the 60s default cooldown so the circuit breaker expires
vi.advanceTimersByTime(61_000)
mockFetchOk()
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(result.status).toBe("delivered")
expect(getCircuitState(TARGET_ID).failures).toBe(0)
vi.useRealTimers()
})
// ─── Rate limiting (429) ─────────────────────────────────────────────
it("handles 429 with Retry-After header", async () => {
mockFetchError(429, "Too Many Requests", { "Retry-After": "10" })
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(result.status).toBe("rate_limited")
expect(result.error).toBe("Rate limited by Discord")
})
it("caps Retry-After at 5 minutes (300_000ms)", async () => {
mockFetchError(429, "Too Many Requests", { "Retry-After": "999" })
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
const state = getCircuitState(TARGET_ID)
const cooldownMs = (state.openUntil?.getTime() ?? 0) - Date.now()
// Should be capped at ~300_000ms, not 999_000ms
expect(cooldownMs).toBeLessThanOrEqual(300_100) // small tolerance
expect(cooldownMs).toBeGreaterThan(299_000)
})
it("falls back to 60s when Retry-After is NaN (date format)", async () => {
mockFetchError(429, "Too Many Requests", { "Retry-After": "Thu, 01 Jan 2026 00:00:00 GMT" })
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
const state = getCircuitState(TARGET_ID)
const cooldownMs = (state.openUntil?.getTime() ?? 0) - Date.now()
// Should fall back to 60_000ms, not NaN
expect(cooldownMs).toBeGreaterThan(59_000)
expect(cooldownMs).toBeLessThanOrEqual(60_100)
})
it("defaults Retry-After to 60s when header is absent", async () => {
mockFetchError(429, "Too Many Requests")
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
const state = getCircuitState(TARGET_ID)
const cooldownMs = (state.openUntil?.getTime() ?? 0) - Date.now()
expect(cooldownMs).toBeGreaterThan(59_000)
expect(cooldownMs).toBeLessThanOrEqual(60_100)
})
// ─── Network errors ──────────────────────────────────────────────────
it("handles fetch throw (network error) as failure", async () => {
mockFetchThrow("connect ECONNREFUSED")
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(result.success).toBe(false)
expect(result.status).toBe("failed")
expect(getCircuitState(TARGET_ID).failures).toBe(1)
})
it("sanitizes error messages from fetch failures", async () => {
const errorUtils = await import("@/lib/error-utils")
vi.spyOn(errorUtils, "sanitizeNetworkError")
mockFetchThrow("connect ECONNREFUSED 192.168.1.100:443")
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(errorUtils.sanitizeNetworkError).toHaveBeenCalledWith(
"connect ECONNREFUSED 192.168.1.100:443",
"Delivery failed"
)
// Raw IP/port details must not leak through — sanitizeNetworkError maps ECONNREFUSED → "Connection refused"
expect(result.error).not.toBe("connect ECONNREFUSED 192.168.1.100:443")
expect(result.error).toBe("Connection refused")
})
it("sanitizes error messages from non-ok HTTP responses", async () => {
const errorUtils = await import("@/lib/error-utils")
vi.spyOn(errorUtils, "sanitizeNetworkError")
mockFetchError(403, "Forbidden")
const result = await deliverDiscordWebhook(TARGET_ID, WEBHOOK_URL, EMBEDS)
expect(errorUtils.sanitizeNetworkError).toHaveBeenCalledWith(
"Webhook API error: 403 Forbidden",
"Delivery failed"
)
// 403 Forbidden matches the 401|403|Unauthorized|Forbidden pattern → "Authentication failed"
expect(result.error).not.toBe("Webhook API error: 403 Forbidden")
expect(result.error).toBe("Authentication failed")
})
// ─── Isolation between targets ────────────────────────────────────────
it("tracks circuit state independently per target", async () => {
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(1, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(1, WEBHOOK_URL, EMBEDS)
expect(getCircuitState(1).failures).toBe(2)
expect(getCircuitState(2).failures).toBe(0)
})
it("resetCircuitBreaker clears state for one target only", async () => {
mockFetchError(500, "Internal Server Error")
await deliverDiscordWebhook(1, WEBHOOK_URL, EMBEDS)
await deliverDiscordWebhook(2, WEBHOOK_URL, EMBEDS)
resetCircuitBreaker(1)
expect(getCircuitState(1).failures).toBe(0)
expect(getCircuitState(2).failures).toBe(1)
})
})