Files
OmniRoute/src/lib/gamification/notifications.ts
anhtahaylove 67618978b0 fix(gamification): close the badge SSE stream when the signal is already aborted (#13106)
Correct: an `abort` listener registered on an already-aborted signal never fires, and `safeEnqueue` can't save it because enqueuing into an unread stream only buffers. The abort-later test earning its keep as a guard on the healthy path is the right instinct.


I reformatted the changelog fragment to the `changelog.d` convention (`- **fix(scope):** …`) before merging — `check:changelog-integrity` rejects a fragment that does not start with a markdown bullet, which is the same gate your #13158 was about. Wording is yours, unchanged in substance.

---

Validated in one consolidated worktree cut from `release/v3.8.51`, boarded together with the other 13 PRs of this batch — zero merge conflicts between them.

- `typecheck:core` clean
- complexity 2799 / baseline 3218 and cognitive-complexity 1265 / baseline 1437 — both under baseline
- 71 focused assertions green across the 13 test files this batch adds or touches

⚠️ base-red inherited: #12732 — `Docs Gates (fast-path)`, `Merge integrity`, `No new ESLint warnings`, `Unit Tests fast-path` and `Fast Quality Gates` all reproduce on the pure `release/v3.8.51` tip (provider count 356 vs the 358 the modules define, SKILL.md drift, and `open-sse/utils/stream.ts` at 3115 > frozen 3098). None of them touch this diff.

Thanks @anhtahaylove — the root-cause write-up, the measured before/after numbers and the red-before-green proof on every one of these made the batch reviewable as a unit.
2026-09-11 13:30:27 -03:00

126 lines
3.5 KiB
TypeScript

/**
* Badge unlock notification system.
* Emits events that the dashboard can listen to for toast notifications.
*
* @module lib/gamification/notifications
*/
export interface BadgeUnlockEvent {
badgeId: string;
badgeName: string;
badgeDescription: string;
badgeIcon: string;
badgeRarity: string;
unlockedAt: string;
}
// In-memory event buffer for SSE streaming
const recentUnlocks: Map<string, { event: BadgeUnlockEvent; addedAt: number }[]> = new Map();
const MAX_BUFFER_SIZE = 50;
const BUFFER_TTL_MS = 60_000; // 1 minute
const STALE_KEY_TTL_MS = 120_000; // 2 minutes for stale key cleanup
/**
* Record a badge unlock event for notification.
* Also cleans stale entries across all keys to prevent memory leaks.
*/
export function recordBadgeUnlock(apiKeyId: string, event: BadgeUnlockEvent): void {
if (!recentUnlocks.has(apiKeyId)) {
recentUnlocks.set(apiKeyId, []);
}
const list = recentUnlocks.get(apiKeyId)!;
list.push({ event, addedAt: Date.now() });
// Trim old entries for this key
const cutoff = Date.now() - BUFFER_TTL_MS;
while (list.length > 0 && list[0].addedAt < cutoff) {
list.shift();
}
if (list.length > MAX_BUFFER_SIZE) {
list.splice(0, list.length - MAX_BUFFER_SIZE);
}
// Periodic stale key cleanup (on each record, check all keys)
const staleCutoff = Date.now() - STALE_KEY_TTL_MS;
for (const [key, entries] of recentUnlocks) {
// Remove old entries
const fresh = entries.filter((e) => e.addedAt >= staleCutoff);
if (fresh.length === 0) {
recentUnlocks.delete(key);
} else if (fresh.length !== entries.length) {
recentUnlocks.set(key, fresh);
}
}
}
/**
* Get and clear recent badge unlocks for an API key.
*/
export function consumeBadgeUnlocks(apiKeyId: string): BadgeUnlockEvent[] {
const entries = recentUnlocks.get(apiKeyId) || [];
recentUnlocks.delete(apiKeyId);
return entries.map((e) => e.event);
}
/**
* Create a ReadableStream for badge unlock notifications via SSE.
*/
export function createBadgeNotificationStream(
apiKeyId: string,
signal?: AbortSignal
): ReadableStream {
return new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
let closed = false;
const safeEnqueue = (chunk: Uint8Array) => {
if (closed) return;
try {
controller.enqueue(chunk);
} catch {
closed = true;
clearInterval(interval);
clearInterval(heartbeat);
}
};
// Check for unlocks every 2s
const interval = setInterval(() => {
const events = consumeBadgeUnlocks(apiKeyId);
for (const event of events) {
safeEnqueue(encoder.encode(`event: badge_unlock\ndata: ${JSON.stringify(event)}\n\n`));
}
}, 2000);
// Heartbeat every 15s
const heartbeat = setInterval(() => {
safeEnqueue(encoder.encode(`: heartbeat ${Date.now()}\n\n`));
}, 15_000);
// Cleanup on abort
const cleanup = () => {
closed = true;
clearInterval(interval);
clearInterval(heartbeat);
try {
controller.close();
} catch {
/* already closed */
}
};
// A client that disconnects while the route is still awaiting auth
// arrives here already aborted, and "abort" will never fire again --
// the timers above would then run for the lifetime of the process.
if (signal?.aborted) {
cleanup();
return;
}
if (signal) {
signal.addEventListener("abort", cleanup);
}
},
});
}