summaryrefslogtreecommitdiffstats
path: root/test/socket-back-pressure.js
blob: 9e774b3de6aa590e97ca6e500dd04669e44185a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
'use strict'

const { Client } = require('..')
const { createServer } = require('http')
const { Readable } = require('stream')
const { test } = require('tap')

test('socket back-pressure', (t) => {
  t.plan(3)

  const server = createServer()
  let bytesWritten = 0

  const buf = Buffer.allocUnsafe(16384)
  const src = new Readable({
    read () {
      bytesWritten += buf.length
      this.push(buf)
      if (bytesWritten >= 1e6) {
        this.push(null)
      }
    }
  })

  server.on('request', (req, res) => {
    src.pipe(res)
  })
  t.teardown(server.close.bind(server))

  server.listen(0, () => {
    const client = new Client(`http://localhost:${server.address().port}`, {
      pipelining: 1
    })
    t.teardown(client.destroy.bind(client))

    client.request({ path: '/', method: 'GET', opaque: 'asd' }, (err, data) => {
      t.error(err)
      data.body
        .resume()
        .once('data', () => {
          data.body.pause()
          // TODO: Try to avoid timeout.
          setTimeout(() => {
            t.ok(data.body._readableState.length < bytesWritten - data.body._readableState.highWaterMark)
            src.push(null)
            data.body.resume()
          }, 1e3)
        })
        .on('end', () => {
          t.pass()
        })
    })
  })
})