ronantakizawa/codereview-bench huggingface dataset:
Repository: fastify/fastify
File: fastify.js (JavaScript)

Code before:

  function ready (cb) {
    if (this[kState].readyPromise !== null) {
      if (cb != null) {
        this[kState].readyPromise.then(() => cb(null, fastify), cb)
        return
      }

      return this[kState].readyPromise
    }

    let resolveReady
    let rejectReady

    // run the hooks after returning the promise
    process.nextTick(runHooks)

    if (!cb) {
      const promise = new Promise(function (resolve, reject) {
        resolveReady = resolve
        rejectReady = reject
      })

      this[kState].readyPromise = promise

      return promise
    }

    function runHooks () {
      // start loading
      fastify[kAvvioBoot]((err, done) => {
        if (err || fastify[kState].started || fastify[kState].ready || fastify[kState].booting) {
          manageErr(err)
        } else {
          fastify[kState].booting = true
          hookRunnerApplication('onReady', fastify[kAvvioBoot], fastify, manageErr)
        }
        done()
      })
    }

    function manageErr (err) {
      // If the error comes out of Avvio's Error codes
      // We create a make and preserve the previous error
      // as cause
      err = err != null && AVVIO_ERRORS_MAP[err.code] != null
        ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message))
        : err

      if (cb) {
        if (err) {

Review comment (suggestion):
```suggestion
      return this[kState].readyPromise
```

Code after:

  function ready (cb) {
    if (this[kState].readyPromise !== null) {
      if (cb != null) {
        this[kState].readyPromise.then(() => cb(null, fastify), cb)
        return
      }

      return this[kState].readyPromise
    }

    let resolveReady
    let rejectReady

    // run the hooks after returning the promise
    process.nextTick(runHooks)

    // Create a promise no matter what
    // It will work as a barrier for all the .ready() calls (ensuring single hook execution)
    // as well as a flow control mechanism to chain cbs and further
    // promises
    this[kState].readyPromise = new Promise(function (resolve, reject) {
      resolveReady = resolve
      rejectReady = reject
    })

    if (!cb) {
      return this[kState].readyPromise
    } else {
      this[kState].readyPromise.then(() => cb(null, fastify), cb)
    }

    function runHooks () {
      // start loading
      fastify[kAvvioBoot]((err, done) => {
        if (err || fastify[kState].started || fastify[kState].ready || fastify[kState].booting) {
          manageErr(err)
        } else {
          fastify[kState].booting = true
          hookRunnerApplication('onReady', fastify[kAvvioBoot], fastify, manageErr)
        }
        done()
      })
    }

    function manageErr (err) {
      // If the error comes out of Avvio's Error codes
      // We create a make and preserve the previous error
      // as cause
      err = err != null && AVVIO_ERRORS_MAP[err.code] != null
        ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message))
Repository: fastify/fastify
File: lib/reply.js (JavaScript)

Code before:
  this[kReplyHijacked] = true
  return this
}

Reply.prototype.send = function (payload) {
  if (this[kReplyIsRunningOnErrorHook] === true) {
    throw new FST_ERR_SEND_INSIDE_ONERR()
  }

  if (this.sent) {
    this.log.warn({ err: new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method) })
    return this
  }

  if (payload instanceof Error || this[kReplyIsError] === true) {
    this[kReplyIsError] = false
    onErrorHook(this, payload, onSendHook)
    return this
  }

  const statusCode = this.raw.statusCode

  if ((statusCode >= 100 && statusCode < 200) || statusCode === 204) {
    onSendHook(this, payload)
    return this
  }

  if (payload === undefined) {
    onSendHook(this, payload)
    return this
  }

  const contentType = this.getHeader('content-type')
  const hasContentType = contentType !== undefined

  if (payload !== null) {
    if (typeof payload.pipe === 'function') {
      onSendHook(this, payload)
      return this
    }

    if (payload?.buffer instanceof ArrayBuffer) {
      if (hasContentType === false) {
        this[kReplyHeaders]['content-type'] = CONTENT_TYPE.OCTET
      }
      const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer)
      onSendHook(this, payloadToSend)
      return this
    }

    if (hasContentType === false && typeof payload === 'string') {

Review comment (suggestion):
```suggestion
  const statusCode = this.raw.statusCode
  if ((statusCode >= 100 && statusCode < 200) || statusCode === 204) {
    // Responses without a content body must not send content-type
    // or content-length headers.
    // See https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6.
    onSendHook(this, payload)
    return this
  }
```

Code after:
  this[kReplyHijacked] = true
  return this
}

Reply.prototype.send = function (payload) {
  if (this[kReplyIsRunningOnErrorHook] === true) {
    throw new FST_ERR_SEND_INSIDE_ONERR()
  }

  if (this.sent) {
    this.log.warn({ err: new FST_ERR_REP_ALREADY_SENT(this.request.url, this.request.method) })
    return this
  }

  if (payload instanceof Error || this[kReplyIsError] === true) {
    this[kReplyIsError] = false
    onErrorHook(this, payload, onSendHook)
    return this
  }

  if (payload === undefined) {
    onSendHook(this, payload)
    return this
  }

  const contentType = this.getHeader('content-type')
  const hasContentType = contentType !== undefined

  if (payload !== null) {
    if (typeof payload.pipe === 'function') {
      onSendHook(this, payload)
      return this
    }

    if (payload?.buffer instanceof ArrayBuffer) {
      if (hasContentType === false) {
        this[kReplyHeaders]['content-type'] = CONTENT_TYPE.OCTET
      }
      const payloadToSend = Buffer.isBuffer(payload) ? payload : Buffer.from(payload.buffer)
      onSendHook(this, payloadToSend)
      return this
    }

    if (hasContentType === false && typeof payload === 'string') {
      this[kReplyHeaders]['content-type'] = CONTENT_TYPE.PLAIN
      onSendHook(this, payload)
      return this
    }
  }

  if (this[kReplySerializer] !== null) {
Repository: fastify/fastify
File: test/reply-code.test.js (JavaScript)

Code before:
  })

  fastify.inject({
    method: 'GET',
    url: '/undefined'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 500)
    t.same(res.json(), {
      statusCode: 500,
      code: 'FST_ERR_BAD_STATUS_CODE',
      error: 'Internal Server Error',
      message: 'Called reply with an invalid status code: undefined'
    })
  })

  fastify.inject({
    method: 'GET',
    url: '/404.5'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 404)
  })
})

test('code should handle 204', t => {
  t.plan(4)

  const fastify = Fastify()

  fastify.get('/204', function (request, reply) {
    reply.status(204)
    return null
  })

  fastify.inject({
    method: 'GET',
    url: '/204'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 204)
    t.equal(res.payload, '')
    t.equal(res.headers['content-length'], undefined)
  })
})


Review comment (suggestion):
Can you also add a test where the body is explicitly ignored? e.g. sending a payload but being ignored because `204`

Code after:
  })

  fastify.inject({
    method: 'GET',
    url: '/undefined'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 500)
    t.same(res.json(), {
      statusCode: 500,
      code: 'FST_ERR_BAD_STATUS_CODE',
      error: 'Internal Server Error',
      message: 'Called reply with an invalid status code: undefined'
    })
  })

  fastify.inject({
    method: 'GET',
    url: '/404.5'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 404)
  })
})

test('code should handle 204', t => {
  t.plan(8)

  const fastify = Fastify()

  fastify.get('/204', function (request, reply) {
    reply.status(204)
    return null
  })

  fastify.get('/undefined/204', function (request, reply) {
    reply.status(204).send({ message: 'hello' })
  })

  fastify.inject({
    method: 'GET',
    url: '/204'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 204)
    t.equal(res.payload, '')
    t.equal(res.headers['content-length'], undefined)
  })

  fastify.inject({
    method: 'GET',
Repository: fastify/fastify
File: test/reply-code.test.js (JavaScript)

Code before:
  })

  fastify.inject({
    method: 'GET',
    url: '/undefined'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 500)
    t.same(res.json(), {
      statusCode: 500,
      code: 'FST_ERR_BAD_STATUS_CODE',
      error: 'Internal Server Error',
      message: 'Called reply with an invalid status code: undefined'
    })
  })

  fastify.inject({
    method: 'GET',
    url: '/404.5'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 404)
  })
})

test('code should handle 204', t => {
  t.plan(8)

  const fastify = Fastify()

  fastify.get('/204', function (request, reply) {
    reply.status(204)
    return null
  })
  fastify.get('/undefined/204', function (request, reply) {
    reply.status(204).send({ message: 'hello' })
  })

  fastify.inject({
    method: 'GET',
    url: '/204'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 204)
    t.equal(res.payload, '')
    t.equal(res.headers['content-length'], undefined)
  })

  fastify.inject({
    method: 'GET',
    url: '/undefined/204'

Review comment (suggestion):
Out of @climba03003 comment, we should add a test that verifies that if the `onSend` tries to alter the body, this alteration is ignored.

Code after:
  })

  fastify.inject({
    method: 'GET',
    url: '/undefined'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 500)
    t.same(res.json(), {
      statusCode: 500,
      code: 'FST_ERR_BAD_STATUS_CODE',
      error: 'Internal Server Error',
      message: 'Called reply with an invalid status code: undefined'
    })
  })

  fastify.inject({
    method: 'GET',
    url: '/404.5'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 404)
  })
})

test('code should handle 204', t => {
  t.plan(8)

  const fastify = Fastify()

  fastify.get('/204', function (request, reply) {
    reply.status(204)
    return null
  })

  fastify.get('/undefined/204', function (request, reply) {
    reply.status(204).send({ message: 'hello' })
  })

  fastify.inject({
    method: 'GET',
    url: '/204'
  }, (error, res) => {
    t.error(error)
    t.equal(res.statusCode, 204)
    t.equal(res.payload, '')
    t.equal(res.headers['content-length'], undefined)
  })

  fastify.inject({
    method: 'GET',
Repository: fastify/fastify
File: lib/errors.js (JavaScript)

Code before:
    'FST_ERR_REOPENED_CLOSE_SERVER',
    'Fastify has already been closed and cannot be reopened'
  ),
  FST_ERR_REOPENED_SERVER: createError(
    'FST_ERR_REOPENED_SERVER',
    'Fastify is already listening'
  ),
  FST_ERR_INSTANCE_ALREADY_LISTENING: createError(
    'FST_ERR_INSTANCE_ALREADY_LISTENING',
    'Fastify instance is already listening. %s'
  ),

  /**
   * plugin
   */
  FST_ERR_PLUGIN_VERSION_MISMATCH: createError(
    'FST_ERR_PLUGIN_VERSION_MISMATCH',
    "fastify-plugin: %s - expected '%s' fastify version, '%s' is installed"
  ),
  FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE: createError(
    'FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE',
    "The decorator '%s'%s is not present in %s"
  ),
  FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER: createError(
    'FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER',
    'Async function has too many arguments. Async plugin should not use the \'done\' argument.',
    500,
    TypeError
  ),

  /**
   *  Avvio Errors
   */
  FST_ERR_PLUGIN_CALLBACK_NOT_FN: createError(
    'FST_ERR_PLUGIN_CALLBACK_NOT_FN',
    'fastify-plugin: %s',
    500,
    TypeError
  ),
  FST_ERR_PLUGIN_NOT_VALID: createError(
    'FST_ERR_PLUGIN_NOT_VALID',
    'fastify-plugin: %s'
  ),
  FST_ERR_ROOT_PLG_BOOTED: createError(
    'FST_ERR_ROOT_PLG_BOOTED',
    'fastify-plugin: %s'
  ),
  FST_ERR_PARENT_PLUGIN_BOOTED: createError(
    'FST_ERR_PARENT_PLUGIN_BOOTED',
    'fastify-plugin: %s'
  ),

Review comment (suggestion):
```suggestion
    'The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.',
```

Code after:
    'FST_ERR_REOPENED_CLOSE_SERVER',
    'Fastify has already been closed and cannot be reopened'
  ),
  FST_ERR_REOPENED_SERVER: createError(
    'FST_ERR_REOPENED_SERVER',
    'Fastify is already listening'
  ),
  FST_ERR_INSTANCE_ALREADY_LISTENING: createError(
    'FST_ERR_INSTANCE_ALREADY_LISTENING',
    'Fastify instance is already listening. %s'
  ),

  /**
   * plugin
   */
  FST_ERR_PLUGIN_VERSION_MISMATCH: createError(
    'FST_ERR_PLUGIN_VERSION_MISMATCH',
    "fastify-plugin: %s - expected '%s' fastify version, '%s' is installed"
  ),
  FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE: createError(
    'FST_ERR_PLUGIN_NOT_PRESENT_IN_INSTANCE',
    "The decorator '%s'%s is not present in %s"
  ),
  FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER: createError(
    'FST_ERR_PLUGIN_INVALID_ASYNC_HANDLER',
    'The %s plugin being registered mixes async and callback styles. Async plugin should not mix async and callback style.',
    500,
    TypeError
  ),

  /**
   *  Avvio Errors
   */
  FST_ERR_PLUGIN_CALLBACK_NOT_FN: createError(
    'FST_ERR_PLUGIN_CALLBACK_NOT_FN',
    'fastify-plugin: %s',
    500,
    TypeError
  ),
  FST_ERR_PLUGIN_NOT_VALID: createError(
    'FST_ERR_PLUGIN_NOT_VALID',
    'fastify-plugin: %s'
  ),
  FST_ERR_ROOT_PLG_BOOTED: createError(
    'FST_ERR_ROOT_PLG_BOOTED',
    'fastify-plugin: %s'
  ),
  FST_ERR_PARENT_PLUGIN_BOOTED: createError(
    'FST_ERR_PARENT_PLUGIN_BOOTED',
    'fastify-plugin: %s'
  ),
Repository: fastify/fastify
File: test/hooks.on-listen.test.js (JavaScript)

Code before:
  t.plan(2)

  let timer
  let listenDone = false
  let doneRef
  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))

  fastify.addHook('onListen', function (done) {
    if (listenDone) {
      done()
    } else {
      timer = setTimeout(done, 100000)
      doneRef = done
    }
  })

  const startDate = Date.now()
  fastify.listen({
    host: 'localhost',
    port: 0
  }, err => {
    t.error(err)
    t.ok(Date.now() - startDate < 2000)
    listenDone = true
    clearTimeout(timer)
    if (doneRef) doneRef()
  })
})

test('onListen hooks do not block /2', async t => {
  t.plan(1)
  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))
  let timer
  let timedPromise
  let timePromiseResolve

  fastify.addHook('onListen', async function () {
    timedPromise = new Promise(resolve => {
      timer = setTimeout(resolve, 100000)
      timePromiseResolve = resolve
    })
    return timedPromise
  })

  const startDate = Date.now()
  await fastify.listen({
    host: 'localhost',
    port: 0
  })

Review comment (suggestion):
```suggestion
    timer && clearTimeout(timer)
```

Code after:
test('onListen hooks do not block /1', t => {
  t.plan(2)

  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))

  fastify.addHook('onListen', function (done) {
    t.equal(fastify[kState].listening, true)
    done()
  })

  fastify.listen({
    host: 'localhost',
    port: 0
  }, err => {
    t.error(err)
  })
})

test('onListen hooks do not block /2', async t => {
  t.plan(1)

  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))

  fastify.addHook('onListen', async function () {
    t.equal(fastify[kState].listening, true)
  })

  await fastify.listen({
    host: 'localhost',
    port: 0
  })
})
Repository: fastify/fastify
File: test/hooks.on-listen.test.js (JavaScript)

Code before:
  fastify.addHook('onListen', async function () {
    t.equal(++order, 1, '1st async called in root')
  })

  fastify.addHook('onListen', async function () {
    t.equal(++order, 2, '2nd async called in root')
    t.end()
  })

  fastify.listen({
    host: 'localhost',
    port: 0
  })
})

test('onListen hooks do not block /1', t => {
  t.plan(2)

  let timer
  let listenDone = false
  let doneRef
  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))

  fastify.addHook('onListen', function (done) {
    if (listenDone) {
      done()
    } else {
      timer = setTimeout(done, 100000)
      doneRef = done
    }
  })

  const startDate = Date.now()
  fastify.listen({
    host: 'localhost',
    port: 0
  }, err => {
    t.error(err)
    t.ok(Date.now() - startDate < 2000)
    listenDone = true
    timer && clearTimeout(timer)
    doneRef && doneRef()
  })
})

test('onListen hooks do not block /2', async t => {
  t.plan(1)
  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))
  let timer

Review comment (suggestion):
I don't think it is testing what it should be tested.
In most case `onListen` hook will run after the listen callback.
So, the timer is never fired.

Code after:

  fastify.addHook('onListen', async function () {
    t.equal(++order, 1, '1st async called in root')
  })

  fastify.addHook('onListen', async function () {
    t.equal(++order, 2, '2nd async called in root')
    t.end()
  })

  fastify.listen({
    host: 'localhost',
    port: 0
  })
})

test('onListen hooks do not block /1', t => {
  t.plan(2)

  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))

  fastify.addHook('onListen', function (done) {
    t.equal(fastify[kState].listening, true)
    done()
  })

  fastify.listen({
    host: 'localhost',
    port: 0
  }, err => {
    t.error(err)
  })
})

test('onListen hooks do not block /2', async t => {
  t.plan(1)

  const fastify = Fastify()
  t.teardown(fastify.close.bind(fastify))

  fastify.addHook('onListen', async function () {
    t.equal(fastify[kState].listening, true)
  })

  await fastify.listen({
    host: 'localhost',
    port: 0
  })
})
Repository: fastify/fastify
File: test/genReqId.test.js (JavaScript)

Code before:
      return 'foo'
    })
    instance.get('/', (req, reply) => {
      t.ok(req.id)
      reply.send({ id: req.id })
    })
    next()
  }, { prefix: 'foo' })

  fastify.register(function (instance, opts, next) {
    instance.setGenReqId(function (req) {
      return 'bar'
    })
    instance.get('/', (req, reply) => {
      t.ok(req.id)
      reply.send({ id: req.id })
    })
    next()
  }, { prefix: 'bar' })

  fastify.get('/', (req, reply) => {
    t.ok(req.id)
    reply.send({ id: req.id })
  })

  fastify.listen({ port: 0 }, err => {
    t.error(err)

    fastify.inject({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port
    }, (err, res) => {
      t.error(err)
      const payload = JSON.parse(res.payload)
      t.equal(payload.id, 'base')
      fastify.close()
    })

    fastify.inject({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/foo'
    }, (err, res) => {
      t.error(err)
      const payload = JSON.parse(res.payload)
      t.equal(payload.id, 'foo')
      fastify.close()
    })

    fastify.inject({
      method: 'GET',
      url: 'http://localhost:' + fastify.server.address().port + '/bar'

Review comment (suggestion):
No need to listen, `inject` already simulates and handles that

Code after:
    instance.setGenReqId(function (req) {
      return 'foo'
    })
    instance.get('/', (req, reply) => {
      t.ok(req.id)
      reply.send({ id: req.id })
    })
    next()
  }, { prefix: 'foo' })

  fastify.register(function (instance, opts, next) {
    instance.setGenReqId(function (req) {
      return 'bar'
    })
    instance.get('/', (req, reply) => {
      t.ok(req.id)
      reply.send({ id: req.id })
    })
    next()
  }, { prefix: 'bar' })

  fastify.get('/', (req, reply) => {
    t.ok(req.id)
    reply.send({ id: req.id })
  })

  fastify.inject({
    method: 'GET',
    url: '/'
  }, (err, res) => {
    t.error(err)
    const payload = JSON.parse(res.payload)
    t.equal(payload.id, 'base')
    fastify.close()
  })

  fastify.inject({
    method: 'GET',
    url: '/foo'
  }, (err, res) => {
    t.error(err)
    const payload = JSON.parse(res.payload)
    t.equal(payload.id, 'foo')
    fastify.close()
  })

  fastify.inject({
    method: 'GET',
    url: '/bar'
  }, (err, res) => {
    t.error(err)
Repository: fastify/fastify
File: lib/reqIdGenFactory.js (JavaScript)

Code before:
'use strict'

/**
 * @callback GenerateRequestId
 * @param {Object} req
 * @returns {string}
 */

/**
 * @param {string} [requestIdHeader]
 * @param {GenerateRequestId} [optGenReqId]
 * @returns {GenerateRequestId}
 */
function reqIdGenFactory (requestIdHeader, optGenReqId) {
  const genReqId = optGenReqId || buildDefaultGenReqId()

  if (requestIdHeader) {
    return buildOptionalHeaderReqId(requestIdHeader, genReqId)
  }

  return genReqId
}

function getGenReqId (contextServer, req) {
  const result = contextServer.genReqId.bind(contextServer, req)
  return result()
}

function buildDefaultGenReqId () {
  // 2,147,483,647 (2^31 − 1) stands for max SMI value (an internal optimization of V8).
  // With this upper bound, if you'll be generating 1k ids/sec, you're going to hit it in ~25 days.
  // This is very likely to happen in real-world applications, hence the limit is enforced.
  // Growing beyond this value will make the id generation slower and cause a deopt.
  // In the worst cases, it will become a float, losing accuracy.
  const maxInt = 2147483647

  let nextReqId = 0
  return function defaultGenReqId () {
    nextReqId = (nextReqId + 1) & maxInt
    return `req-${nextReqId.toString(36)}`
  }
}

function buildOptionalHeaderReqId (requestIdHeader, genReqId) {
  return function (req) {
    return req.headers[requestIdHeader] || genReqId(req)
  }
}

module.exports = {

Review comment (suggestion):
```suggestion
  return contextServer.genReqId.call(contextServer, req)
```

No need to create a binded function 👍  

Code after:
'use strict'

/**
 * @callback GenerateRequestId
 * @param {Object} req
 * @returns {string}
 */

/**
 * @param {string} [requestIdHeader]
 * @param {GenerateRequestId} [optGenReqId]
 * @returns {GenerateRequestId}
 */
function reqIdGenFactory (requestIdHeader, optGenReqId) {
  const genReqId = optGenReqId || buildDefaultGenReqId()

  if (requestIdHeader) {
    return buildOptionalHeaderReqId(requestIdHeader, genReqId)
  }

  return genReqId
}

function getGenReqId (contextServer, req) {
  return contextServer.genReqId(req)
}

function buildDefaultGenReqId () {
  // 2,147,483,647 (2^31 − 1) stands for max SMI value (an internal optimization of V8).
  // With this upper bound, if you'll be generating 1k ids/sec, you're going to hit it in ~25 days.
  // This is very likely to happen in real-world applications, hence the limit is enforced.
  // Growing beyond this value will make the id generation slower and cause a deopt.
  // In the worst cases, it will become a float, losing accuracy.
  const maxInt = 2147483647

  let nextReqId = 0
  return function defaultGenReqId () {
    nextReqId = (nextReqId + 1) & maxInt
    return `req-${nextReqId.toString(36)}`
  }
}

function buildOptionalHeaderReqId (requestIdHeader, genReqId) {
  return function (req) {
    return req.headers[requestIdHeader] || genReqId(req)
  }
}

module.exports = {
  getGenReqId,