295 lines
11 KiB
TypeScript
295 lines
11 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import { REALTIME_EVENT_NAMES, type NotificationStreamItem } from "./events.js";
|
|
import {
|
|
subscribeToRealtime,
|
|
type RealtimeEventSourceLike,
|
|
type RealtimeMessageEvent,
|
|
type RealtimeReconnectScheduler,
|
|
type RealtimeSubscriberDiagnostic,
|
|
type RealtimeSubscriberOptions,
|
|
} from "./client.js";
|
|
|
|
const item: NotificationStreamItem = {
|
|
id: "delivery_client_1",
|
|
cursor: "2026-05-08T20:00:00.000Z:delivery_client_1",
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
channel: "IN_APP",
|
|
category: "billing",
|
|
messageKey: "invoice.ready",
|
|
status: "SENT",
|
|
attemptsMade: 1,
|
|
createdAt: "2026-05-08T19:59:00.000Z",
|
|
updatedAt: "2026-05-08T20:00:00.000Z",
|
|
sentAt: "2026-05-08T20:00:00.000Z",
|
|
readAt: null,
|
|
deeplink: null,
|
|
lastError: null,
|
|
};
|
|
|
|
const baseEvent = {
|
|
cursor: item.cursor,
|
|
requestId: "req_client_1",
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
};
|
|
|
|
class FakeScheduler implements RealtimeReconnectScheduler {
|
|
private nextHandle = 1;
|
|
readonly timers = new Map<number, () => void>();
|
|
readonly delays: number[] = [];
|
|
readonly cleared: number[] = [];
|
|
|
|
setTimeout(callback: () => void, delayMs: number): number {
|
|
const handle = this.nextHandle;
|
|
this.nextHandle += 1;
|
|
this.timers.set(handle, callback);
|
|
this.delays.push(delayMs);
|
|
return handle;
|
|
}
|
|
|
|
clearTimeout(handle: unknown): void {
|
|
if (typeof handle === "number") {
|
|
this.cleared.push(handle);
|
|
this.timers.delete(handle);
|
|
}
|
|
}
|
|
|
|
runNext(): void {
|
|
const [handle, callback] = [...this.timers.entries()][0] ?? [];
|
|
|
|
if (handle === undefined || callback === undefined) {
|
|
throw new Error("No pending reconnect timer.");
|
|
}
|
|
|
|
this.timers.delete(handle);
|
|
callback();
|
|
}
|
|
}
|
|
|
|
class FakeEventSource implements RealtimeEventSourceLike {
|
|
static instances: FakeEventSource[] = [];
|
|
|
|
readonly listeners = new Map<string, Array<(event: RealtimeMessageEvent) => void>>();
|
|
onopen: (() => void) | null = null;
|
|
onmessage: ((event: RealtimeMessageEvent) => void) | null = null;
|
|
onerror: ((event: unknown) => void) | null = null;
|
|
closed = false;
|
|
|
|
constructor(readonly url: string | URL) {
|
|
FakeEventSource.instances.push(this);
|
|
}
|
|
|
|
open(): void {
|
|
this.onopen?.();
|
|
}
|
|
|
|
emit(data: unknown): void {
|
|
this.onmessage?.({ data: typeof data === "string" ? data : JSON.stringify(data) });
|
|
}
|
|
|
|
emitNamed(type: string, data: unknown): void {
|
|
const message = { data: typeof data === "string" ? data : JSON.stringify(data), type };
|
|
for (const listener of this.listeners.get(type) ?? []) {
|
|
listener(message);
|
|
}
|
|
}
|
|
|
|
addEventListener(type: string, listener: (event: RealtimeMessageEvent) => void): void {
|
|
const listeners = this.listeners.get(type) ?? [];
|
|
listeners.push(listener);
|
|
this.listeners.set(type, listeners);
|
|
}
|
|
|
|
fail(): void {
|
|
this.onerror?.({});
|
|
}
|
|
|
|
close(): void {
|
|
this.closed = true;
|
|
}
|
|
}
|
|
|
|
function createSubscriber(overrides: Partial<RealtimeSubscriberOptions> = {}) {
|
|
FakeEventSource.instances = [];
|
|
const diagnostics: RealtimeSubscriberDiagnostic[] = [];
|
|
const statuses: string[] = [];
|
|
const subscriber = subscribeToRealtime({
|
|
...overrides,
|
|
url: overrides.url ?? "https://example.test/stream",
|
|
EventSource: overrides.EventSource ?? FakeEventSource,
|
|
onDiagnostic: (diagnostic) => diagnostics.push(diagnostic),
|
|
onStatus: (status) => statuses.push(status),
|
|
});
|
|
const source = FakeEventSource.instances[0];
|
|
|
|
return { diagnostics, source, statuses, subscriber };
|
|
}
|
|
|
|
function createScheduledSubscriber(options: Partial<RealtimeSubscriberOptions> = {}) {
|
|
const scheduler = new FakeScheduler();
|
|
const result = createSubscriber({
|
|
...options,
|
|
reconnect: { baseDelayMs: 100, maxDelayMs: 250, maxRetries: 3, ...options.reconnect, scheduler },
|
|
});
|
|
|
|
return { ...result, scheduler };
|
|
}
|
|
|
|
describe("realtime client subscriber", () => {
|
|
it("creates one EventSource instance and dispatches typed realtime events", () => {
|
|
const onSnapshot = vi.fn();
|
|
const onUpdate = vi.fn();
|
|
const onKeepalive = vi.fn();
|
|
const onError = vi.fn();
|
|
const { diagnostics, source, statuses } = createSubscriber({ onSnapshot, onUpdate, onKeepalive, onError });
|
|
|
|
source.open();
|
|
source.emitNamed(REALTIME_EVENT_NAMES.notificationSnapshot, { ...baseEvent, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: [item] });
|
|
source.emitNamed(REALTIME_EVENT_NAMES.notificationUpdate, { ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
|
|
source.emitNamed(REALTIME_EVENT_NAMES.keepalive, { ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
|
|
source.emitNamed(REALTIME_EVENT_NAMES.error, { ...baseEvent, event: REALTIME_EVENT_NAMES.error, code: "STREAM_FAILED", message: "Notification stream failed." });
|
|
|
|
expect(FakeEventSource.instances).toHaveLength(1);
|
|
expect([...source.listeners.keys()]).toEqual([
|
|
REALTIME_EVENT_NAMES.notificationSnapshot,
|
|
REALTIME_EVENT_NAMES.notificationUpdate,
|
|
REALTIME_EVENT_NAMES.keepalive,
|
|
REALTIME_EVENT_NAMES.error,
|
|
]);
|
|
expect(statuses).toEqual(["connecting", "open"]);
|
|
expect(onSnapshot).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: [item] });
|
|
expect(onUpdate).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
|
|
expect(onKeepalive).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
|
|
expect(onError).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.error, code: "STREAM_FAILED", message: "Notification stream failed." });
|
|
expect(diagnostics).toEqual([]);
|
|
});
|
|
|
|
it("reports malformed JSON and validation failures with redacted diagnostics", () => {
|
|
const { diagnostics, source } = createSubscriber();
|
|
|
|
source.emit("{not-json");
|
|
source.emit({ ...baseEvent, event: "notification.unknown", authorizationHeader: "Bearer secret-token" });
|
|
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item: { ...item, providerPayload: "super-secret-token" } });
|
|
|
|
expect(diagnostics).toEqual([
|
|
{ phase: "parse", message: expect.stringContaining("[redacted]") },
|
|
{
|
|
phase: "validation",
|
|
message: "event must be a supported realtime event name",
|
|
eventName: "notification.unknown",
|
|
cursor: item.cursor,
|
|
requestId: "req_client_1",
|
|
},
|
|
{
|
|
phase: "validation",
|
|
message: "notification item contains secret-like key: [redacted]",
|
|
eventName: REALTIME_EVENT_NAMES.notificationUpdate,
|
|
cursor: item.cursor,
|
|
requestId: "req_client_1",
|
|
},
|
|
]);
|
|
expect(JSON.stringify(diagnostics)).not.toMatch(/secret-token|super-secret-token|Bearer/i);
|
|
});
|
|
|
|
it("reports EventSource and callback exceptions without exposing stack traces", () => {
|
|
const onUpdate = vi.fn(() => {
|
|
throw new Error("callback leaked token=abc123");
|
|
});
|
|
const { diagnostics, source } = createSubscriber({ reconnect: { enabled: false }, onUpdate });
|
|
|
|
source.fail();
|
|
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
|
|
|
|
expect(diagnostics).toEqual([
|
|
{ phase: "eventsource", message: "EventSource reported an error." },
|
|
{
|
|
phase: "callback",
|
|
message: "callback leaked token=abc123",
|
|
eventName: REALTIME_EVENT_NAMES.notificationUpdate,
|
|
cursor: item.cursor,
|
|
requestId: "req_client_1",
|
|
},
|
|
]);
|
|
expect(JSON.stringify(diagnostics)).not.toContain("Error:");
|
|
});
|
|
|
|
it("closes explicitly once and ignores later messages or duplicate close calls", () => {
|
|
const onKeepalive = vi.fn();
|
|
const { source, statuses, subscriber } = createSubscriber({ onKeepalive });
|
|
|
|
subscriber.close();
|
|
subscriber.close();
|
|
source.open();
|
|
source.fail();
|
|
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
|
|
|
|
expect(source.closed).toBe(true);
|
|
expect(statuses).toEqual(["connecting", "closed"]);
|
|
expect(onKeepalive).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("schedules deterministic capped reconnects and replaces failed sources", () => {
|
|
const { diagnostics, scheduler, source, statuses } = createScheduledSubscriber();
|
|
|
|
source.fail();
|
|
|
|
expect(source.closed).toBe(true);
|
|
expect(scheduler.delays).toEqual([100]);
|
|
expect(scheduler.timers.size).toBe(1);
|
|
expect(FakeEventSource.instances).toHaveLength(1);
|
|
expect(statuses).toEqual(["connecting", "reconnecting"]);
|
|
expect(diagnostics).toContainEqual({ phase: "reconnect", message: "Realtime reconnect scheduled.", retryAttempt: 1, delayMs: 100 });
|
|
|
|
scheduler.runNext();
|
|
const retrySource = FakeEventSource.instances[1];
|
|
|
|
expect(FakeEventSource.instances).toHaveLength(2);
|
|
expect(retrySource.closed).toBe(false);
|
|
expect(statuses).toEqual(["connecting", "reconnecting", "connecting"]);
|
|
});
|
|
|
|
it("stops reconnecting after maxRetries is reached", () => {
|
|
const { diagnostics, scheduler, source, statuses } = createScheduledSubscriber({ reconnect: { baseDelayMs: 50, maxDelayMs: 75, maxRetries: 2 } });
|
|
|
|
source.fail();
|
|
scheduler.runNext();
|
|
FakeEventSource.instances[1].fail();
|
|
scheduler.runNext();
|
|
FakeEventSource.instances[2].fail();
|
|
|
|
expect(FakeEventSource.instances).toHaveLength(3);
|
|
expect(scheduler.delays).toEqual([50, 75]);
|
|
expect(scheduler.timers.size).toBe(0);
|
|
expect(diagnostics).toContainEqual({ phase: "reconnect", message: "Realtime reconnect retry limit reached.", retryAttempt: 2 });
|
|
expect(statuses.at(-1)).toBe("closed");
|
|
});
|
|
|
|
it("resets retry attempts after a successful open", () => {
|
|
const { diagnostics, scheduler, source } = createScheduledSubscriber({ reconnect: { baseDelayMs: 100, maxDelayMs: 1_000, maxRetries: 3 } });
|
|
|
|
source.fail();
|
|
scheduler.runNext();
|
|
FakeEventSource.instances[1].open();
|
|
FakeEventSource.instances[1].fail();
|
|
|
|
expect(scheduler.delays).toEqual([100, 100]);
|
|
expect(diagnostics).toContainEqual({ phase: "reconnect", message: "Realtime reconnect scheduled.", retryAttempt: 1, delayMs: 100 });
|
|
});
|
|
|
|
it("cancels pending reconnects and prevents future sources after explicit close", () => {
|
|
const { scheduler, source, statuses, subscriber } = createScheduledSubscriber();
|
|
|
|
source.fail();
|
|
subscriber.close();
|
|
|
|
expect(source.closed).toBe(true);
|
|
expect(scheduler.timers.size).toBe(0);
|
|
expect(scheduler.cleared).toEqual([1]);
|
|
expect(statuses).toEqual(["connecting", "reconnecting", "closed"]);
|
|
expect(() => scheduler.runNext()).toThrow("No pending reconnect timer.");
|
|
expect(FakeEventSource.instances).toHaveLength(1);
|
|
});
|
|
});
|