diff --git a/backend/tests/redis-connection.test.ts b/backend/tests/redis-connection.test.ts new file mode 100644 index 00000000..b46f1578 --- /dev/null +++ b/backend/tests/redis-connection.test.ts @@ -0,0 +1,555 @@ +/** + * Issue #1749: Redis connect, reconnect policy, command failure and the + * unavailable-server fallback. + * + * The existing coverage stops at the in-memory cache (`tests/redis.test.ts`, + * `tests/memory-cache.test.ts`) and at the tracker's happy path + * (`tests/sentinel-service.test.ts`); everywhere else `src/lib/redis.js` is + * `vi.mock`-ed away. Nothing tested `connectRedis`, `disconnectRedis`, the + * reconnect schedule, or what the sliding-window tracker does when the + * dependency is missing or answers badly — which is the whole of how this + * service survives a Redis outage. + * + * Note on "command timeout" in the issue text: `makeClient` sets no + * per-command timeout. What bounds a command instead is + * `enableOfflineQueue: false` (a command issued while the link is down rejects + * immediately rather than sitting in a queue) together with + * `maxRetriesPerRequest: 3`. Both are asserted below as the real contract. + * + * Two behaviours found here are deliberately *not* pinned, because they look + * wrong rather than intended, and are reported in the pull request: + * - `connectRedis`'s catch calls `disconnect()` on module state it has + * assigned nothing to, so the client whose connect failed is never closed. + * A publisher that connected before its subscriber failed keeps its socket + * open while the app reports Redis unavailable. + * - `SlidingWindowTracker.add` documents `id` as the dedupe key, but the id + * is stored encoded together with the weight, so re-adding one id with a + * new weight keeps a second sample and `distinct()` counts it twice. + */ +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; + +interface FakeClient { + url: string; + options: Record; + connected: boolean; + connect: ReturnType; + quit: ReturnType; + disconnect: ReturnType; + zadd: ReturnType; + zremrangebyscore: ReturnType; + zrangebyscore: ReturnType; + zcount: ReturnType; + pexpire: ReturnType; + del: ReturnType; +} + +const state = vi.hoisted(() => ({ + failConnect: false, + instances: [] as unknown[], + commands: [] as string[], +})); + +vi.mock('ioredis', () => { + class FakeRedis { + url: string; + options: Record; + connected = false; + + constructor(url: string, options: Record) { + this.url = url; + this.options = options; + state.instances.push(this); + } + + private record(name: string): void { + state.commands.push(name); + } + + connect = vi.fn(async () => { + this.record('connect'); + if (state.failConnect) { + throw new Error('connect ECONNREFUSED 127.0.0.1:6379'); + } + this.connected = true; + }); + + quit = vi.fn(async () => { + this.record('quit'); + this.connected = false; + return 'OK'; + }); + + disconnect = vi.fn(() => { + this.record('disconnect'); + this.connected = false; + }); + + zadd = vi.fn(async () => { + this.record('zadd'); + return 1; + }); + + zremrangebyscore = vi.fn(async () => { + this.record('zremrangebyscore'); + return 0; + }); + + zrangebyscore = vi.fn(async () => { + this.record('zrangebyscore'); + return [] as string[]; + }); + + zcount = vi.fn(async () => { + this.record('zcount'); + return 0; + }); + + pexpire = vi.fn(async () => { + this.record('pexpire'); + return 1; + }); + + del = vi.fn(async () => { + this.record('del'); + return 1; + }); + } + + return { Redis: FakeRedis }; +}); + +type RedisModule = typeof import('../src/lib/redis.js'); + +const TEST_URL = 'redis://127.0.0.1:6379'; +const DAY_MS = 24 * 60 * 60 * 1_000; +const loaded: RedisModule[] = []; + +/** + * `REDIS_URL` is read once at module scope, so each scenario needs a fresh + * import with the environment set first. Every module loaded here owns a + * cleanup timer started at import, so they are all stopped afterwards. + */ +async function loadRedis(redisUrl?: string): Promise { + if (redisUrl === undefined) delete process.env.REDIS_URL; + else process.env.REDIS_URL = redisUrl; + vi.resetModules(); + const mod = (await import('../src/lib/redis.js')) as RedisModule; + loaded.push(mod); + return mod; +} + +/** + * The module returns `ioredis` types, which the mock replaces at runtime, so + * every handle has to be read back through the fake. Indexing loudly beats an + * `as` on `undefined` if a scenario constructs fewer clients than expected. + */ +function client(index: number): FakeClient { + const instance = state.instances[index]; + if (!instance) throw new Error(`no Redis client constructed at index ${index}`); + return instance as FakeClient; +} + +function publisherOf(redis: RedisModule): FakeClient { + return redis.getPublisher() as unknown as FakeClient; +} + +function subscriberOf(redis: RedisModule): FakeClient { + return redis.getSubscriber() as unknown as FakeClient; +} + +function trackerOf(redis: RedisModule): ReturnType { + return redis.getSlidingWindowTracker(); +} + +beforeEach(() => { + state.instances.length = 0; + state.commands.length = 0; + state.failConnect = false; +}); + +afterEach(() => { + for (const mod of loaded.splice(0)) { + mod.stopMemoryCacheSweep(); + } + delete process.env.REDIS_URL; + state.instances.length = 0; + state.commands.length = 0; + state.failConnect = false; +}); + +describe('boot without Redis configured', () => { + it('connects to nothing and reports itself single-instance', async () => { + const redis = await loadRedis(undefined); + + await expect(redis.connectRedis()).resolves.toBeUndefined(); + + expect(state.instances).toHaveLength(0); + expect(redis.isRedisAvailable()).toBe(false); + expect(redis.getPublisher()).toBeNull(); + expect(redis.getSubscriber()).toBeNull(); + expect(redis.getRedisClient()).toBeNull(); + }); + + it('treats an empty REDIS_URL as unset instead of dialling an empty host', async () => { + const redis = await loadRedis(''); + + await redis.connectRedis(); + + expect(state.instances).toHaveLength(0); + expect(redis.isRedisAvailable()).toBe(false); + }); + + it('tolerates a disconnect that was never connected', async () => { + const redis = await loadRedis(undefined); + + await expect(redis.disconnectRedis()).resolves.toBeUndefined(); + expect(state.instances).toHaveLength(0); + }); +}); + +describe('connect and reconnect', () => { + it('opens one publisher and one subscriber and only then advertises availability', async () => { + const redis = await loadRedis(TEST_URL); + + expect(redis.isRedisAvailable()).toBe(false); + + await redis.connectRedis(); + + const publisher = client(0); + const subscriber = client(1); + expect(state.instances).toHaveLength(2); + expect(publisher.url).toBe(TEST_URL); + expect(subscriber.url).toBe(TEST_URL); + // Separate connections: a client in subscriber mode cannot answer ordinary + // commands, so sharing one would break `publish` against `psubscribe`. + expect(publisher).not.toBe(subscriber); + expect(publisher.connected).toBe(true); + expect(subscriber.connected).toBe(true); + expect(publisher.connect).toHaveBeenCalledTimes(1); + expect(redis.isRedisAvailable()).toBe(true); + expect(publisherOf(redis)).toBe(publisher); + expect(subscriberOf(redis)).toBe(subscriber); + expect(redis.getRedisClient()).toBe(publisher); + }); + + it('falls back to single-instance mode when the server is unreachable', async () => { + state.failConnect = true; + const redis = await loadRedis(TEST_URL); + + // A Redis outage must not take the API down with it, so the failure is + // absorbed here rather than thrown at the boot caller. + await expect(redis.connectRedis()).resolves.toBeUndefined(); + + expect(redis.isRedisAvailable()).toBe(false); + expect(redis.getPublisher()).toBeNull(); + expect(redis.getSubscriber()).toBeNull(); + }); + + it('recovers horizontal mode when a retry succeeds after a failed connect', async () => { + state.failConnect = true; + const redis = await loadRedis(TEST_URL); + await redis.connectRedis(); + expect(redis.isRedisAvailable()).toBe(false); + + state.failConnect = false; + await redis.connectRedis(); + + expect(redis.isRedisAvailable()).toBe(true); + expect(publisherOf(redis)).toBe(client(2)); + expect(subscriberOf(redis)).toBe(client(3)); + }); + + it('quits both clients and reverts to single-instance mode on shutdown', async () => { + const redis = await loadRedis(TEST_URL); + await redis.connectRedis(); + const publisher = client(0); + const subscriber = client(1); + + await redis.disconnectRedis(); + + expect(publisher.quit).toHaveBeenCalledTimes(1); + expect(subscriber.quit).toHaveBeenCalledTimes(1); + expect(publisher.connected).toBe(false); + expect(subscriber.connected).toBe(false); + expect(redis.isRedisAvailable()).toBe(false); + expect(redis.getPublisher()).toBeNull(); + + // Shutdown can be reached twice (signal handler plus test teardown). + await expect(redis.disconnectRedis()).resolves.toBeUndefined(); + expect(publisher.quit).toHaveBeenCalledTimes(1); + }); +}); + +describe('reconnect and command-failure policy', () => { + let publisher: FakeClient; + let subscriber: FakeClient; + + beforeEach(async () => { + const redis = await loadRedis(TEST_URL); + await redis.connectRedis(); + publisher = client(0); + subscriber = client(1); + }); + + it('declines to queue commands while the link is down', () => { + // This is what bounds the wait a caller experiences; there is no separate + // per-command timeout in this module. + expect(publisher.options.enableOfflineQueue).toBe(false); + }); + + it('retries a command at most three times before rejecting it', () => { + expect(publisher.options.maxRetriesPerRequest).toBe(3); + }); + + it('connects on demand so a Redis-less boot costs no socket', () => { + expect(publisher.options.lazyConnect).toBe(true); + expect(publisher.connect).toHaveBeenCalledTimes(1); + }); + + it('backs off 200ms, 400ms, 600ms and then stops retrying', () => { + const retryStrategy = publisher.options.retryStrategy as (times: number) => number | null; + + expect(retryStrategy(1)).toBe(200); + expect(retryStrategy(2)).toBe(400); + expect(retryStrategy(3)).toBe(600); + // `null` is ioredis for "give up"; the fourth gap must be a stop rather + // than a longer wait, or a dead Redis is retried for the life of the + // process by a service that never re-runs `connectRedis`. + expect(retryStrategy(4)).toBeNull(); + expect(retryStrategy(50)).toBeNull(); + }); + + it('hands the same policy to the subscriber as to the publisher', () => { + // A subscriber that reconnects on a different schedule from the publisher + // would leave SSE pub/sub permanently split across the outage. The option + // bags cannot be compared whole — `makeClient` closes over a fresh + // `retryStrategy` per client — so the scalars and both schedules are + // checked separately. + const { retryStrategy: publisherStrategy, ...publisherScalars } = publisher.options; + const { retryStrategy: subscriberStrategy, ...subscriberScalars } = subscriber.options; + + expect(subscriberScalars).toEqual(publisherScalars); + const strategy = subscriberStrategy as (times: number) => number | null; + expect([1, 2, 3, 4].map(strategy)).toEqual([200, 400, 600, null]); + expect(strategy).not.toBe(publisherStrategy); + }); +}); + +describe('sliding-window tracker against the connection state', () => { + it('uses the in-memory window while Redis is absent and keeps one shared instance', async () => { + const redis = await loadRedis(undefined); + + const first = trackerOf(redis); + const second = trackerOf(redis); + + expect(first).toBe(second); + expect(first).toBeInstanceOf(redis.InMemorySlidingWindowTracker); + }); + + it('routes through the publisher once Redis answers and back to memory after shutdown', async () => { + const redis = await loadRedis(TEST_URL); + await redis.connectRedis(); + const publisher = publisherOf(redis); + + const tracker = trackerOf(redis); + expect(tracker).toBeInstanceOf(redis.RedisSlidingWindowTracker); + + await tracker.add('withdrawals', 'stream-1', 25, 1_000); + expect(publisher.zadd).toHaveBeenCalledWith('withdrawals', 1_000, 'stream-1:25'); + + await redis.disconnectRedis(); + publisher.zadd.mockClear(); + + const fallback = trackerOf(redis); + expect(fallback).toBeInstanceOf(redis.InMemorySlidingWindowTracker); + await fallback.add('withdrawals', 'stream-1', 25, 1_000); + expect(publisher.zadd).not.toHaveBeenCalled(); + expect((await fallback.snapshot('withdrawals', 10_000, 2_000)).count).toBe(1); + }); + + it('keeps detecting on the fallback when the connection failed at boot', async () => { + state.failConnect = true; + const redis = await loadRedis(TEST_URL); + await redis.connectRedis(); + + const tracker = trackerOf(redis); + + expect(tracker).toBeInstanceOf(redis.InMemorySlidingWindowTracker); + await tracker.add('k', 'a', 1, 1_000); + expect(await tracker.distinct('k', 60_000, 2_000)).toBe(1); + }); +}); + +describe('Redis command failures and bad replies', () => { + let redis: RedisModule; + let client0: FakeClient; + let tracker: ReturnType; + + beforeEach(async () => { + redis = await loadRedis(TEST_URL); + await redis.connectRedis(); + client0 = client(0); + tracker = trackerOf(redis); + }); + + it('ages a key out as part of the insert, before it writes the sample', async () => { + state.commands.length = 0; + + await tracker.add('k', 'a', 1, 1_000); + + expect(state.commands).toEqual(['zremrangebyscore', 'zadd', 'pexpire']); + expect(client0.zremrangebyscore).toHaveBeenCalledWith('k', '-inf', 1_000 - DAY_MS); + expect(client0.pexpire).toHaveBeenCalledWith('k', DAY_MS); + }); + + it('lets a failed insert reach the caller instead of losing the sample quietly', async () => { + client0.zadd.mockRejectedValue( + new Error("READONLY You can't write against a read only replica."), + ); + + await expect(tracker.add('k', 'a', 1, 1_000)).rejects.toThrow(/READONLY/); + }); + + it('lets a failed read reach the caller instead of reporting an empty window', async () => { + // An empty snapshot here would read as "no activity" to the sentinel, the + // opposite of what a Redis timeout means. + client0.zrangebyscore.mockRejectedValue(new Error('Connection is closed.')); + + await expect(tracker.snapshot('k', 60_000, 1_000)).rejects.toThrow( + 'Connection is closed.', + ); + }); + + it('does not mutate the window while reading it', async () => { + state.commands.length = 0; + + await tracker.snapshot('k', 60_000, 100_000); + + // A narrow read that pruned would blind the long-range baseline read. + expect(state.commands).toEqual(['zrangebyscore']); + expect(client0.zrangebyscore).toHaveBeenCalledWith('k', 40_000, '+inf', 'WITHSCORES'); + }); + + it('sums the weights out of members that embed id and weight together', async () => { + client0.zrangebyscore.mockResolvedValue(['stream:42:12.5', '1000', 'stream:43:7', '2000']); + + expect(await tracker.snapshot('k', 60_000, 3_000)).toEqual({ + count: 2, + sum: 19.5, + firstAt: 1000, + lastAt: 2000, + }); + }); + + it('degrades an unparsable weight to one event rather than dropping the sample', async () => { + client0.zrangebyscore.mockResolvedValue(['legacy-member', 'NaN', 'no-separator', '2000']); + + const snapshot = await tracker.snapshot('k', 60_000, 3_000); + + // Both members still count as activity; the score that is not a number is + // the one thing that cannot be reported as a timestamp. + expect(snapshot.count).toBe(2); + expect(snapshot.sum).toBe(2); + expect(snapshot.firstAt).toBe(2000); + expect(snapshot.lastAt).toBe(2000); + }); + + it('answers an empty window with zeroes and no timestamps', async () => { + const first = await tracker.snapshot('k', 60_000, 1_000); + const second = await tracker.snapshot('other', 60_000, 1_000); + + expect(first).toEqual({ count: 0, sum: 0, firstAt: null, lastAt: null }); + // A caller that writes to the snapshot must not be able to corrupt the + // shared empty value handed to everyone else. + expect(first).not.toBe(second); + first.count = 99; + expect(second.count).toBe(0); + }); + + it('counts distinct ids with ZCOUNT rather than reading the set back', async () => { + client0.zcount.mockResolvedValue(4); + + expect(await tracker.distinct('k', 60_000, 100_000)).toBe(4); + expect(client0.zcount).toHaveBeenCalledWith('k', 40_000, '+inf'); + expect(client0.zrangebyscore).not.toHaveBeenCalled(); + }); + + it('clears a window with DEL', async () => { + await tracker.clear('k'); + + expect(client0.del).toHaveBeenCalledWith('k'); + }); +}); + +describe('in-memory window bounding', () => { + it('keeps history a narrow read could have pruned', async () => { + const redis = await loadRedis(undefined); + const tracker = new redis.InMemorySlidingWindowTracker(); + await tracker.add('k', 'a', 1, 0); + await tracker.add('k', 'b', 1, 1_000); + + expect((await tracker.snapshot('k', 500, 1_000)).count).toBe(1); + // The sentinel reads a short burst window and a long baseline window off + // the same key, so the first read must not consume the second's data. + expect((await tracker.snapshot('k', DAY_MS, 1_000)).count).toBe(2); + }); + + it('drops samples past the retention age on the next insert', async () => { + const redis = await loadRedis(undefined); + const tracker = new redis.InMemorySlidingWindowTracker(); + await tracker.add('k', 'ancient', 1, 0); + await tracker.add('k', 'recent', 1, DAY_MS + 1_000); + + const snapshot = await tracker.snapshot('k', DAY_MS * 2, DAY_MS + 1_000); + + expect(snapshot.count).toBe(1); + expect(snapshot.firstAt).toBe(DAY_MS + 1_000); + }); + + it('evicts the oldest samples once a key is over its cap', async () => { + const redis = await loadRedis(undefined); + const tracker = new redis.InMemorySlidingWindowTracker(3); + const samples: Array<[string, number]> = [ + ['a', 1], + ['b', 2], + ['c', 3], + ['d', 4], + ['e', 5], + ]; + for (const [id, at] of samples) { + await tracker.add('k', id, 1, at); + } + + const snapshot = await tracker.snapshot('k', DAY_MS * 2, 5); + + // Bounded without waiting for a sweep, and it is the oldest that goes + // rather than an arbitrary member. + expect(snapshot.count).toBe(3); + expect(snapshot.firstAt).toBe(3); + expect(snapshot.lastAt).toBe(5); + }); + + it('refreshes an existing id in place rather than doubling it', async () => { + const redis = await loadRedis(undefined); + const tracker = new redis.InMemorySlidingWindowTracker(); + await tracker.add('k', 'stream-1', 1, 1_000); + await tracker.add('k', 'stream-1', 1, 2_000); + + const snapshot = await tracker.snapshot('k', DAY_MS, 2_000); + + expect(snapshot).toMatchObject({ count: 1, firstAt: 2_000, lastAt: 2_000 }); + }); + + it('answers for a key that was never written', async () => { + const redis = await loadRedis(undefined); + const tracker = new redis.InMemorySlidingWindowTracker(); + + expect(await tracker.snapshot('missing', 1_000, 1_000)).toEqual({ + count: 0, + sum: 0, + firstAt: null, + lastAt: null, + }); + expect(await tracker.distinct('missing', 1_000, 1_000)).toBe(0); + }); +}); diff --git a/backend/tests/sse-backpressure.test.ts b/backend/tests/sse-backpressure.test.ts new file mode 100644 index 00000000..d6a2cf29 --- /dev/null +++ b/backend/tests/sse-backpressure.test.ts @@ -0,0 +1,620 @@ +/** + * Issue #1748: SSE backpressure, connection ceilings and dropped-client cleanup. + * + * `tests/sse.service.test.ts` already pins the three headline paths (a write + * that throws, a write that returns false over the buffer ceiling, and the + * per-user cap reached by `close`). This file covers what that suite leaves + * open, which is the rest of the documented contract of + * `src/services/sse.service.ts`: + * + * - what "backpressure" actually costs the client: a slow client is paused + * and frames written while it is paused are dropped, because there is no + * queue in this service; + * - the exact buffer boundary and where the buffer length is read from; + * - that one slow client cannot truncate a fan-out to the clients after it; + * - that every removal path — drop, close, a failing `end()` — gives the + * IP/user slot back, which is what makes `checkCapacity` truthful again; + * - the ceiling `MAX_SSE_CONNECTIONS` imposes, and what a bogus value does; + * - the Redis pub/sub bridge in `initRedisSubscription`, which no test + * exercised at all. + * + * `MAX_WRITABLE_BUFFER` is module-private, so it is spelled out here the same + * way `tests/sse.service.test.ts` does. It is 64 KiB, and the service compares + * with `>=`, which is why both sides of the boundary are asserted. + */ +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import type { Response } from 'express'; +import { EventEmitter } from 'node:events'; + +const MAX_WRITABLE_BUFFER = 64 * 1024; +const MAX_CONNECTIONS_PER_IP = 5; +const MAX_CONNECTIONS_PER_USER = 10; + +vi.mock('../src/lib/redis.js', () => ({ + isRedisAvailable: vi.fn(() => false), + getPublisher: vi.fn(() => null), + getSubscriber: vi.fn(() => null), + cache: { get: vi.fn(), set: vi.fn(), del: vi.fn() }, + connectRedis: vi.fn(), + disconnectRedis: vi.fn(), +})); + +import { SSEService, HEARTBEAT_MESSAGE } from '../src/services/sse.service.js'; +import { + isRedisAvailable, + getPublisher, + getSubscriber, +} from '../src/lib/redis.js'; + +const available = isRedisAvailable as unknown as ReturnType; +const publisher = getPublisher as unknown as ReturnType; +const subscriber = getSubscriber as unknown as ReturnType; + +interface MockResponse extends Response { + emitter: EventEmitter; + frames: string[]; + setPaused: (value: boolean) => void; + setBuffer: (value: number) => void; +} + +/** + * `ownWritableLength: false` leaves the property off the response so the + * service has to fall back to `res.socket.writableLength`, which is the other + * branch of `getWritableLength`. + */ +function createMockResponse(options: { + writeReturns?: boolean; + throwOnWrite?: boolean; + writableLength?: number; + ownWritableLength?: boolean; + writableEnded?: boolean; + throwOnEnd?: boolean; +} = {}): MockResponse { + const emitter = new EventEmitter(); + const state = { + writeReturns: options.writeReturns ?? true, + writableLength: options.writableLength ?? 0, + throwOnWrite: options.throwOnWrite ?? false, + }; + const frames: string[] = []; + const ownWritableLength = options.ownWritableLength !== false; + + const res = { + emitter, + frames, + setPaused: (value: boolean) => { + state.writeReturns = !value; + }, + setBuffer: (value: number) => { + state.writableLength = value; + }, + write: vi.fn((frame: string) => { + if (state.throwOnWrite) throw new Error('write failed'); + frames.push(frame); + return state.writeReturns; + }), + once: emitter.once.bind(emitter), + on: emitter.on.bind(emitter), + end: vi.fn(() => { + if (options.throwOnEnd) throw new Error('end failed'); + }), + writableEnded: options.writableEnded ?? false, + socket: { writableLength: state.writableLength }, + }; + + if (ownWritableLength) { + Object.defineProperty(res, 'writableLength', { + get: () => state.writableLength, + configurable: true, + }); + } else { + // The socket keeps the same live view as the removed response property. + Object.defineProperty(res.socket, 'writableLength', { + get: () => state.writableLength, + configurable: true, + }); + } + + return res as unknown as MockResponse; +} + +let service: SSEService; + +afterEach(() => { + service?.stopHeartbeat(); + delete process.env.MAX_SSE_CONNECTIONS; + available.mockReturnValue(false); + publisher.mockReturnValue(null); + subscriber.mockReturnValue(null); +}); + +describe('backpressure: a paused client is skipped, not queued', () => { + beforeEach(() => { + service = new SSEService(); + }); + + it('drops frames written while the client is behind and does not replay them after drain', () => { + // The issue text calls this a "queue limit". There is no queue: the first + // `write()` returning false pauses the client and every later frame is + // discarded until the socket drains. Pinning it here means a future + // unbounded buffer has to be a deliberate change with a test saying so. + const res = createMockResponse({ writeReturns: false }); + service.addClient('slow', res); + + service.broadcast('stream.created', { n: 1 }); + expect(res.frames).toEqual(['event: stream.created\ndata: {"n":1}\n\n']); + + service.broadcast('stream.created', { n: 2 }); + service.broadcast('stream.created', { n: 3 }); + expect(res.frames).toHaveLength(1); + + res.emitter.emit('drain'); + service.broadcast('stream.created', { n: 4 }); + + // Frame 4 arrives and 2 and 3 never do. + expect(res.frames).toEqual([ + 'event: stream.created\ndata: {"n":1}\n\n', + 'event: stream.created\ndata: {"n":4}\n\n', + ]); + }); + + it('stops writing the moment the socket backs up and resumes on drain alone', () => { + const res = createMockResponse({ writeReturns: false }); + service.addClient('slow', res); + + service.broadcast('a', {}); + expect(res.write).toHaveBeenCalledTimes(1); + + // Heartbeats obey the pause too, so a stalled client cannot be used to + // keep buffering keepalives it will never read. + service.sendHeartbeat(); + expect(res.write).toHaveBeenCalledTimes(1); + + res.emitter.emit('drain'); + service.sendHeartbeat(); + expect(res.write).toHaveBeenCalledTimes(2); + expect(res.frames[1]).toBe(HEARTBEAT_MESSAGE); + }); + + it('keeps a client whose buffer is one byte under the ceiling', () => { + const res = createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER - 1, + }); + service.addClient('almost', res); + + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(1); + expect(service.getSlowClientsDropped()).toBe(0); + expect(res.end).not.toHaveBeenCalled(); + }); + + it('drops a client at the ceiling, where the comparison is inclusive', () => { + const res = createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER, + }); + service.addClient('over', res); + + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(0); + expect(service.getSlowClientsDropped()).toBe(1); + expect(res.end).toHaveBeenCalled(); + }); + + it('drops a client already paused that keeps buffering on a frame it was skipped for', () => { + // The pause branch re-checks the buffer, so a client that was fine when it + // stalled is pruned once its socket has filled up, even though nothing was + // written to it in between. + const res = createMockResponse({ writeReturns: false, writableLength: 1024 }); + service.addClient('slow', res); + + service.broadcast('stream.created', {}); + expect(service.getClientCount()).toBe(1); + + res.setBuffer(MAX_WRITABLE_BUFFER); + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(0); + expect(service.getSlowClientsDropped()).toBe(1); + }); + + it('reads the buffer off the socket when the response has no writableLength', () => { + const res = createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER, + ownWritableLength: false, + }); + service.addClient('socket-buffer', res); + + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(0); + }); + + it('treats a response with neither buffer readout as empty rather than throwing', () => { + const res = createMockResponse({ writeReturns: false }); + delete (res as { writableLength?: unknown }).writableLength; + delete (res as { socket?: unknown }).socket; + service.addClient('bare', res); + + expect(() => service.broadcast('stream.created', {})).not.toThrow(); + expect(service.getClientCount()).toBe(1); + }); +}); + +describe('backpressure: one slow client cannot truncate a fan-out', () => { + beforeEach(() => { + service = new SSEService(); + }); + + it('reaches the clients after a drop in the same broadcast', () => { + const first = createMockResponse(); + const slow = createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER, + }); + const last = createMockResponse(); + service.addClient('first', first); + service.addClient('slow', slow); + service.addClient('last', last); + + service.broadcast('stream.created', { streamId: '1' }); + + expect(service.getClientCount()).toBe(2); + expect(last.frames).toEqual([ + 'event: stream.created\ndata: {"streamId":"1"}\n\n', + ]); + expect(first.frames).toHaveLength(1); + }); + + it('reaches the clients after a write failure in the same broadcast', () => { + const broken = createMockResponse({ throwOnWrite: true }); + const last = createMockResponse(); + service.addClient('broken', broken); + service.addClient('last', last); + + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(1); + // A failed write is a dead connection, not a slow one: it is removed + // without being counted as a backpressure drop. + expect(service.getSlowClientsDropped()).toBe(0); + expect(last.frames).toHaveLength(1); + }); +}); + +describe('dropped-client cleanup', () => { + beforeEach(() => { + service = new SSEService(); + }); + + it('gives the IP slot back when a client is dropped for being slow', () => { + const ip = '10.0.0.5'; + const clients = Array.from({ length: MAX_CONNECTIONS_PER_IP }, (_, i) => + i === 2 + ? createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER, + }) + : createMockResponse(), + ); + clients.forEach((res, i) => service.addClient(`c${i}`, res, [], ip)); + + expect(service.checkCapacity(ip).allowed).toBe(false); + + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(MAX_CONNECTIONS_PER_IP - 1); + expect(service.checkCapacity(ip).allowed).toBe(true); + // The high-water mark is a metric about the peak, so releasing a slot does + // not rewind it. + expect(service.getPerIpPeakConnections()).toBe(MAX_CONNECTIONS_PER_IP); + }); + + it('gives the user slot back when a client is dropped for being slow', () => { + const userId = 'GUSER789'; + const res = createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER, + }); + service.addClient('slow', res, [], '10.0.0.9', userId); + expect(service.getUserConnectionCount(userId)).toBe(1); + + service.broadcast('stream.created', {}); + + expect(service.getUserConnectionCount(userId)).toBe(0); + expect(service.getActiveUserCount()).toBe(0); + }); + + it('leaves an already-ended response alone during cleanup', () => { + const res = createMockResponse({ writableEnded: true }); + service.addClient('ended', res, [], '10.0.0.1'); + + res.emitter.emit('close'); + + expect(service.getClientCount()).toBe(0); + expect(res.end).not.toHaveBeenCalled(); + }); + + it('removes the client even when closing the response throws', () => { + const broken = createMockResponse({ throwOnEnd: true }); + const healthy = createMockResponse(); + service.addClient('broken', broken, [], '10.0.0.1', 'GBROKEN'); + service.addClient('healthy', healthy, [], '10.0.0.2', 'GHEALTHY'); + + expect(() => broken.emitter.emit('close')).not.toThrow(); + + expect(service.getClientCount()).toBe(1); + expect(service.getUserConnectionCount('GBROKEN')).toBe(0); + expect(service.checkCapacity('10.0.0.1').allowed).toBe(true); + + // And the service is still usable afterwards. + service.broadcast('stream.created', {}); + expect(healthy.frames).toHaveLength(1); + }); + + it('is idempotent when a client closes twice', () => { + const res = createMockResponse(); + service.addClient('dup', res, [], '10.0.0.7', 'GDUP'); + + res.emitter.emit('close'); + res.emitter.emit('close'); + + expect(service.getClientCount()).toBe(0); + expect(service.getActiveIpCount()).toBe(0); + expect(service.getUserConnectionCount('GDUP')).toBe(0); + expect(res.end).toHaveBeenCalledTimes(1); + }); + + it('stops the heartbeat once the last client is dropped for being slow', () => { + const res = createMockResponse({ + writeReturns: false, + writableLength: MAX_WRITABLE_BUFFER, + }); + service.addClient('slow', res); + expect(service.isHeartbeatRunning()).toBe(true); + + service.broadcast('stream.created', {}); + + expect(service.getClientCount()).toBe(0); + expect(service.isHeartbeatRunning()).toBe(false); + }); +}); + +describe('connection ceiling', () => { + afterEach(() => { + delete process.env.MAX_SSE_CONNECTIONS; + }); + + it('rejects at MAX_SSE_CONNECTIONS with 503 and no Retry-After hint', () => { + process.env.MAX_SSE_CONNECTIONS = '3'; + service = new SSEService(); + expect(service.getMaxConnections()).toBe(3); + + for (let i = 0; i < 3; i += 1) { + expect(service.checkCapacity(`10.9.0.${i}`).allowed).toBe(true); + service.addClient(`c${i}`, createMockResponse(), [], `10.9.0.${i}`); + } + + const rejected = service.checkCapacity('10.9.9.9'); + expect(rejected).toEqual({ + allowed: false, + status: 503, + message: 'SSE capacity reached. Please try again shortly.', + }); + // A saturated server cannot promise the caller will fit in 60s, so it must + // not send a hint that a `429` would carry. + expect(rejected.retryAfterSeconds).toBeUndefined(); + }); + + it('reports saturation ahead of the per-IP limit it also exceeds', () => { + process.env.MAX_SSE_CONNECTIONS = '2'; + service = new SSEService(); + service.addClient('c0', createMockResponse(), [], '10.10.0.1'); + service.addClient('c1', createMockResponse(), [], '10.10.0.1'); + + const rejected = service.checkCapacity('10.10.0.1'); + + // Both limits are breached by this one IP; the answer has to be the one + // that tells the caller to back off rather than to close a tab. + expect(rejected.status).toBe(503); + }); + + it('falls back to the built-in ceiling for a value that is not a usable count', () => { + for (const raw of ['0', '-4', 'abc', '', ' ', 'Infinity']) { + process.env.MAX_SSE_CONNECTIONS = raw; + service = new SSEService(); + expect(service.getMaxConnections()).toBe(10000); + service.stopHeartbeat(); + } + + // A fractional ceiling is truncated, not rejected, and still honored. + process.env.MAX_SSE_CONNECTIONS = '1.9'; + service = new SSEService(); + expect(service.getMaxConnections()).toBe(1); + service.addClient('c0', createMockResponse(), [], '10.11.0.1'); + expect(service.checkCapacity('10.11.0.2').allowed).toBe(false); + }); + + it('quotes the per-IP limit and a 60s retry window in the rejection', () => { + service = new SSEService(); + const ip = '10.12.0.1'; + for (let i = 0; i < MAX_CONNECTIONS_PER_IP; i += 1) { + service.addClient(`c${i}`, createMockResponse(), [], ip); + } + + const rejected = service.checkCapacity(ip); + + expect(rejected).toMatchObject({ + allowed: false, + status: 429, + retryAfterSeconds: 60, + }); + expect(rejected.message).toBe( + `Too many SSE connections from this IP. Max ${MAX_CONNECTIONS_PER_IP}.`, + ); + }); + + it('counts a user against the per-user ceiling across every IP it uses', () => { + service = new SSEService(); + const userId = 'GFARM'; + for (let i = 0; i < MAX_CONNECTIONS_PER_USER; i += 1) { + service.addClient(`c${i}`, createMockResponse(), [], `10.13.${i}.1`, userId); + } + + expect(service.getActiveIpCount()).toBe(MAX_CONNECTIONS_PER_USER); + const rejected = service.checkCapacity('10.13.99.1', userId); + + expect(rejected.status).toBe(429); + expect(rejected.retryAfterSeconds).toBe(60); + expect(rejected.message).toBe( + `Too many concurrent SSE connections for this user. Max ${MAX_CONNECTIONS_PER_USER}.`, + ); + expect(service.getPerUserPeakConnections()).toBe(MAX_CONNECTIONS_PER_USER); + }); + + it('applies the per-IP ceiling per address instead of globally', () => { + service = new SSEService(); + for (let i = 0; i < MAX_CONNECTIONS_PER_IP; i += 1) { + service.addClient(`a${i}`, createMockResponse(), [], '10.14.0.1'); + } + + expect(service.checkCapacity('10.14.0.1').allowed).toBe(false); + expect(service.checkCapacity('10.14.0.2').allowed).toBe(true); + expect(service.getActiveIpCount()).toBe(1); + }); +}); + +describe('shutdown fan-out', () => { + beforeEach(() => { + service = new SSEService(); + }); + + it('tells every client to reconnect and survives a client whose socket is already gone', () => { + const broken = createMockResponse({ throwOnWrite: true }); + const healthy = createMockResponse(); + service.addClient('broken', broken); + service.addClient('healthy', healthy); + + service.sendReconnectToAll(); + + expect(service.isShuttingDown()).toBe(true); + expect(healthy.frames).toEqual(['event: reconnect\ndata: {}\n\n']); + // The broken client is not removed here: shutdown only announces, and the + // peer's own close event does the cleanup. + expect(service.getClientCount()).toBe(2); + }); + + it('tells the clients it is shutting down before the last frame goes out', () => { + const res = createMockResponse(); + service.addClient('client', res); + + expect(service.isShuttingDown()).toBe(false); + service.sendReconnectToAll(); + + expect(service.isShuttingDown()).toBe(true); + expect(service.isHeartbeatRunning()).toBe(false); + }); +}); + +describe('redis pub/sub bridge', () => { + beforeEach(() => { + service = new SSEService(); + }); + + it('publishes stream events instead of writing locally when redis is up', () => { + // Without this, a two-process deployment would silently stop delivering + // events to the process that does not hold the client. + const publish = vi.fn(); + available.mockReturnValue(true); + publisher.mockReturnValue({ publish }); + const local = createMockResponse(); + service.addClient('local', local, ['7']); + + service.broadcastToStream('7', 'stream.topped_up', { amount: '10' }); + + expect(publish).toHaveBeenCalledWith( + 'sse:stream:7', + JSON.stringify({ event: 'stream.topped_up', data: { amount: '10' } }), + ); + expect(local.write).not.toHaveBeenCalled(); + }); + + it('publishes user events on the user channel', () => { + const publish = vi.fn(); + available.mockReturnValue(true); + publisher.mockReturnValue({ publish }); + + service.broadcastToUser('GPUB123', 'stream.completed', { streamId: '7' }); + + expect(publish).toHaveBeenCalledWith( + 'sse:user:GPUB123', + JSON.stringify({ event: 'stream.completed', data: { streamId: '7' } }), + ); + }); + + it('delivers a redis message to the subscribed clients when the bridge reads it back', async () => { + const handlers = new Map void>(); + subscriber.mockReturnValue({ + psubscribe: vi.fn(), + on: vi.fn((event: string, handler: (...args: never[]) => void) => { + handlers.set(event, handler); + }), + }); + + await service.initRedisSubscription(); + + const mine = createMockResponse(); + const theirs = createMockResponse(); + const watching = createMockResponse(); + service.addClient('mine', mine, ['7']); + service.addClient('theirs', theirs, ['8']); + service.addClient('watching', watching, ['*']); + + handlers.get('pmessage')!( + 'sse:stream:*' as never, + 'sse:stream:7' as never, + JSON.stringify({ event: 'stream.cancelled', data: { streamId: '7' } }) as never, + ); + + expect(mine.frames).toEqual([ + 'event: stream.cancelled\ndata: {"streamId":"7"}\n\n', + ]); + expect(watching.frames).toHaveLength(1); + expect(theirs.write).not.toHaveBeenCalled(); + }); + + it('ignores a malformed redis payload instead of failing the subscription', async () => { + const handlers = new Map void>(); + subscriber.mockReturnValue({ + psubscribe: vi.fn(), + on: vi.fn((event: string, handler: (...args: never[]) => void) => { + handlers.set(event, handler); + }), + }); + await service.initRedisSubscription(); + + const res = createMockResponse(); + service.addClient('client', res, ['*']); + + const deliver = () => + handlers.get('pmessage')!( + 'sse:stream:*' as never, + 'sse:stream:7' as never, + '{not json' as never, + ); + + expect(deliver).not.toThrow(); + expect(res.write).not.toHaveBeenCalled(); + expect(service.getClientCount()).toBe(1); + }); + + it('does nothing without a subscriber, so a redis-less boot is not an error', async () => { + subscriber.mockReturnValue(null); + + await expect(service.initRedisSubscription()).resolves.toBeUndefined(); + }); +}); diff --git a/backend/tests/stream-cancel-idempotency.test.ts b/backend/tests/stream-cancel-idempotency.test.ts new file mode 100644 index 00000000..1ae77fa5 --- /dev/null +++ b/backend/tests/stream-cancel-idempotency.test.ts @@ -0,0 +1,417 @@ +/** + * Issue #1745: repeated cancellation, concurrent cancellation, and + * already-completed streams. + * + * These tests drive `cancelStreamHandler` directly (the same level + * `tests/cancel.controller.test.ts` works at) and pin the parts of the + * contract that file does not reach: what a second request does, what a + * request against a finished-but-not-cancelled stream does, the two + * streamId rejections, and which failure the catch block turns into 400 + * instead of 500. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { cancelStreamHandler } from '../src/controllers/stream/cancel.js'; +import { prisma } from '../src/lib/prisma.js'; +import * as sorobanService from '../src/services/sorobanService.js'; +import * as streamRepository from '../src/repositories/stream.repository.js'; +import type { Response } from 'express'; +import type { AuthenticatedRequest } from '../src/types/auth.types.js'; + +vi.mock('../src/lib/prisma.js', () => ({ + prisma: { + stream: { + findUnique: vi.fn(), + }, + }, +})); + +vi.mock('../src/services/sorobanService.js', () => ({ + cancelStream: vi.fn(), +})); + +vi.mock('../src/repositories/stream.repository.js', () => ({ + updateStatus: vi.fn(), + markCancelledProvisionally: vi.fn(), +})); + +vi.mock('../src/logger.js', () => ({ + default: { + info: vi.fn(), + error: vi.fn(), + warn: vi.fn(), + }, +})); + +const SENDER = 'GSENDER1'; + +type MockFn = ReturnType; + +const findUnique = prisma.stream.findUnique as unknown as MockFn; +const cancelOnChain = sorobanService.cancelStream as unknown as MockFn; +const markCancelled = streamRepository.markCancelledProvisionally as unknown as MockFn; + +function activeStream(overrides: Record = {}) { + return { streamId: 123n, sender: SENDER, isActive: true, status: 'ACTIVE', ...overrides }; +} + +function cancelledStream() { + return activeStream({ isActive: false, status: 'CANCELLED' }); +} + +function makeReq(overrides: Partial = {}): AuthenticatedRequest { + return { + params: { streamId: '123' }, + user: { publicKey: SENDER }, + body: { senderSecret: 'SABC123' }, + ...overrides, + } as unknown as AuthenticatedRequest; +} + +function makeRes(): Response & { status: MockFn; json: MockFn } { + const res = { status: vi.fn(), json: vi.fn() }; + res.status.mockReturnValue(res); + res.json.mockReturnValue(res); + return res as unknown as Response & { status: MockFn; json: MockFn }; +} + +/** The `{ error: { code, message } }` envelope `sendApiError` writes. */ +function errorBody(code: string, message: string) { + return { error: { code, message } }; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +/** The three dependencies every successful cancel needs. */ +function stubHappyPath(txHash = 'tx_first') { + findUnique.mockResolvedValue(activeStream()); + cancelOnChain.mockResolvedValue(txHash); + markCancelled.mockResolvedValue(undefined); +} + +beforeEach(() => { + // resetAllMocks, not clearAllMocks: `clear` leaves a queued + // `mockResolvedValueOnce` behind for the next test in the file. + vi.resetAllMocks(); +}); + +describe('cancel stream: a repeated request must not cancel twice', () => { + it('answers the first request 200 and the second 409 once the write is visible', async () => { + findUnique + .mockResolvedValueOnce(activeStream()) + .mockResolvedValueOnce(cancelledStream()); + cancelOnChain.mockResolvedValue('tx_first'); + markCancelled.mockResolvedValue(undefined); + + const first = makeRes(); + const second = makeRes(); + + await cancelStreamHandler(makeReq(), first); + await cancelStreamHandler(makeReq(), second); + + expect(first.status).toHaveBeenCalledWith(200); + expect(first.json).toHaveBeenCalledWith({ txHash: 'tx_first', status: 'CANCELLED' }); + + expect(second.status).toHaveBeenCalledWith(409); + expect(second.json).toHaveBeenCalledWith( + errorBody('CONFLICT', 'Stream is already cancelled or completed'), + ); + }); + + it('broadcasts the cancellation on-chain exactly once across two sequential requests', async () => { + findUnique + .mockResolvedValueOnce(activeStream()) + .mockResolvedValueOnce(cancelledStream()); + cancelOnChain.mockResolvedValue('tx_first'); + markCancelled.mockResolvedValue(undefined); + + await cancelStreamHandler(makeReq(), makeRes()); + await cancelStreamHandler(makeReq(), makeRes()); + + // The point of the 409: a client that retries a cancel it already + // succeeded with must not move money twice. + expect(cancelOnChain).toHaveBeenCalledTimes(1); + expect(cancelOnChain).toHaveBeenCalledWith(123n, 'SABC123'); + expect(markCancelled).toHaveBeenCalledTimes(1); + }); + + it('still answers 409 when the retry carries no senderSecret at all', async () => { + // Status is decided before the body is read, so a client that lost the + // original response can learn "it already happened" without resending + // its signing key. + findUnique.mockResolvedValue(cancelledStream()); + + const res = makeRes(); + await cancelStreamHandler(makeReq({ body: {} }), res); + + expect(res.status).toHaveBeenCalledWith(409); + expect(cancelOnChain).not.toHaveBeenCalled(); + }); + + it('lets the loser of two simultaneous requests read the winner write', async () => { + // Both handlers start together. The loser's lookup is made to wait until + // the winner's write has landed, which is the serialization Prisma gives + // two overlapping POSTs on one row, and then it sees an inactive stream. + const writeLanded = deferred(); + + findUnique + .mockResolvedValueOnce(activeStream()) + .mockImplementationOnce(async () => { + await writeLanded.promise; + return cancelledStream(); + }); + cancelOnChain.mockResolvedValue('tx_race'); + markCancelled.mockImplementation(async () => { + writeLanded.resolve(); + }); + + const winner = makeRes(); + const loser = makeRes(); + + await Promise.all([ + cancelStreamHandler(makeReq(), winner), + cancelStreamHandler(makeReq(), loser), + ]); + + expect(winner.status).toHaveBeenCalledWith(200); + expect(loser.status).toHaveBeenCalledWith(409); + expect(cancelOnChain).toHaveBeenCalledTimes(1); + }); +}); + +describe('cancel stream: a completed stream is not a cancellable one', () => { + it.each([ + ['COMPLETED', 'a stream that ran to term'], + ['CANCELLED', 'a stream cancelled earlier'], + ['PAUSED', 'a stream that is paused'], + ])('refuses %s (%s) with 409 and touches nothing', async (status) => { + findUnique.mockResolvedValue(activeStream({ isActive: false, status })); + + const res = makeRes(); + await cancelStreamHandler(makeReq(), res); + + expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith( + errorBody('CONFLICT', 'Stream is already cancelled or completed'), + ); + expect(cancelOnChain).not.toHaveBeenCalled(); + expect(markCancelled).not.toHaveBeenCalled(); + }); + + it('treats isActive as the liveness signal rather than the status label', async () => { + // Pinning which of the two representations the route trusts, so a later + // change to either has to be a deliberate one. + findUnique.mockResolvedValue(activeStream({ isActive: false, status: 'ACTIVE' })); + const inactive = makeRes(); + await cancelStreamHandler(makeReq(), inactive); + expect(inactive.status).toHaveBeenCalledWith(409); + + vi.resetAllMocks(); + findUnique.mockResolvedValue(activeStream({ isActive: true, status: 'COMPLETED' })); + cancelOnChain.mockResolvedValue('tx_flagged'); + markCancelled.mockResolvedValue(undefined); + const flagged = makeRes(); + await cancelStreamHandler(makeReq(), flagged); + expect(flagged.status).toHaveBeenCalledWith(200); + }); +}); + +describe('cancel stream: streamId boundary inputs', () => { + it('rejects an empty path segment with 400 MISSING_STREAM_ID before any read', async () => { + const res = makeRes(); + await cancelStreamHandler(makeReq({ params: { streamId: '' } }), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith( + errorBody('MISSING_STREAM_ID', 'Missing streamId parameter'), + ); + expect(findUnique).not.toHaveBeenCalled(); + }); + + it.each([ + ['whitespace only', ' '], + ['not decimal', 'abc'], + ['negative', '-1'], + ['a float', '12.5'], + ['a signed exponent', '1e3'], + ['a hex literal', '0x7b'], + ])('rejects a streamId that is %s with 400 INVALID_STREAM_ID', async (_label, streamId) => { + const res = makeRes(); + await cancelStreamHandler(makeReq({ params: { streamId } }), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith( + errorBody('INVALID_STREAM_ID', 'Invalid streamId parameter'), + ); + expect(findUnique).not.toHaveBeenCalled(); + }); + + it('accepts stream 0, the smallest legal u64', async () => { + findUnique.mockResolvedValue(activeStream({ streamId: 0n })); + cancelOnChain.mockResolvedValue('tx_zero'); + markCancelled.mockResolvedValue(undefined); + + const res = makeRes(); + await cancelStreamHandler(makeReq({ params: { streamId: '0' } }), res); + + // 0 is falsy, which is the case an `if (!streamId)` guard gets wrong. + expect(res.status).toHaveBeenCalledWith(200); + expect(cancelOnChain).toHaveBeenCalledWith(0n, 'SABC123'); + }); + + it('keeps precision above Number.MAX_SAFE_INTEGER', async () => { + const huge = '9007199254740993'; // 2^53 + 1 + findUnique.mockResolvedValue(activeStream({ streamId: BigInt(huge) })); + cancelOnChain.mockResolvedValue('tx_huge'); + markCancelled.mockResolvedValue(undefined); + + const res = makeRes(); + await cancelStreamHandler(makeReq({ params: { streamId: huge } }), res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(cancelOnChain).toHaveBeenCalledWith(BigInt(huge), 'SABC123'); + }); + + it('looks the stream up by the parsed bigint, never the raw string', async () => { + findUnique.mockResolvedValue(null); + + const res = makeRes(); + await cancelStreamHandler(makeReq({ params: { streamId: '007' } }), res); + + expect(findUnique).toHaveBeenCalledWith({ where: { streamId: 7n } }); + expect(res.status).toHaveBeenCalledWith(404); + expect(res.json).toHaveBeenCalledWith(errorBody('NOT_FOUND', 'Stream not found')); + }); +}); + +describe('cancel stream: senderSecret and the failure taxonomy', () => { + beforeEach(() => { + findUnique.mockResolvedValue(activeStream()); + }); + + it.each([ + ['absent', undefined], + ['null', null], + ['empty', ''], + ['a number', 12345], + ['an array', ['SABC123']], + ['a boolean', true], + ])('rejects a senderSecret that is %s with 400 INVALID_REQUEST', async (_label, secret) => { + cancelOnChain.mockResolvedValue('tx_unsent'); + + const res = makeRes(); + await cancelStreamHandler(makeReq({ body: { senderSecret: secret } }), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith( + errorBody('INVALID_REQUEST', 'senderSecret is required'), + ); + expect(cancelOnChain).not.toHaveBeenCalled(); + }); + + it('reads the body defensively when there is no body at all', async () => { + const res = makeRes(); + await cancelStreamHandler(makeReq({ body: undefined as never }), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(cancelOnChain).not.toHaveBeenCalled(); + }); + + it('maps a simulation failure to 400 with the upstream message, not a generic 500', async () => { + // A rejected transaction is the network's answer to the caller's own + // parameters, so it must not read as a server fault worth retrying. + cancelOnChain.mockRejectedValue(new Error('Simulation failed: insufficient balance')); + + const res = makeRes(); + await cancelStreamHandler(makeReq(), res); + + expect(res.status).toHaveBeenCalledWith(400); + expect(res.json).toHaveBeenCalledWith( + errorBody('TRANSACTION_SIMULATION_FAILED', 'Simulation failed: insufficient balance'), + ); + expect(markCancelled).not.toHaveBeenCalled(); + }); + + it('maps every other broadcast failure to 500 and writes nothing', async () => { + cancelOnChain.mockRejectedValue(new Error('tx_fail_post_submission')); + + const res = makeRes(); + await cancelStreamHandler(makeReq(), res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith( + errorBody('INTERNAL_SERVER_ERROR', 'A technical error occurred. Please try again later.'), + ); + expect(markCancelled).not.toHaveBeenCalled(); + }); + + it('answers 500 when the on-chain cancel succeeded but the DB write failed', async () => { + // The money has moved and the row still says active. Pinning the 500 so + // that inconsistency surfaces as an error a caller will retry rather + // than a success it will not. + cancelOnChain.mockResolvedValue('tx_moved'); + markCancelled.mockRejectedValue(new Error('connection lost')); + + const res = makeRes(); + await cancelStreamHandler(makeReq(), res); + + expect(cancelOnChain).toHaveBeenCalledTimes(1); + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith( + errorBody('INTERNAL_SERVER_ERROR', 'A technical error occurred. Please try again later.'), + ); + }); + + it('answers 500 when the lookup itself fails, not a 404 for an unknown stream', async () => { + findUnique.mockRejectedValue(new Error('db down')); + + const res = makeRes(); + await cancelStreamHandler(makeReq(), res); + + expect(res.status).toHaveBeenCalledWith(500); + expect(res.json).toHaveBeenCalledWith( + errorBody('INTERNAL_SERVER_ERROR', 'A technical error occurred. Please try again later.'), + ); + }); +}); + +describe('cancel stream: which guard answers first', () => { + it.each([ + ['a missing stream', null, 404], + ["someone else's active stream", { sender: 'GOTHER', isActive: true, status: 'ACTIVE' }, 403], + [ + "someone else's inactive stream", + { sender: 'GOTHER', isActive: false, status: 'CANCELLED' }, + 403, + ], + [ + 'an inactive stream', + { sender: SENDER, isActive: false, status: 'CANCELLED' }, + 409, + ], + ])('reports the stream state over the request body: %s', async (_label, row, expected) => { + findUnique.mockResolvedValue(row); + + const res = makeRes(); + await cancelStreamHandler(makeReq({ body: {} }), res); + + expect(res.status).toHaveBeenCalledWith(expected); + expect(cancelOnChain).not.toHaveBeenCalled(); + }); + + it('calls the on-chain cancel only for the sender of an active stream', async () => { + stubHappyPath('tx_ok'); + + const res = makeRes(); + await cancelStreamHandler(makeReq(), res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(cancelOnChain).toHaveBeenCalledWith(123n, 'SABC123'); + expect(markCancelled).toHaveBeenCalledWith(123n, 'tx_ok'); + }); +}); diff --git a/backend/tests/stream-events-cursor.test.ts b/backend/tests/stream-events-cursor.test.ts new file mode 100644 index 00000000..f60fced3 --- /dev/null +++ b/backend/tests/stream-events-cursor.test.ts @@ -0,0 +1,376 @@ +/** + * Issue #1746: event cursor ordering and invalid cursor recovery. + * + * The cursor lives on `GET /v1/streams/:streamId/events` + * (`src/routes/v1/stream.routes.ts:468` → `getStreamEvents` in + * `src/controllers/stream.controller.ts:336`), which is where the OpenAPI + * document declares the `cursor` parameter. `src/routes/v1/events.routes.ts`, + * named by the issue, paginates by limit/offset and has no cursor at all — + * verified with `grep -n cursor src/routes/v1/events.routes.ts`, which + * returns nothing — so there is no cursor contract to test there. + * + * These tests pin the cursor contract as it is published and as it behaves: + * which query the route hands the database, what makes one page follow + * another, how `hasMore` is decided in cursor mode, and what a cursor the + * database cannot resolve costs the caller. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import request from 'supertest'; + +const mocks = vi.hoisted(() => ({ + prisma: { + streamEvent: { + findMany: vi.fn(), + count: vi.fn(), + }, + }, + sseService: { + broadcastToStream: vi.fn(), + broadcastToUser: vi.fn(), + addClient: vi.fn(), + removeClient: vi.fn(), + getClientCount: vi.fn().mockReturnValue(0), + getActiveIpCount: vi.fn().mockReturnValue(0), + getPerIpPeakConnections: vi.fn().mockReturnValue(0), + getMaxConnections: vi.fn().mockReturnValue(10000), + checkCapacity: vi.fn().mockReturnValue({ allowed: true }), + isShuttingDown: vi.fn().mockReturnValue(false), + initRedisSubscription: vi.fn().mockResolvedValue(undefined), + }, +})); + +vi.mock('../src/lib/prisma.js', () => ({ + withReplicaFallback: (query: (client: unknown) => unknown) => + Promise.resolve(query(mocks.prisma)), + default: mocks.prisma, + prisma: mocks.prisma, +})); + +vi.mock('../src/services/sse.service.js', () => ({ + sseService: mocks.sseService, + SSEService: vi.fn(() => mocks.sseService), +})); + +vi.mock('../src/lib/redis.js', () => ({ + cache: { + get: vi.fn().mockReturnValue(null), + set: vi.fn(), + del: vi.fn(), + getMetadata: vi.fn(), + getStats: vi.fn().mockReturnValue({ hits: 0, misses: 0, hitRate: 0, itemCount: 0 }), + cleanup: vi.fn(), + }, + isRedisAvailable: vi.fn().mockReturnValue(false), + getPublisher: vi.fn().mockReturnValue(null), + getSubscriber: vi.fn().mockReturnValue(null), + connectRedis: vi.fn().mockResolvedValue(undefined), + disconnectRedis: vi.fn().mockResolvedValue(undefined), +})); + +import app from '../src/app.js'; + +const STREAM = '42'; +const PATH = `/v1/streams/${STREAM}/events`; + +/** + * `timestamp` alone is not unique — events written in the same ledger share + * one — so `id` is the tiebreaker that makes a cursor land in the same place + * twice. Two rows with one timestamp are the only way to see that. + */ +function event(id: string, timestamp: number) { + return { + id, + streamId: 42n, + eventType: 'WITHDRAWN', + amount: '1000', + transactionHash: `tx-${id}`, + ledgerSequence: 100, + timestamp, + metadata: null, + createdAt: new Date(timestamp * 1000), + }; +} + +const findMany = mocks.prisma.streamEvent.findMany as unknown as ReturnType; +const count = mocks.prisma.streamEvent.count as unknown as ReturnType; + +/** The one argument a spy received, with a message that names the spy. */ +function soleArgument(spy: ReturnType, name: string): Record { + const call = spy.mock.calls[0]; + if (!call) throw new Error(`${name} was never called`); + return call[0] as Record; +} + +/** + * The complete failure envelope, for a request that goes through the real + * express app. + * + * `sendApiError` echoes the `X-Request-ID` the request middleware put on the + * response, so a failure body carries three fields rather than two. The header + * is pinned non-empty before the comparison, otherwise a build that dropped + * both the header and the body field would match `undefined` against + * `undefined` and pass. + */ +function expectErrorEnvelope( + res: { headers: Record; body: unknown }, + code: string, + message: string, +) { + const requestId = res.headers['x-request-id']; + expect(typeof requestId).toBe('string'); + expect((requestId as string).length).toBeGreaterThan(0); + expect(res.body).toEqual({ error: { code, message, requestId } }); +} + +/** + * The `findMany` and `count` arguments the route built for this request. + * Both are asserted per call rather than by a mock matcher so a failure says + * which query drifted. + */ +async function queryFor(query: string) { + const res = await request(app).get(`${PATH}${query ? `?${query}` : ''}`).expect(200); + expect(findMany).toHaveBeenCalledTimes(1); + expect(count).toHaveBeenCalledTimes(1); + return { + body: res.body, + args: soleArgument(findMany, 'streamEvent.findMany'), + countArgs: soleArgument(count, 'streamEvent.count'), + }; +} + +beforeEach(() => { + vi.resetAllMocks(); + findMany.mockResolvedValue([]); + count.mockResolvedValue(0); +}); + +describe('event cursor: what the route asks the database for', () => { + it('seeks past the cursor row instead of re-reading it', async () => { + const { args } = await queryFor('cursor=evt-7'); + + expect(args.cursor).toEqual({ id: 'evt-7' }); + // skip:1 is what makes the next page start after the cursor rather than + // on it. Without it the first row of page N+1 repeats the last of page N. + expect(args.skip).toBe(1); + }); + + it('ignores offset entirely when a cursor is present', async () => { + const { args } = await queryFor('cursor=evt-7&offset=500'); + + expect(args.skip).toBe(1); + expect(args.skip).not.toBe(500); + }); + + it('pages by offset when no cursor is given', async () => { + const { args } = await queryFor('limit=2&page=3'); + + expect(args).not.toHaveProperty('cursor'); + expect(args.skip).toBe(4); + expect(args.take).toBe(2); + }); + + it('treats an empty cursor as no cursor', async () => { + // `?cursor=` arrives as the empty string, which is falsy, so the route + // must fall back to offset rather than seek to a row called "". + const { args } = await queryFor('cursor=&offset=10'); + + expect(args).not.toHaveProperty('cursor'); + expect(args.skip).toBe(10); + }); + + it('treats a repeated cursor parameter as no cursor', async () => { + // Express hands an array to a `?cursor=a&cursor=b`; the route only reads + // a string, so this has to page by offset and not hand Prisma an array. + const { args } = await queryFor('cursor=a&cursor=b'); + + expect(args).not.toHaveProperty('cursor'); + expect(args.skip).toBe(0); + }); + + it('counts the whole stream rather than the cursor window', async () => { + count.mockResolvedValue(9); + const { body, countArgs } = await queryFor('cursor=evt-7'); + + // The count carries only the filter: no cursor, skip or take. It is the + // stream's event count, so a client can tell how far into the list a + // cursor page sits. + expect(countArgs).toEqual({ where: { streamId: 42n } }); + expect(body.total).toBe(9); + }); +}); + +describe('event cursor: ordering', () => { + it('sorts by timestamp with id as the tiebreaker, newest first', async () => { + const { args } = await queryFor('cursor=evt-7'); + + expect(args.orderBy).toEqual([ + { timestamp: 'desc' }, + { id: 'desc' }, + ]); + }); + + it('flips both sort keys for order=asc, so a cursor still lands in the same place', async () => { + const { args } = await queryFor('cursor=evt-7&order=asc'); + + expect(args.orderBy).toEqual([ + { timestamp: 'asc' }, + { id: 'asc' }, + ]); + }); + + it('ignores an order value that is not asc', async () => { + const { args } = await queryFor('order=ASCENDING'); + + expect(args.orderBy).toEqual([ + { timestamp: 'desc' }, + { id: 'desc' }, + ]); + }); + + it('keeps two same-timestamp events in a stable order through the tiebreaker', async () => { + // The ledger wrote both events in one sequence, so they carry one + // timestamp. A cursor on the first of them has to resume at the second. + const ledger = 1_700_000_000; + findMany.mockResolvedValue([event('evt-b', ledger)]); + + const { body, args } = await queryFor('cursor=evt-a'); + + const order = args.orderBy as Array>; + expect(order.map((key) => Object.keys(key))).toEqual([['timestamp'], ['id']]); + expect(body.data.map((row: { id: string }) => row.id)).toEqual(['evt-b']); + }); +}); + +describe('event cursor: hasMore is decided by the page, not by the total', () => { + it('reports more pages when the cursor page came back exactly full', async () => { + findMany.mockResolvedValue([event('evt-8', 1), event('evt-9', 2)]); + count.mockResolvedValue(2); + + const { body } = await queryFor('cursor=evt-7&limit=2'); + + // A full page says nothing about whether the stream ended exactly there; + // the route must not claim the list is finished, and must not over-read. + expect(body.hasMore).toBe(true); + }); + + it('reports the last page when the cursor page came back short', async () => { + findMany.mockResolvedValue([event('evt-8', 1)]); + count.mockResolvedValue(9); + + const { body } = await queryFor('cursor=evt-7&limit=2'); + + // `total` still says 9, which is exactly why the cursor path cannot use + // `offset + length < total`: the cursor page has no offset. + expect(body.hasMore).toBe(false); + }); + + it('reports no more pages for an empty cursor page', async () => { + const { body } = await queryFor('cursor=evt-last&limit=5'); + + expect(body).toEqual({ data: [], total: 0, hasMore: false }); + }); + + it('reports a full page of the default size as having more', async () => { + findMany.mockResolvedValue( + Array.from({ length: 50 }, (_, i) => event(`evt-${i}`, 1_700_000_000 - i)), + ); + + const { args, body } = await queryFor('cursor=evt-50'); + + expect(args.take).toBe(50); + expect(body.hasMore).toBe(true); + }); +}); + +describe('event cursor: page size boundaries', () => { + it('clamps a cursor request for more than the published maximum', async () => { + const { args } = await queryFor('cursor=evt-7&limit=999999'); + + expect(args.take).toBe(200); + }); + + it.each([ + ['zero', '0'], + ['negative', '-5'], + ['not a number', 'ten'], + ['a float', '1.5'], + ['padded digits', ' 5'], + ])('rejects a limit of %s with 400 even alongside a valid cursor', async (_label, limit) => { + const res = await request(app).get(`${PATH}?cursor=evt-7&limit=${encodeURIComponent(limit)}`); + + expect(res.status).toBe(400); + expectErrorEnvelope(res, 'INVALID_PAGINATION', 'limit must be a positive integer'); + expect(findMany).not.toHaveBeenCalled(); + }); + + it('rejects a malformed cursor page request before reaching the database', async () => { + const res = await request(app).get(`${PATH}?cursor=evt-7&offset=-1`); + + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('INVALID_PAGINATION'); + expect(findMany).not.toHaveBeenCalled(); + }); +}); + +describe('event cursor: a cursor the database cannot resolve', () => { + it('answers 500 for a cursor that names no event', async () => { + // There is no recovery path: the route passes the raw id to Prisma, and + // a missing row throws. So a caller who follows a cursor they saved + // before the events were pruned gets a server error, not an empty page. + // This test pins that as the current contract; #1746 asks for recovery, + // which the code does not implement — reported rather than assumed. + findMany.mockRejectedValue(new Error('Record to update not found.')); + + const res = await request(app).get(`${PATH}?cursor=evt-deleted`); + + expect(res.status).toBe(500); + expectErrorEnvelope( + res, + 'INTERNAL_SERVER_ERROR', + 'A technical error occurred. Please try again later.', + ); + }); + + it('answers 500 for a cursor that is not an id at all, rather than 400', async () => { + findMany.mockRejectedValue(new Error("Invalid `prisma.streamEvent.findMany()` invocation")); + + const res = await request(app).get(`${PATH}?cursor=${encodeURIComponent('not-a-uuid')}`); + + expect(res.status).toBe(500); + expect(res.body.error.code).toBe('INTERNAL_SERVER_ERROR'); + }); + + it('does not retry or silently fall back to the first page', async () => { + // A client paging with a stale cursor must not be handed page 1 and never + // learn the difference. + findMany.mockRejectedValue(new Error('Record to update not found.')); + + await request(app).get(`${PATH}?cursor=evt-gone`).expect(500); + + expect(findMany).toHaveBeenCalledTimes(1); + }); +}); + +describe('event cursor: what is not a cursor problem', () => { + it('rejects a stream id that is not a u64 before reading a cursor', async () => { + const res = await request(app).get('/v1/streams/not-a-number/events?cursor=evt-7'); + + expect(res.status).toBe(400); + expectErrorEnvelope(res, 'INVALID_STREAM_ID', 'Invalid streamId parameter'); + expect(findMany).not.toHaveBeenCalled(); + }); + + it('keeps the event type filter applied across a cursor page', async () => { + const { args } = await queryFor('cursor=evt-7&eventType=WITHDRAWN'); + + expect(args.where).toEqual({ streamId: 42n, eventType: 'WITHDRAWN' }); + }); + + it('rejects an unknown event type alongside a cursor with 400', async () => { + const res = await request(app).get(`${PATH}?cursor=evt-7&eventType=NOT_A_THING`); + + expect(res.status).toBe(400); + expect(res.body.error.code).toBe('INVALID_EVENT_TYPE'); + expect(findMany).not.toHaveBeenCalled(); + }); +});