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
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { EventDrivenWsServer, MockRedisPubSubAdapter } from '../eventDrivenWsServer';
import type { RedisPubSubAdapter } from '../redisPubSubAdapter';
import type { AuthUser } from '../../shared/authStrategies';

class SharedPubSub implements RedisPubSubAdapter {
private static handlers = new Map<string, Set<(channel: string, message: string) => void>>();
static reset(): void { SharedPubSub.handlers.clear(); }
async publish(channel: string, message: string): Promise<void> {
for (const handler of SharedPubSub.handlers.get(channel) ?? []) handler(channel, message);
}
async subscribe(channel: string, handler: (channel: string, message: string) => void): Promise<void> {
const handlers = SharedPubSub.handlers.get(channel) ?? new Set();
handlers.add(handler);
SharedPubSub.handlers.set(channel, handlers);
}
async close(): Promise<void> { SharedPubSub.handlers.clear(); }
}

const event = {
type: 'subscription.created' as const,
subscriptionId: 'sub-1',
userId: 'user-1',
payload: { plan: 'pro' },
timestamp: 1,
};

function connection(clientId: string, send: jest.Mock): Parameters<EventDrivenWsServer['registerConnection']>[0] {
return {
clientId,
user: { id: 'user-1' } as AuthUser,
lastPing: Date.now(),
isAlive: true,
filter: { userId: 'user-1' },
send,
close: jest.fn(),
};
}

describe('EventDrivenWsServer Redis Pub/Sub integration', () => {
afterEach(() => SharedPubSub.reset());

it('delivers an event published by one server to connections on another server', async () => {
const publisher = new EventDrivenWsServer(new SharedPubSub());
const receiver = new EventDrivenWsServer(new SharedPubSub());
const send = jest.fn();
await Promise.all([publisher.ready, receiver.ready]);
receiver.registerConnection(connection('client-2', send));

const published = await publisher.publishEvent(event);

expect(send).toHaveBeenCalledWith(expect.objectContaining({
type: event.type,
subscriptionId: event.subscriptionId,
sequenceId: published.sequenceId,
}));
await Promise.all([publisher.shutdown(), receiver.shutdown()]);
});

it('does not deliver events that fail the local connection filter', async () => {
const server = new EventDrivenWsServer(new SharedPubSub());
const send = jest.fn();
await server.ready;
server.registerConnection({
...connection('client-3', send),
filter: { userId: 'different-user' },
});

await server.publishEvent(event);

expect(send).not.toHaveBeenCalled();
await server.shutdown();
});

it('keeps the in-memory adapter available for local development', async () => {
const server = new EventDrivenWsServer(new MockRedisPubSubAdapter());
await server.ready;
expect(server.activeConnectionsCount).toBe(0);
await server.shutdown();
});
});
102 changes: 102 additions & 0 deletions backend/services/notification/__tests__/redisPubSubAdapter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { IORedisPubSubAdapter, RedisPubSubClient } from '../redisPubSubAdapter';

class FakeRedisClient implements RedisPubSubClient {
readonly listeners = new Set<(channel: string, message: string) => void>();
readonly published: Array<{ channel: string; message: string }> = [];
readonly subscriptions: string[] = [];
readonly unsubscriptions: string[] = [];
quitCalls = 0;

async ping(): Promise<string> { return 'PONG'; }
async publish(channel: string, message: string): Promise<number> {
this.published.push({ channel, message });
return 1;
}
async subscribe(channel: string): Promise<number> {
this.subscriptions.push(channel);
return 1;
}
async unsubscribe(channel: string): Promise<number> {
this.unsubscriptions.push(channel);
return 1;
}
on(_event: 'message', listener: (channel: string, message: string) => void): this {
this.listeners.add(listener);
return this;
}
removeListener(_event: 'message', listener: (channel: string, message: string) => void): this {
this.listeners.delete(listener);
return this;
}
async quit(): Promise<string> {
this.quitCalls++;
return 'OK';
}
emitMessage(channel: string, message: string): void {
for (const listener of this.listeners) listener(channel, message);
}
}

describe('IORedisPubSubAdapter', () => {
it('publishes through the publisher connection', async () => {
const publisher = new FakeRedisClient();
const subscriber = new FakeRedisClient();
const adapter = new IORedisPubSubAdapter(publisher, subscriber);

await adapter.publish('events', '{"id":1}');

expect(publisher.published).toEqual([{ channel: 'events', message: '{"id":1}' }]);
expect(subscriber.published).toHaveLength(0);
await adapter.close();
});

it('subscribes once per channel and dispatches messages to local handlers', async () => {
const publisher = new FakeRedisClient();
const subscriber = new FakeRedisClient();
const adapter = new IORedisPubSubAdapter(publisher, subscriber);
const first = jest.fn();
const second = jest.fn();

await adapter.subscribe('events', first);
await adapter.subscribe('events', second);
subscriber.emitMessage('events', 'hello');

expect(subscriber.subscriptions).toEqual(['events']);
expect(first).toHaveBeenCalledWith('events', 'hello');
expect(second).toHaveBeenCalledWith('events', 'hello');
await adapter.close();
});

it('isolates a throwing handler from other handlers', async () => {
const publisher = new FakeRedisClient();
const subscriber = new FakeRedisClient();
const adapter = new IORedisPubSubAdapter(publisher, subscriber);
const next = jest.fn();

await adapter.subscribe('events', () => { throw new Error('handler failure'); });
await adapter.subscribe('events', next);
subscriber.emitMessage('events', 'hello');

expect(next).toHaveBeenCalledWith('events', 'hello');
await adapter.close();
});

it('closes both connections and rejects operations after close', async () => {
const publisher = new FakeRedisClient();
const subscriber = new FakeRedisClient();
const adapter = new IORedisPubSubAdapter(publisher, subscriber);
await adapter.subscribe('events', jest.fn());

await adapter.close();

expect(publisher.quitCalls).toBe(1);
expect(subscriber.quitCalls).toBe(1);
expect(subscriber.unsubscriptions).toEqual(['events']);
await expect(adapter.publish('events', 'message')).rejects.toThrow('closed');
});

it('rejects using the same connection for publishing and subscribing', () => {
const client = new FakeRedisClient();
expect(() => new IORedisPubSubAdapter(client, client)).toThrow('separate');
});
});
72 changes: 37 additions & 35 deletions backend/services/notification/eventDrivenWsServer.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import { EventEmitter } from 'events';
import { SubscriptionEvent, EventFilter, ClientInfo } from './websocket';
import { AuthUser } from '../shared/authStrategies';
import { SubscriptionEvent, EventFilter } from './websocket';
import type { AuthUser } from '../shared/authStrategies';
import type { RedisPubSubAdapter as PubSubAdapter } from './redisPubSubAdapter';
export type { RedisPubSubAdapter } from './redisPubSubAdapter';

export interface StoredEvent extends SubscriptionEvent {
sequenceId: number;
}

export interface RedisPubSubAdapter {
publish(channel: string, message: string): Promise<void>;
subscribe(channel: string, handler: (channel: string, message: string) => void): Promise<void>;
}

export class MockRedisPubSubAdapter implements RedisPubSubAdapter {
/** In-memory adapter for unit tests and single-process development. */
export class MockRedisPubSubAdapter implements PubSubAdapter {
private handlers: Map<string, ((channel: string, message: string) => void)[]> = new Map();

async publish(channel: string, message: string): Promise<void> {
const list = this.handlers.get(channel) || [];
for (const handler of list) {
handler(channel, message);
}
for (const handler of list) handler(channel, message);
}

async subscribe(channel: string, handler: (channel: string, message: string) => void): Promise<void> {
Expand All @@ -43,47 +39,48 @@ export class EventDrivenWsServer extends EventEmitter {
private eventStore: StoredEvent[] = [];
private sequenceCounter = 0;
private heartbeatInterval?: NodeJS.Timeout;
private pubSub: RedisPubSubAdapter;
private readonly pubSub: PubSubAdapter;
readonly ready: Promise<void>;

constructor(pubSubAdapter?: RedisPubSubAdapter) {
constructor(pubSubAdapter?: PubSubAdapter) {
super();
this.pubSub = pubSubAdapter || new MockRedisPubSubAdapter();
this.setupPubSub();
this.ready = this.setupPubSub();
}

private async setupPubSub() {
private async setupPubSub(): Promise<void> {
await this.pubSub.subscribe('subtrackr_ws_events', (_channel, message) => {
try {
const event: StoredEvent = JSON.parse(message);
this.dispatchToLocalConnections(event);
} catch (e) {
// Parse error ignore
} catch (error) {
this.emit('invalidMessage', error);
}
});
}

startHeartbeat(intervalMs = 30000) {
startHeartbeat(intervalMs = 30000): void {
this.stopHeartbeat();
this.heartbeatInterval = setInterval(() => {
const now = Date.now();
for (const [clientId, conn] of this.connections) {
if (!conn.isAlive) {
conn.close(4001, 'Heartbeat timeout');
this.connections.delete(clientId);
this.emit('presence', { type: 'leave', clientId, userId: conn.user.id });
this.removeConnection(clientId);
} else {
conn.isAlive = false;
}
}
}, intervalMs);
}

stopHeartbeat() {
stopHeartbeat(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = undefined;
}
}

handlePong(clientId: string) {
handlePong(clientId: string): void {
const conn = this.connections.get(clientId);
if (conn) {
conn.isAlive = true;
Expand All @@ -105,23 +102,22 @@ export class EventDrivenWsServer extends EventEmitter {
}

async publishEvent(rawEvent: SubscriptionEvent): Promise<StoredEvent> {
await this.ready;
this.sequenceCounter++;
const storedEvent: StoredEvent = {
...rawEvent,
sequenceId: this.sequenceCounter,
};
this.eventStore.push(storedEvent);
if (this.eventStore.length > 10000) {
this.eventStore.shift(); // Keep buffer bounded
}
if (this.eventStore.length > 10000) this.eventStore.shift();

await this.pubSub.publish('subtrackr_ws_events', JSON.stringify(storedEvent));
return storedEvent;
}

private dispatchToLocalConnections(event: StoredEvent) {
private dispatchToLocalConnections(event: StoredEvent): void {
let delivered = 0;
for (const [_, conn] of this.connections) {
for (const conn of this.connections.values()) {
if (this.matchesFilter(event, conn.filter, conn.user.id)) {
conn.send(event);
delivered++;
Expand All @@ -135,21 +131,27 @@ export class EventDrivenWsServer extends EventEmitter {
if (!conn) return [];

const missedEvents = this.eventStore.filter(
(e) => e.sequenceId > lastSequenceId && this.matchesFilter(e, conn.filter, conn.user.id)
(event) => event.sequenceId > lastSequenceId &&
this.matchesFilter(event, conn.filter, conn.user.id),
);
for (const event of missedEvents) conn.send(event);
return missedEvents;
}

for (const event of missedEvents) {
conn.send(event);
async shutdown(): Promise<void> {
this.stopHeartbeat();
for (const clientId of [...this.connections.keys()]) this.removeConnection(clientId);
try {
await this.ready;
} finally {
await this.pubSub.close?.();
}

return missedEvents;
}

private matchesFilter(event: SubscriptionEvent, filter: EventFilter, userId: string): boolean {
if (filter.userId && filter.userId !== userId) return false;
if (filter.types?.length && !filter.types.includes(event.type)) return false;
if (filter.subscriptionIds?.length && !filter.subscriptionIds.includes(event.subscriptionId))
return false;
if (filter.subscriptionIds?.length && !filter.subscriptionIds.includes(event.subscriptionId)) return false;
return true;
}

Expand Down
Loading