|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const mockLogger = { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() }; |
| 4 | +jest.mock('../src/logger', () => mockLogger); |
| 5 | +jest.mock('../src/config', () => ({ |
| 6 | + ws: { maxConnections: 100, maxConnectionsPerIp: 5 }, |
| 7 | +})); |
| 8 | + |
| 9 | +const { PriceSubscriptionManager } = require('../src/ws/PriceSubscriptionManager'); |
| 10 | + |
| 11 | +const OPEN = 1; |
| 12 | +const CLOSED = 3; |
| 13 | + |
| 14 | +/** Minimal fake matching the subset of the `ws` socket API this class uses. */ |
| 15 | +class FakeSocket { |
| 16 | + constructor() { |
| 17 | + this.readyState = OPEN; |
| 18 | + this._handlers = {}; |
| 19 | + this.sent = []; |
| 20 | + this.closed = false; |
| 21 | + this.terminated = false; |
| 22 | + } |
| 23 | + |
| 24 | + on(event, handler) { |
| 25 | + (this._handlers[event] ??= []).push(handler); |
| 26 | + } |
| 27 | + |
| 28 | + emit(event, ...args) { |
| 29 | + for (const h of this._handlers[event] || []) h(...args); |
| 30 | + } |
| 31 | + |
| 32 | + send(data) { |
| 33 | + this.sent.push(JSON.parse(data)); |
| 34 | + } |
| 35 | + |
| 36 | + close() { |
| 37 | + this.closed = true; |
| 38 | + this.readyState = CLOSED; |
| 39 | + this.emit('close'); |
| 40 | + } |
| 41 | + |
| 42 | + terminate() { |
| 43 | + this.terminated = true; |
| 44 | + this.readyState = CLOSED; |
| 45 | + } |
| 46 | +} |
| 47 | +// `ws.readyState !== ws.constructor.OPEN` is how the real code checks |
| 48 | +// openness — give the fake the same static shape. |
| 49 | +FakeSocket.OPEN = OPEN; |
| 50 | + |
| 51 | +function req(ip) { |
| 52 | + return { socket: { remoteAddress: ip }, headers: {} }; |
| 53 | +} |
| 54 | + |
| 55 | +describe('PriceSubscriptionManager.drain (#364)', () => { |
| 56 | + let manager; |
| 57 | + |
| 58 | + beforeEach(() => { |
| 59 | + manager = new PriceSubscriptionManager(); |
| 60 | + jest.useFakeTimers(); |
| 61 | + }); |
| 62 | + |
| 63 | + afterEach(() => { |
| 64 | + jest.useRealTimers(); |
| 65 | + }); |
| 66 | + |
| 67 | + test('add() is rejected with 1013 once draining has started', () => { |
| 68 | + manager.drain(5000); |
| 69 | + |
| 70 | + const ws = new FakeSocket(); |
| 71 | + const closeSpy = jest.spyOn(ws, 'close'); |
| 72 | + const accepted = manager.add(ws, req('10.0.0.9')); |
| 73 | + |
| 74 | + expect(accepted).toBe(false); |
| 75 | + expect(closeSpy).toHaveBeenCalledWith(1013, 'Server shutting down'); |
| 76 | + expect(manager.connectionCount).toBe(0); |
| 77 | + }); |
| 78 | + |
| 79 | + test('warns every pre-drain client, then closes them after the grace delay', () => { |
| 80 | + const a = new FakeSocket(); |
| 81 | + const b = new FakeSocket(); |
| 82 | + manager.add(a, req('10.0.0.1')); |
| 83 | + manager.add(b, req('10.0.0.2')); |
| 84 | + |
| 85 | + manager.drain(4000); |
| 86 | + |
| 87 | + expect(a.sent[0]).toMatchObject({ type: 'server_shutdown' }); |
| 88 | + expect(b.sent[0]).toMatchObject({ type: 'server_shutdown' }); |
| 89 | + expect(a.closed).toBe(false); |
| 90 | + |
| 91 | + jest.advanceTimersByTime(1000); // closeDelayMs = min(1000, 4000/2) = 1000 |
| 92 | + expect(a.closed).toBe(true); |
| 93 | + expect(b.closed).toBe(true); |
| 94 | + }); |
| 95 | + |
| 96 | + test('force-terminates anything still open once drainTimeoutMs elapses', async () => { |
| 97 | + const a = new FakeSocket(); |
| 98 | + manager.add(a, req('10.0.0.1')); |
| 99 | + // Never actually closes on its own even after close() is called below — |
| 100 | + // simulate a stuck client by no-oping close(). |
| 101 | + a.close = () => {}; |
| 102 | + |
| 103 | + const donePromise = manager.drain(2000); |
| 104 | + jest.advanceTimersByTime(1000); // grace delay -> ws.close() (no-op here) |
| 105 | + jest.advanceTimersByTime(1000); // deadline -> ws.terminate() |
| 106 | + await donePromise; |
| 107 | + |
| 108 | + expect(a.terminated).toBe(true); |
| 109 | + expect(manager.drainStats.forceClosed).toBe(1); |
| 110 | + }); |
| 111 | + |
| 112 | + // The core of #364: even though add() already rejects connections once |
| 113 | + // _draining is true (verified above), drain() now also operates on a |
| 114 | + // snapshot of the client set taken atomically the instant draining |
| 115 | + // starts, rather than the live, mutable this._clients map. This proves |
| 116 | + // that guarantee directly: an entry inserted into the live map by some |
| 117 | + // other path *after* drain() has already captured its snapshot (bypassing |
| 118 | + // add()'s own guard, standing in for any future bug that might do so) is |
| 119 | + // never touched by any later drain phase. |
| 120 | + test('a client inserted into the live map after drain() starts is never touched by later phases', async () => { |
| 121 | + const a = new FakeSocket(); |
| 122 | + manager.add(a, req('10.0.0.1')); |
| 123 | + |
| 124 | + const donePromise = manager.drain(2000); |
| 125 | + |
| 126 | + const intruder = new FakeSocket(); |
| 127 | + manager._clients.set(intruder, { assets: new Set(), missedPings: 0 }); |
| 128 | + |
| 129 | + jest.advanceTimersByTime(1000); |
| 130 | + expect(a.closed).toBe(true); |
| 131 | + expect(intruder.closed).toBe(false); |
| 132 | + |
| 133 | + jest.advanceTimersByTime(1000); |
| 134 | + await donePromise; |
| 135 | + |
| 136 | + expect(intruder.terminated).toBe(false); |
| 137 | + expect(manager.drainStats.warned).toBe(1); // only `a`, captured at drain() start |
| 138 | + }); |
| 139 | + |
| 140 | + test('a client that disconnects naturally between drain phases is not double-counted', async () => { |
| 141 | + const a = new FakeSocket(); |
| 142 | + const b = new FakeSocket(); |
| 143 | + manager.add(a, req('10.0.0.1')); |
| 144 | + manager.add(b, req('10.0.0.2')); |
| 145 | + |
| 146 | + const donePromise = manager.drain(2000); |
| 147 | + |
| 148 | + jest.advanceTimersByTime(1000); // both get ws.close() -> FakeSocket emits 'close' -> _remove() |
| 149 | + expect(manager.connectionCount).toBe(0); |
| 150 | + |
| 151 | + jest.advanceTimersByTime(1000); // deadline: nothing left to force-close |
| 152 | + await donePromise; |
| 153 | + |
| 154 | + expect(manager.drainStats.forceClosed).toBe(0); |
| 155 | + }); |
| 156 | + |
| 157 | + test('drain() with no connected clients resolves immediately without scheduling timers', async () => { |
| 158 | + await expect(manager.drain(2000)).resolves.toBeUndefined(); |
| 159 | + expect(manager.isDraining).toBe(true); |
| 160 | + }); |
| 161 | +}); |
0 commit comments