|
| 1 | +'use strict'; |
| 2 | +const common = require('../common'); |
| 3 | +const http = require('http'); |
| 4 | +const assert = require('assert'); |
| 5 | + |
| 6 | +// Test that drain event is emitted correctly when using cork/uncork |
| 7 | +// with ServerResponse and the write buffer is full |
| 8 | + |
| 9 | +const server = http.createServer(common.mustCall(async (req, res) => { |
| 10 | + res.cork(); |
| 11 | + |
| 12 | + // Write small amount - won't need drain |
| 13 | + assert.strictEqual(res.write('1'.repeat(100)), true); |
| 14 | + |
| 15 | + // Write large amount that should require drain |
| 16 | + const needsDrain = !res.write('2'.repeat(1000000)); |
| 17 | + |
| 18 | + if (needsDrain) { |
| 19 | + // Verify writableNeedDrain is set |
| 20 | + assert.strictEqual(res.writableNeedDrain, true); |
| 21 | + |
| 22 | + // Wait for drain event after uncorking |
| 23 | + const drainPromise = new Promise((resolve) => { |
| 24 | + res.once('drain', common.mustCall(() => { |
| 25 | + // After drain, writableNeedDrain should be false |
| 26 | + assert.strictEqual(res.writableNeedDrain, false); |
| 27 | + resolve(); |
| 28 | + })); |
| 29 | + }); |
| 30 | + |
| 31 | + // Uncork should trigger drain if needed |
| 32 | + res.uncork(); |
| 33 | + |
| 34 | + await drainPromise; |
| 35 | + |
| 36 | + // Cork again for next write |
| 37 | + res.cork(); |
| 38 | + } |
| 39 | + |
| 40 | + // Write more data |
| 41 | + res.write('3'.repeat(100)); |
| 42 | + |
| 43 | + // Final uncork and end |
| 44 | + res.uncork(); |
| 45 | + res.end(); |
| 46 | +})); |
| 47 | + |
| 48 | +server.listen(0, common.mustCall(() => { |
| 49 | + http.get({ |
| 50 | + port: server.address().port, |
| 51 | + }, common.mustCall((res) => { |
| 52 | + let data = ''; |
| 53 | + res.setEncoding('utf8'); |
| 54 | + |
| 55 | + res.on('data', (chunk) => { |
| 56 | + data += chunk; |
| 57 | + }); |
| 58 | + |
| 59 | + res.on('end', common.mustCall(() => { |
| 60 | + // Verify we got all the data |
| 61 | + assert.strictEqual(data.length, 100 + 1000000 + 100); |
| 62 | + assert.strictEqual(data.substring(0, 100), '1'.repeat(100)); |
| 63 | + assert.strictEqual(data.substring(100, 1000100), '2'.repeat(1000000)); |
| 64 | + assert.strictEqual(data.substring(1000100), '3'.repeat(100)); |
| 65 | + |
| 66 | + server.close(); |
| 67 | + })); |
| 68 | + })); |
| 69 | +})); |
| 70 | + |
0 commit comments