import { EventEmitter } from 'node:events'; import { Client } from 'pg'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Drizzle } from './drizzle/index.js'; import { createStreamer, LISTEN_RECONNECT_DELAY_MS, listenChannel, } from './streamer.js'; vi.mock('pg', () => ({ Client: vi.fn(function Client() { return { connect: vi.fn(async () => {}), query: vi.fn(async () => {}), on: vi.fn(), removeListener: vi.fn(), end: vi.fn(async () => {}), }; }), Pool: vi.fn(), })); const fakePool = { options: {}, query: vi.fn(async () => ({ rows: [] })), } as any; /** * Minimal fake for the drizzle query chain used by `streams.get()`: * `drizzle.select(...).from(...).where(...).orderBy(...)`. */ function createFakeDrizzle( rows: () => Promise> ): Drizzle { return { select: () => ({ from: () => ({ where: () => ({ orderBy: () => rows(), limit: () => rows(), }), }), }), } as unknown as Drizzle; } describe('postgres streamer reader listener cleanup', () => { // `createStreamer()` keeps its EventEmitter private, so capture any // emitter that receives a `strm:*` listener via a prototype spy. let streamEmitters: Set; const listenerCount = (name: string) => { let count = 0; for (const emitter of streamEmitters) { count += emitter.listenerCount(`strm:${name}`); } return count; }; beforeEach(() => { streamEmitters = new Set(); const originalOn = EventEmitter.prototype.on; vi.spyOn(EventEmitter.prototype, 'on').mockImplementation(function ( this: EventEmitter, eventName, listener ) { if (typeof eventName === 'string' && eventName.startsWith('strm:')) { streamEmitters.add(this); } return originalOn.call(this, eventName, listener); }); }); afterEach(() => { vi.restoreAllMocks(); }); it('removes the listener when a persisted EOF closes the stream', async () => { const drizzle = createFakeDrizzle(async () => [ { id: 'chnk_00000000000000000000000001', eof: false, data: Buffer.from('hello'), }, { id: 'chnk_00000000000000000000000002', eof: true, data: Buffer.from([]), }, ]); const streamer = createStreamer(fakePool, drizzle); const warnings: Error[] = []; const onWarning = (warning: Error) => warnings.push(warning); process.on('warning', onWarning); try { // Repeated reads of the same completed stream must not accumulate // listeners (issue reproduction uses 12 readers to trip the default // max-listeners threshold of 10). for (let i = 0; i < 12; i++) { const stream = await streamer.streams.get('run_1', 'stream-eof'); const reader = stream.getReader(); let done = false; while (!done) { ({ done } = await reader.read()); } expect(listenerCount('stream-eof')).toBe(0); } // Warnings are emitted via process.nextTick; flush before asserting. await new Promise((resolve) => setImmediate(resolve)); expect( warnings.filter((w) => w.name === 'MaxListenersExceededWarning') ).toEqual([]); } finally { process.removeListener('warning', onWarning); await streamer.close(); } }); it('removes the listener when the initial chunk query rejects', async () => { const drizzle = createFakeDrizzle(async () => { throw new Error('initial query failed'); }); const streamer = createStreamer(fakePool, drizzle); try { for (let i = 0; i < 12; i++) { const stream = await streamer.streams.get('run_1', 'stream-err'); const reader = stream.getReader(); await expect(reader.read()).rejects.toThrow('initial query failed'); } expect(listenerCount('stream-err')).toBe(0); } finally { await streamer.close(); } }); it('removes the listener when a live EOF arrives via notification', async () => { // No persisted EOF: the reader tails live events and is closed by an // EOF chunk delivered through the LISTEN emitter. const drizzle = createFakeDrizzle(async () => [ { id: 'chnk_00000000000000000000000001', eof: false, data: Buffer.from('hello'), }, ]); const streamer = createStreamer(fakePool, drizzle); try { for (let i = 0; i < 12; i++) { const stream = await streamer.streams.get('run_1', 'stream-live-eof'); const reader = stream.getReader(); await reader.read(); expect(listenerCount('stream-live-eof')).toBe(1); for (const emitter of streamEmitters) { emitter.emit('strm:stream-live-eof', { id: 'chnk_00000000000000000000000002', eof: true, data: Buffer.from([]), }); } expect(await reader.read()).toEqual({ done: true, value: undefined }); expect(listenerCount('stream-live-eof')).toBe(0); } } finally { await streamer.close(); } }); it('detaches and fails pending readers when the streamer is closed', async () => { // No EOF chunk: readers stay open, tailing live events. const drizzle = createFakeDrizzle(async () => [ { id: 'chnk_00000000000000000000000001', eof: false, data: Buffer.from('hello'), }, ]); const streamer = createStreamer(fakePool, drizzle); const readers: ReadableStreamDefaultReader[] = []; for (let i = 0; i < 10; i++) { const stream = await streamer.streams.get('run_1', 'stream-open'); readers.push(stream.getReader()); // Consume the persisted chunk; the reader keeps waiting for more. await readers[i].read(); } expect(listenerCount('stream-open')).toBe(10); // An outstanding read() must settle once the streamer shuts down: the // LISTEN client is gone, so nothing could ever wake it otherwise. const pending = readers[0].read(); await streamer.close(); expect(listenerCount('stream-open')).toBe(0); await expect(pending).rejects.toThrow('streamer has been closed'); for (const reader of readers) { await expect(reader.read()).rejects.toThrow('streamer has been closed'); } }); it('rejects streams.get() after the streamer is closed', async () => { const drizzle = createFakeDrizzle(async () => []); const streamer = createStreamer(fakePool, drizzle); await streamer.close(); await expect( streamer.streams.get('run_1', 'stream-after-close') ).rejects.toThrow('streamer has been closed'); // A rejected get() must not leave a listener behind on the dead emitter. expect(listenerCount('stream-after-close')).toBe(0); }); it('cleans up when cancelled while the initial query is in flight', async () => { let resolveQuery!: ( rows: Array<{ id: string; eof: boolean; data: Buffer }> ) => void; const drizzle = createFakeDrizzle( () => new Promise((resolve) => (resolveQuery = resolve)) ); const streamer = createStreamer(fakePool, drizzle); try { const stream = await streamer.streams.get('run_1', 'stream-cancel-early'); const reader = stream.getReader(); expect(listenerCount('stream-cancel-early')).toBe(1); await reader.cancel(); expect(listenerCount('stream-cancel-early')).toBe(0); // The query resolving into a cancelled stream is dropped; the listener // count must not bounce back. resolveQuery([ { id: 'chnk_00000000000000000000000001', eof: false, data: Buffer.from('hello'), }, { id: 'chnk_00000000000000000000000002', eof: true, data: Buffer.from([]), }, ]); await new Promise((resolve) => setImmediate(resolve)); expect(listenerCount('stream-cancel-early')).toBe(0); } finally { await streamer.close(); } }); it('does not count a redelivered skipped chunk against the start offset', async () => { const drizzle = createFakeDrizzle(async () => []); const streamer = createStreamer(fakePool, drizzle); try { // startIndex 2: skip 'first' and 'second', deliver from 'third'. const stream = await streamer.streams.get('run_1', 'stream-offset', 2); const reader = stream.getReader(); const first = { id: 'chnk_00000000000000000000000001', eof: false, data: Buffer.from('first'), }; const emit = (chunk: typeof first) => { for (const emitter of streamEmitters) { emitter.emit('strm:stream-offset', chunk); } }; // Let start() finish its (empty) initial query so notifications are // enqueued directly rather than buffered. await new Promise((resolve) => setImmediate(resolve)); emit(first); // A redelivered NOTIFY for the chunk that was just skipped must not // decrement the remaining offset a second time. emit(first); emit({ id: 'chnk_00000000000000000000000002', eof: false, data: Buffer.from('second'), }); emit({ id: 'chnk_00000000000000000000000003', eof: false, data: Buffer.from('third'), }); const result = await reader.read(); expect(result.done).toBe(false); expect(Buffer.from(result.value as Uint8Array).toString()).toBe('third'); } finally { await streamer.close(); } }); it('still cleans up on explicit consumer cancellation', async () => { const drizzle = createFakeDrizzle(async () => []); const streamer = createStreamer(fakePool, drizzle); try { const stream = await streamer.streams.get('run_1', 'stream-cancel'); const reader = stream.getReader(); expect(listenerCount('stream-cancel')).toBe(1); await reader.cancel(); expect(listenerCount('stream-cancel')).toBe(0); } finally { await streamer.close(); } }); }); describe('streams.get() rows written after the first EOF', () => { type Row = { id: string; eof: boolean; data: Buffer }; /** The one query the catch-up loop runs: select(...).from(...).where(...).orderBy(...). */ function fakeDrizzle(rows: Row[]): Drizzle { const chain = { from: () => chain, where: () => chain, orderBy: async () => rows, limit: async () => rows, }; return { select: () => chain } as unknown as Drizzle; } async function drain(stream: ReadableStream): Promise { const reader = stream.getReader(); const decoder = new TextDecoder(); let out = ''; for (;;) { const { done, value } = await reader.read(); if (done) break; out += decoder.decode(value, { stream: true }); } return out; } it('ignores rows written after the first EOF instead of erroring the stream', async () => { // Several data rows before the EOF, on purpose: the catch-up loop is // synchronous, so all but the first sit in the controller's queue when // the EOF closes it. A post-EOF `enqueue` then threw out of `start()`, // which errors the stream and drops that queue — with a single queued // chunk the consumer happens to drain it first and the bug hides. const rows: Row[] = ['a', 'b', 'c', 'd', 'e'].map((text, i) => ({ id: `chnk_0${i}`, eof: false, data: Buffer.from(`${text}\n`), })); rows.push( { id: 'chnk_10', eof: true, data: Buffer.alloc(0) }, // A retried terminal write: the frame appended again, the stream // closed again. { id: 'chnk_11', eof: false, data: Buffer.from('e\n') }, { id: 'chnk_12', eof: true, data: Buffer.alloc(0) } ); const streamer = createStreamer(fakePool, fakeDrizzle(rows)); try { const stream = await streamer.streams.get('run_1', 'stream-1', 0); await expect(drain(stream)).resolves.toBe('a\nb\nc\nd\ne\n'); } finally { await streamer.close(); } }); it.each([ 5, 6, ])('a start index at or past the data count (%i) closes at the first EOF instead of consuming it', async (startIndex) => { // Offsets count data chunks (`getInfo` reports tailIndex = dataCount - 1), // so the EOF marker must never be skipped as if it were data: before this // guard the marker was swallowed, the post-EOF duplicate came back as // live data, and with no later EOF the stream never closed. const rows: Row[] = ['a', 'b', 'c', 'd', 'e'].map((text, i) => ({ id: `chnk_0${i}`, eof: false, data: Buffer.from(`${text}\n`), })); rows.push( { id: 'chnk_10', eof: true, data: Buffer.alloc(0) }, { id: 'chnk_11', eof: false, data: Buffer.from('e\n') } ); const streamer = createStreamer(fakePool, fakeDrizzle(rows)); try { const stream = await streamer.streams.get( 'run_1', 'stream-1', startIndex ); await expect(drain(stream)).resolves.toBe(''); } finally { await streamer.close(); } }, 5_000); it.each([ [-1, 'e\n'], [-2, 'd\ne\n'], ])( 'a negative start index (%i) counts data chunks up to the first EOF only', async (startIndex, expected) => { // The negative offset used to resolve against every row, including the // ones after the first EOF, so `-1` on A…E + EOF + duplicate-E skipped // the last valid chunk and returned nothing. const rows: Row[] = ['a', 'b', 'c', 'd', 'e'].map((text, i) => ({ id: `chnk_0${i}`, eof: false, data: Buffer.from(`${text}\n`), })); rows.push( { id: 'chnk_10', eof: true, data: Buffer.alloc(0) }, { id: 'chnk_11', eof: false, data: Buffer.from('e\n') } ); const streamer = createStreamer(fakePool, fakeDrizzle(rows)); try { const stream = await streamer.streams.get( 'run_1', 'stream-1', startIndex ); await expect(drain(stream)).resolves.toBe(expected); } finally { await streamer.close(); } }, 5_000 ); }); describe('postgres streamer listenChannel credentials', () => { // The tests below replace the module-level `Client` mock; put it back so a // test added after them gets the default fake client. const defaultClient = vi.mocked(Client).getMockImplementation(); afterEach(() => { vi.mocked(Client).mockReset(); if (defaultClient) vi.mocked(Client).mockImplementation(defaultClient); vi.useRealTimers(); vi.restoreAllMocks(); }); it('retains non-enumerable password credentials on initial connect and reconnect', async () => { vi.useFakeTimers(); vi.spyOn(console, 'warn').mockImplementation(() => {}); const password = async () => 'dynamic-token-456'; const poolOptions = { host: 'localhost', user: 'postgres' }; Object.defineProperty(poolOptions, 'password', { value: password, writable: true, enumerable: false, configurable: true, }); const handlers: Record void> = {}; const fakeClient = { connect: vi.fn(async () => {}), query: vi.fn(async () => {}), on: vi.fn((event: string, handler: () => void) => { handlers[event] = handler; }), removeListener: vi.fn(), end: vi.fn(async () => {}), }; vi.mocked(Client) .mockReset() .mockImplementation( class { constructor() { // biome-ignore lint/correctness/noConstructorReturn: fake client instance return fakeClient as any; } } as any ); const pool = { options: poolOptions } as any; const sub = await listenChannel(pool, 'test_channel', async () => {}); expect(Client).toHaveBeenCalled(); const firstCallConfig = vi.mocked(Client).mock.calls[0][0] as any; expect(firstCallConfig.password).toBe(password); // Trigger disconnect to exercise reconnect handlers.error?.(); await vi.advanceTimersByTimeAsync(LISTEN_RECONNECT_DELAY_MS); expect(Client).toHaveBeenCalledTimes(2); const reconnectConfig = vi.mocked(Client).mock.calls[1][0] as any; expect(reconnectConfig.password).toBe(password); expect(reconnectConfig.connectionTimeoutMillis).toBe(10_000); await sub.close(); }); it('logs the code of a failed reconnect once per outage, never the error message', async () => { vi.useFakeTimers(); const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); const handlers: Record void> = {}; const authError = Object.assign( new Error('password authentication failed for user "postgres"'), { code: '28P01' } ); let failures = 3; const fakeClient = { connect: vi.fn(async () => { if (vi.mocked(Client).mock.calls.length > 1 && failures-- > 0) { throw authError; } }), query: vi.fn(async () => {}), on: vi.fn((event: string, handler: () => void) => { handlers[event] = handler; }), removeListener: vi.fn(), end: vi.fn(async () => {}), }; vi.mocked(Client) .mockReset() .mockImplementation( class { constructor() { // biome-ignore lint/correctness/noConstructorReturn: fake client instance return fakeClient as any; } } as any ); const onReconnect = vi.fn(); const sub = await listenChannel( { options: {} } as any, 'test_channel', async () => {}, { onReconnect } ); handlers.error?.(); for (let i = 0; i <= 3; i++) { await vi.advanceTimersByTimeAsync(LISTEN_RECONNECT_DELAY_MS); } expect(onReconnect).toHaveBeenCalledTimes(1); const lines = warn.mock.calls.map((call) => String(call[0])); expect(lines.filter((line) => line.includes('reconnect failed'))).toEqual([ '[world-postgres] LISTEN test_channel reconnect failed (28P01); retrying', ]); expect(lines.join('\n')).not.toContain('password authentication'); await sub.close(); }); });