|
1 | 1 | import { JSONRPCMessage } from '../../src/types.js'; |
2 | | -import { ReadBuffer } from '../../src/shared/stdio.js'; |
| 2 | +import { STDIO_DEFAULT_MAX_BUFFER_SIZE, ReadBuffer } from '../../src/shared/stdio.js'; |
3 | 3 |
|
4 | 4 | const testMessage: JSONRPCMessage = { |
5 | 5 | jsonrpc: '2.0', |
@@ -33,3 +33,46 @@ test('should be reusable after clearing', () => { |
33 | 33 | readBuffer.append(Buffer.from('\n')); |
34 | 34 | expect(readBuffer.readMessage()).toEqual(testMessage); |
35 | 35 | }); |
| 36 | + |
| 37 | +describe('buffer size limit', () => { |
| 38 | + test('should throw when buffer exceeds default max size', () => { |
| 39 | + const readBuffer = new ReadBuffer(); |
| 40 | + const chunkSize = 1024 * 1024; // 1 MB |
| 41 | + const chunk = Buffer.alloc(chunkSize); |
| 42 | + const chunksToFill = Math.floor(STDIO_DEFAULT_MAX_BUFFER_SIZE / chunkSize); |
| 43 | + for (let i = 0; i < chunksToFill; i++) { |
| 44 | + readBuffer.append(chunk); |
| 45 | + } |
| 46 | + expect(() => readBuffer.append(chunk)).toThrow(/ReadBuffer exceeded maximum size/); |
| 47 | + }); |
| 48 | + |
| 49 | + test('should throw when buffer exceeds custom max size', () => { |
| 50 | + const readBuffer = new ReadBuffer({ maxBufferSize: 100 }); |
| 51 | + readBuffer.append(Buffer.alloc(50)); |
| 52 | + expect(() => readBuffer.append(Buffer.alloc(51))).toThrow(/ReadBuffer exceeded maximum size/); |
| 53 | + }); |
| 54 | + |
| 55 | + test('should clear buffer before throwing on overflow', () => { |
| 56 | + const readBuffer = new ReadBuffer({ maxBufferSize: 100 }); |
| 57 | + readBuffer.append(Buffer.alloc(50)); |
| 58 | + expect(() => readBuffer.append(Buffer.alloc(51))).toThrow(); |
| 59 | + |
| 60 | + // Buffer should be cleared — can append again |
| 61 | + readBuffer.append(Buffer.alloc(50)); |
| 62 | + // And read messages normally |
| 63 | + expect(readBuffer.readMessage()).toBeNull(); |
| 64 | + }); |
| 65 | + |
| 66 | + test('should allow appending up to exactly the max size', () => { |
| 67 | + const readBuffer = new ReadBuffer({ maxBufferSize: 100 }); |
| 68 | + // Should not throw — exactly at limit |
| 69 | + expect(() => readBuffer.append(Buffer.alloc(100))).not.toThrow(); |
| 70 | + }); |
| 71 | + |
| 72 | + test('should work with no options (backwards compatible)', () => { |
| 73 | + const readBuffer = new ReadBuffer(); |
| 74 | + // Small append should always work |
| 75 | + readBuffer.append(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: 'ping' }) + '\n')); |
| 76 | + expect(readBuffer.readMessage()).not.toBeNull(); |
| 77 | + }); |
| 78 | +}); |
0 commit comments