|
1 | | -import { ReadBuffer } from '../../src/shared/stdio.js'; |
| 1 | +import { ReadBuffer, STDIO_DEFAULT_MAX_BUFFER_SIZE } from '../../src/shared/stdio.js'; |
2 | 2 | import type { JSONRPCMessage } from '../../src/types/index.js'; |
3 | 3 |
|
4 | 4 | const testMessage: JSONRPCMessage = { |
@@ -113,3 +113,46 @@ describe('non-JSON line filtering', () => { |
113 | 113 | expect(() => readBuffer.readMessage()).toThrow(); |
114 | 114 | }); |
115 | 115 | }); |
| 116 | + |
| 117 | +describe('buffer size limit', () => { |
| 118 | + test('should throw when buffer exceeds default max size', () => { |
| 119 | + const readBuffer = new ReadBuffer(); |
| 120 | + const chunkSize = 1024 * 1024; // 1 MB |
| 121 | + const chunk = Buffer.alloc(chunkSize); |
| 122 | + const chunksToFill = Math.floor(STDIO_DEFAULT_MAX_BUFFER_SIZE / chunkSize); |
| 123 | + for (let i = 0; i < chunksToFill; i++) { |
| 124 | + readBuffer.append(chunk); |
| 125 | + } |
| 126 | + expect(() => readBuffer.append(chunk)).toThrow(/ReadBuffer exceeded maximum size/); |
| 127 | + }); |
| 128 | + |
| 129 | + test('should throw when buffer exceeds custom max size', () => { |
| 130 | + const readBuffer = new ReadBuffer({ maxBufferSize: 100 }); |
| 131 | + readBuffer.append(Buffer.alloc(50)); |
| 132 | + expect(() => readBuffer.append(Buffer.alloc(51))).toThrow(/ReadBuffer exceeded maximum size/); |
| 133 | + }); |
| 134 | + |
| 135 | + test('should clear buffer before throwing on overflow', () => { |
| 136 | + const readBuffer = new ReadBuffer({ maxBufferSize: 100 }); |
| 137 | + readBuffer.append(Buffer.alloc(50)); |
| 138 | + expect(() => readBuffer.append(Buffer.alloc(51))).toThrow(); |
| 139 | + |
| 140 | + // Buffer should be cleared — can append again |
| 141 | + readBuffer.append(Buffer.alloc(50)); |
| 142 | + // And read messages normally |
| 143 | + expect(readBuffer.readMessage()).toBeNull(); |
| 144 | + }); |
| 145 | + |
| 146 | + test('should allow appending up to exactly the max size', () => { |
| 147 | + const readBuffer = new ReadBuffer({ maxBufferSize: 100 }); |
| 148 | + // Should not throw — exactly at limit |
| 149 | + expect(() => readBuffer.append(Buffer.alloc(100))).not.toThrow(); |
| 150 | + }); |
| 151 | + |
| 152 | + test('should work with no options (backwards compatible)', () => { |
| 153 | + const readBuffer = new ReadBuffer(); |
| 154 | + // Small append should always work |
| 155 | + readBuffer.append(Buffer.from(JSON.stringify({ jsonrpc: '2.0', method: 'ping' }) + '\n')); |
| 156 | + expect(readBuffer.readMessage()).not.toBeNull(); |
| 157 | + }); |
| 158 | +}); |
0 commit comments