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

Code before:
  }

  for (const address of addresses) {
    this.log.info(listenTextResolver(address))
  }
  return addresses[0]
}

/**
 * @param {http2.Http2Server} http2Server
 * @returns {() => void}
 */
function createCloseHttp2SessionsByHttp2Server (http2Server) {
  /**
   * @type {Set<http2.Http2Session>}
   */
  const http2Sessions = new Set()

  http2Server.on('session', function (session) {
    session.on('connect', function () {
      http2Sessions.add(session)
    })

    session.on('close', function () {
      http2Sessions.delete(session)
    })
  })

  return function closeHttp2Sessions () {
    if (http2Sessions.size === 0) {
      return
    }

    for (const session of http2Sessions.values()) {
      session.close()
    }
  }
}


Review comment (suggestion):
```suggestion
    session.once('connect', function () {
      http2Sessions.add(session)
    })

    session.once('close', function () {
      http2Sessions.delete(session)
    })
```

Code after:
    addresses = addresses.map((address) => ('http' + (this[kOptions].https ? 's' : '') + '://') + address)
  } else {
    addresses = [server.address()]
  }

  for (const address of addresses) {
    this.log.info(listenTextResolver(address))
  }
  return addresses[0]
}

/**
 * @param {http2.Http2Server} http2Server
 * @returns {() => void}
 */
function createCloseHttp2SessionsByHttp2Server (http2Server) {
  /**
   * @type {Set<http2.Http2Session>}
   */
  http2Server[kHttp2ServerSessions] = new Set()

  http2Server.on('session', function (session) {
    session.once('connect', function () {
      http2Server[kHttp2ServerSessions].add(session)
    })

    session.once('close', function () {
      http2Server[kHttp2ServerSessions].delete(session)
    })

    session.once('frameError', function (type, code, streamId) {
      if (streamId === 0) {
        // The stream ID is 0, which means that the error is related to the session itself.
        // If the event is not associated with a stream, the Http2Session will be shut down immediately
        http2Server[kHttp2ServerSessions].delete(session)
      }
    })

    session.once('goaway', function () {
      // The Http2Session instance will be shut down automatically when the 'goaway' event is emitted.
      http2Server[kHttp2ServerSessions].delete(session)
    })
  })

  return function closeHttp2Sessions () {
    if (http2Server[kHttp2ServerSessions].size === 0) {
      return
    }

    for (const session of http2Server[kHttp2ServerSessions]) {
      session.close()
Repository: fastify/fastify
File: test/allow-unsafe-regex.test.js (JavaScript)

Code before:
      reply.send({ foo: req.params.foo })
    })
  })
  done()
})

test('allow unsafe regex allow unsafe', async t => {
  t.plan(3)

  const fastify = Fastify({
    allowUnsafeRegex: true
  })
  t.after(() => fastify.close())

  t.assert.doesNotThrow(() => {
    fastify.get('/:foo(^([0-9]+){4}$)', (req, reply) => {
      reply.send({ foo: req.params.foo })
    })
  })

  await fastify.listen({ port: 0 })

  const result = await fetch(`http://localhost:${fastify.server.address().port}/1234`)
  t.assert.strictEqual(result.status, 200)
  const body = await result.json()
  t.assert.deepStrictEqual(body, { foo: '1234' })
})


Review comment (suggestion):
```suggestion
  t.assert.deepStrictEqual(await result.json(), { foo: '1234' })
```

Code after:
    })
  })
  done()
})

test('allow unsafe regex allow unsafe', async t => {
  t.plan(3)

  const fastify = Fastify({
    allowUnsafeRegex: true
  })
  t.after(() => fastify.close())

  t.assert.doesNotThrow(() => {
    fastify.get('/:foo(^([0-9]+){4}$)', (req, reply) => {
      reply.send({ foo: req.params.foo })
    })
  })

  await fastify.listen({ port: 0 })

  const result = await fetch(`http://localhost:${fastify.server.address().port}/1234`)
  t.assert.strictEqual(result.status, 200)
  t.assert.deepStrictEqual(await result.json(), { foo: '1234' })
})
Repository: fastify/fastify
File: test/allow-unsafe-regex.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')

test('allow unsafe regex', async t => {
  t.plan(2)

  const fastify = Fastify({
    allowUnsafeRegex: false
  })
  t.after(() => fastify.close())

  fastify.get('/:foo(^[0-9]*$)', (req, reply) => {
    reply.send({ foo: req.params.foo })
  })

  await fastify.listen({ port: 0 })

  const result = await fetch(`http://localhost:${fastify.server.address().port}/1234`)
  t.assert.strictEqual(result.status, 200)
  const body = await result.json()
  t.assert.deepStrictEqual(body, { foo: '1234' })
})

test('allow unsafe regex not match', async t => {
  t.plan(1)

  const fastify = Fastify({
    allowUnsafeRegex: false
  })
  t.after(() => fastify.close())

  fastify.get('/:foo(^[0-9]*$)', (req, reply) => {
    reply.send({ foo: req.params.foo })
  })

  await fastify.listen({ port: 0 })

  const result = await fetch(`http://localhost:${fastify.server.address().port}/a1234`)
  t.assert.strictEqual(result.status, 404)
})

test('allow unsafe regex not safe', (t, done) => {
  t.plan(1)

  const fastify = Fastify({
    allowUnsafeRegex: false

Review comment (suggestion):
```suggestion
  t.assert.deepStrictEqual(await result.json(), { foo: '1234' })
```

Code after:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')

test('allow unsafe regex', async t => {
  t.plan(2)

  const fastify = Fastify({
    allowUnsafeRegex: false
  })
  t.after(() => fastify.close())

  fastify.get('/:foo(^[0-9]*$)', (req, reply) => {
    reply.send({ foo: req.params.foo })
  })

  await fastify.listen({ port: 0 })

  const result = await fetch(`http://localhost:${fastify.server.address().port}/1234`)
  t.assert.strictEqual(result.status, 200)
  t.assert.deepStrictEqual(await result.json(), { foo: '1234' })
})

test('allow unsafe regex not match', async t => {
  t.plan(1)

  const fastify = Fastify({
    allowUnsafeRegex: false
  })
  t.after(() => fastify.close())

  fastify.get('/:foo(^[0-9]*$)', (req, reply) => {
    reply.send({ foo: req.params.foo })
  })

  await fastify.listen({ port: 0 })

  const result = await fetch(`http://localhost:${fastify.server.address().port}/a1234`)
  t.assert.strictEqual(result.status, 404)
})

test('allow unsafe regex not safe', (t, done) => {
  t.plan(1)

  const fastify = Fastify({
    allowUnsafeRegex: false
  })
Repository: fastify/fastify
File: test/custom-parser.1.test.js (JavaScript)

Code before:
  const postResult = await fetch(fastifyServer, {
    method: 'POST',
    body: '',
    headers: {
      'Content-Type': 'text/plain'
    }
  })

  t.assert.ok(postResult.ok)
  t.assert.strictEqual(postResult.status, 200)
  const postBody = await postResult.text()
  t.assert.strictEqual(postBody, '')

  const deleteResult = await fetch(fastifyServer, {
    method: 'DELETE',
    body: '',
    headers: {
      'Content-Type': 'text/plain',
      'Content-Length': '0'
    }
  })

  t.assert.ok(deleteResult.ok)
  t.assert.strictEqual(deleteResult.status, 200)
  const deleteBody = await deleteResult.text()
  t.assert.strictEqual(deleteBody, '')
})

test('Should parse empty bodies as a buffer', async (t) => {
  t.plan(4)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.addContentTypeParser('text/plain', { parseAs: 'buffer' }, function (req, body, done) {
    t.assert.ok(body instanceof Buffer)
    t.assert.strictEqual(body.length, 0)
    done(null, body)
  })

  const fastifyServer = await fastify.listen({ port: 0 })
  t.after(() => fastify.close())

  const result = await fetch(fastifyServer, {
    method: 'POST',
    body: '',
    headers: {
      'Content-Type': 'text/plain'
    }

Review comment (suggestion):
```suggestion
  t.assert.strictEqual(await deleteResult.text(), '')
```

Code after:
  const postResult = await fetch(fastifyServer, {
    method: 'POST',
    body: '',
    headers: {
      'Content-Type': 'text/plain'
    }
  })

  t.assert.ok(postResult.ok)
  t.assert.strictEqual(postResult.status, 200)
  t.assert.strictEqual(await postResult.text(), '')

  const deleteResult = await fetch(fastifyServer, {
    method: 'DELETE',
    body: '',
    headers: {
      'Content-Type': 'text/plain',
      'Content-Length': '0'
    }
  })

  t.assert.ok(deleteResult.ok)
  t.assert.strictEqual(deleteResult.status, 200)
  t.assert.strictEqual(await deleteResult.text(), '')
})

test('Should parse empty bodies as a buffer', async (t) => {
  t.plan(4)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.addContentTypeParser('text/plain', { parseAs: 'buffer' }, function (req, body, done) {
    t.assert.ok(body instanceof Buffer)
    t.assert.strictEqual(body.length, 0)
    done(null, body)
  })

  const fastifyServer = await fastify.listen({ port: 0 })
  t.after(() => fastify.close())

  const result = await fetch(fastifyServer, {
    method: 'POST',
    body: '',
    headers: {
      'Content-Type': 'text/plain'
    }
  })
Repository: fastify/fastify
File: test/custom-parser.1.test.js (JavaScript)

Code before:
    done(null, body)
  })

  fastify.route({
    method: ['POST', 'DELETE'],
    url: '/',
    handler (request, reply) {
      reply.send(request.body)
    }
  })

  const fastifyServer = await fastify.listen({ port: 0 })
  t.after(() => fastify.close())

  const postResult = await fetch(fastifyServer, {
    method: 'POST',
    body: '',
    headers: {
      'Content-Type': 'text/plain'
    }
  })

  t.assert.ok(postResult.ok)
  t.assert.strictEqual(postResult.status, 200)
  const postBody = await postResult.text()
  t.assert.strictEqual(postBody, '')

  const deleteResult = await fetch(fastifyServer, {
    method: 'DELETE',
    body: '',
    headers: {
      'Content-Type': 'text/plain',
      'Content-Length': '0'
    }
  })

  t.assert.ok(deleteResult.ok)
  t.assert.strictEqual(deleteResult.status, 200)
  const deleteBody = await deleteResult.text()
  t.assert.strictEqual(deleteBody, '')
})

test('Should parse empty bodies as a buffer', async (t) => {
  t.plan(4)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.addContentTypeParser('text/plain', { parseAs: 'buffer' }, function (req, body, done) {

Review comment (suggestion):
```suggestion
  t.assert.strictEqual(await postResult.text(), '')
```

Code after:
    done(null, body)
  })

  fastify.route({
    method: ['POST', 'DELETE'],
    url: '/',
    handler (request, reply) {
      reply.send(request.body)
    }
  })

  const fastifyServer = await fastify.listen({ port: 0 })
  t.after(() => fastify.close())

  const postResult = await fetch(fastifyServer, {
    method: 'POST',
    body: '',
    headers: {
      'Content-Type': 'text/plain'
    }
  })

  t.assert.ok(postResult.ok)
  t.assert.strictEqual(postResult.status, 200)
  t.assert.strictEqual(await postResult.text(), '')

  const deleteResult = await fetch(fastifyServer, {
    method: 'DELETE',
    body: '',
    headers: {
      'Content-Type': 'text/plain',
      'Content-Length': '0'
    }
  })

  t.assert.ok(deleteResult.ok)
  t.assert.strictEqual(deleteResult.status, 200)
  t.assert.strictEqual(await deleteResult.text(), '')
})

test('Should parse empty bodies as a buffer', async (t) => {
  t.plan(4)
  const fastify = Fastify()

  fastify.post('/', (req, reply) => {
    reply.send(req.body)
  })

  fastify.addContentTypeParser('text/plain', { parseAs: 'buffer' }, function (req, body, done) {
    t.assert.ok(body instanceof Buffer)
    t.assert.strictEqual(body.length, 0)
Repository: fastify/fastify
File: test/http-methods/copy.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const fastify = require('../../fastify')()
fastify.addHttpMethod('COPY')

test('can be created - copy', async t => {
  t.plan(3)

  t.after(() => { fastify.close() })

  try {
    fastify.route({
      method: 'COPY',
      url: '*',
      handler: function (req, reply) {
        reply.code(204).send()
      }
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }

  const fastifyServer = await fastify.listen({ port: 0 })

  const result = await fetch(`${fastifyServer}/test.txt`, {
    method: 'COPY',
    headers: {
      Destination: '/test2.txt'
    }
  })
  t.assert.ok(result.ok)
  t.assert.strictEqual(result.status, 204)
})

Review comment (suggestion):
```suggestion
  t.after(() => fastify.close())
```

Otherwise we are not waiting for the instance to be closed.

Code after:
'use strict'

const { test } = require('node:test')
const fastify = require('../../fastify')()
fastify.addHttpMethod('COPY')

test('can be created - copy', async t => {
  t.plan(3)

  t.after(() => fastify.close())

  try {
    fastify.route({
      method: 'COPY',
      url: '*',
      handler: function (req, reply) {
        reply.code(204).send()
      }
    })
    t.assert.ok(true)
  } catch (e) {
    t.assert.fail()
  }

  const fastifyServer = await fastify.listen({ port: 0 })

  const result = await fetch(`${fastifyServer}/test.txt`, {
    method: 'COPY',
    headers: {
      Destination: '/test2.txt'
    }
  })
  t.assert.ok(result.ok)
  t.assert.strictEqual(result.status, 204)
})
Repository: fastify/fastify
File: test/validation-error-handling.test.js (JavaScript)

Code before:
    schema: {
      body: {
        type: 'object',
        properties: {
          name: { type: 'string' }
        }
      }
    },
    validatorCompiler: ({ schema, method, url, httpPart }) => {
      return function (data) {
        // This custom validator throws an error instead of returning {error}
        throw new Error('Custom validation failed')
      }
    }
  }, function (request, reply) {
    t.assert.fail('Handler should not be called')
    reply.send({ success: true })
  })

  const response = await fastify.inject({
    method: 'POST',
    url: '/',
    payload: { name: 'test' }
  })

  t.assert.strictEqual(response.statusCode, 400)
  t.assert.deepStrictEqual(response.json(), { error: 'Custom validation failed' })
})


Review comment (suggestion):
```suggestion
  t.assert.strictEqual(response.statusCode, 500)
```

Code after:

    const fastify = Fastify()
    fastify.setErrorHandler((error, request, reply) => {
      t.assert.ok(error instanceof Error, 'error should be an Error instance')
      t.assert.strictEqual(error.message, 'Custom validation failed')
      reply.status(500).send({ error: error.message })
    })

    // Add async preValidation hook
    fastify.addHook('preValidation', async (request, reply) => {
      await Promise.resolve('ok')
    })
    fastify.post('/async', throwingRouteValidator)

    const response = await fastify.inject({
      method: 'POST',
      url: '/async',
      payload: { name: 'test' }
    })
    t.assert.strictEqual(response.statusCode, 500)
    t.assert.deepStrictEqual(response.json(), { error: 'Custom validation failed' })
  })

  test('sync preValidation with custom validator should trigger error handler when validator throws', async (t) => {
    t.plan(4)

    const fastify = Fastify()
    fastify.setErrorHandler((error, request, reply) => {
      t.assert.ok(error instanceof Error, 'error should be an Error instance')
      t.assert.strictEqual(error.message, 'Custom validation failed')
      reply.status(500).send({ error: error.message })
    })

    // Add sync preValidation hook
    fastify.addHook('preValidation', (request, reply, next) => { next() })
    fastify.post('/sync', throwingRouteValidator)

    const response = await fastify.inject({
      method: 'POST',
      url: '/sync',
      payload: { name: 'test' }
    })
    t.assert.strictEqual(response.statusCode, 500)
    t.assert.deepStrictEqual(response.json(), { error: 'Custom validation failed' })
  })
})
Repository: fastify/fastify
File: test/validation-error-handling.test.js (JavaScript)

Code before:
    method: 'POST',
    payload: {
      hello: 'michelangelo'
    },
    url: '/stillC'
  })

  t.assert.deepStrictEqual(response5.json(), {
    statusCode: 400,
    code: 'FST_ERR_VALIDATION',
    error: 'Bad Request',
    message: 'C'
  })
  t.assert.strictEqual(response5.statusCode, 400)
})

test('async preValidation with custom validator should trigger error handler when validator throws', async (t) => {
  t.plan(4)

  const fastify = Fastify()

  // Set up error handler
  fastify.setErrorHandler((error, request, reply) => {
    t.assert.ok(error instanceof Error, 'error should be an Error instance')
    t.assert.strictEqual(error.message, 'Custom validation failed')
    reply.status(400).send({ error: error.message })
  })

  // Add async preValidation hook
  fastify.addHook('preValidation', async (request, reply) => {
    // This hook makes the validation async
    await new Promise(resolve => setImmediate(resolve))
  })

  // Route with custom validator that throws
  fastify.post('/', {
    schema: {
      body: {
        type: 'object',
        properties: {
          name: { type: 'string' }
        }
      }
    },
    validatorCompiler: ({ schema, method, url, httpPart }) => {
      return function (data) {
        // This custom validator throws an error instead of returning {error}
        throw new Error('Custom validation failed')
      }
    }
  }, function (request, reply) {

Review comment (suggestion):
So we can test that the status code is correctly set

```suggestion
    reply.send({ error: error.message })
```

Code after:
    method: 'POST',
    payload: {
      hello: 'michelangelo'
    },
    url: '/stillC'
  })

  t.assert.deepStrictEqual(response5.json(), {
    statusCode: 400,
    code: 'FST_ERR_VALIDATION',
    error: 'Bad Request',
    message: 'C'
  })
  t.assert.strictEqual(response5.statusCode, 400)
})

describe('sync and async must work in the same way', () => {
  // Route with custom validator that throws
  const throwingRouteValidator = {
    schema: {
      body: {
        type: 'object',
        properties: { name: { type: 'string' } }
      }
    },
    validatorCompiler: () => {
      return function (inputData) {
        // This custom validator throws a sync error instead of returning `{ error }`
        throw new Error('Custom validation failed')
      }
    },
    handler (request, reply) { reply.send({ success: true }) }
  }

  test('async preValidation with custom validator should trigger error handler when validator throws', async (t) => {
    t.plan(4)

    const fastify = Fastify()
    fastify.setErrorHandler((error, request, reply) => {
      t.assert.ok(error instanceof Error, 'error should be an Error instance')
      t.assert.strictEqual(error.message, 'Custom validation failed')
      reply.status(500).send({ error: error.message })
    })

    // Add async preValidation hook
    fastify.addHook('preValidation', async (request, reply) => {
      await Promise.resolve('ok')
    })
    fastify.post('/async', throwingRouteValidator)

    const response = await fastify.inject({
Repository: fastify/fastify
File: test/close-pipelining.test.js (JavaScript)

Code before:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')
const { Client } = require('undici')

test('Should return 503 while closing - pipelining', { skip: 'flaky test' }, async t => {
  const fastify = Fastify({
    return503OnClosing: true,
    forceCloseConnections: false
  })

  fastify.get('/', async (req, reply) => {
    // Simulate a delay to allow pipelining to kick in
    await new Promise(resolve => setTimeout(resolve, 5))
    reply.send({ hello: 'world' })
    fastify.close()
  })

  await fastify.listen({ port: 0 })

  const instance = new Client('http://localhost:' + fastify.server.address().port, {
    pipelining: 2
  })

  const [firstRequest, secondRequest, thirdRequest] = await Promise.allSettled([
    instance.request({ path: '/', method: 'GET', blocking: false }),
    instance.request({ path: '/', method: 'GET', blocking: false }),
    instance.request({ path: '/', method: 'GET', blocking: false })
  ])
  t.assert.strictEqual(firstRequest.status, 'fulfilled')
  t.assert.strictEqual(secondRequest.status, 'fulfilled')

Review comment (suggestion):
```suggestion
test('Should return 503 while closing - pipelining', async t => {
```

Code after:
'use strict'

const { test } = require('node:test')
const Fastify = require('..')
const { Client } = require('undici')

test('Should return 503 while closing - pipelining', async t => {
  const fastify = Fastify({
    return503OnClosing: true,
    forceCloseConnections: false
  })

  fastify.get('/', async (req, reply) => {
    // Simulate a delay to allow pipelining to kick in
    await new Promise(resolve => setTimeout(resolve, 5))
    reply.send({ hello: 'world' })
    fastify.close()
  })

  await fastify.listen({ port: 0 })

  const instance = new Client('http://localhost:' + fastify.server.address().port, {
    pipelining: 2
  })

  const [firstRequest, secondRequest, thirdRequest] = await Promise.allSettled([
    instance.request({ path: '/', method: 'GET', blocking: false }),
    instance.request({ path: '/', method: 'GET', blocking: false }),
    instance.request({ path: '/', method: 'GET', blocking: false })
  ])
  t.assert.strictEqual(firstRequest.status, 'fulfilled')
  t.assert.strictEqual(secondRequest.status, 'fulfilled')