profile
viewpoint
Matteo Collina mcollina @nearform In the clouds above Italy Technical Director @nearform, TSC member @nodejs, IoT Expert, Conference Speaker, Ph.D.

davidmarkclements/0x 1886

🔥 single-command flamegraph profiling 🔥

delvedor/find-my-way 676

A crazy fast HTTP router

davidmarkclements/v8-perf 253

Exploring v8 performance characteristics in Node across v8 versions 5.1, 5.8, 5.9, 6.0 and 6.1

davidmarkclements/fast-safe-stringify 219

Safely and quickly serialize JavaScript objects

davidmarkclements/overload-protection 161

Load detection and shedding capabilities for http, express, restify and koa

davidmarkclements/fast-redact 134

very fast object redaction

andreareginato/conference_site 23

A conference site that can be used for your next big event

delvedor/fast-decode-uri-component 13

Fast and safe decodeURIComponent

created tagpinojs/pino-std-serializers

tagv2.5.0

🌲 A list of standard object serializers for the Pino logger

created time in 2 hours

release pinojs/pino-std-serializers

v2.5.0

released time in 2 hours

push eventpinojs/pino-std-serializers

Matteo Collina

commit sha 1e6ef469dee7e6c10502c30063fe4f7d0cb9a622

Bumped v2.5.0

view details

push time in 2 hours

push eventpinojs/pino-std-serializers

Matteo Collina

commit sha e89823284ae88295482af8720f1c44a46e0c30db

Added Node v14 to .travis.yml

view details

push time in 2 hours

push eventpinojs/pino-std-serializers

Hugo Ortiz

commit sha 3f60a622655dc83ccb163c9415451841fde65f89

[master] prefer req.path instead of req.url.path (#29) * [master] prefer req.path instead of req.url.path * [master] add fallback when req path is not present, added unit test Co-authored-by: Hugo Ortiz <huortiz@paypal.com>

view details

push time in 2 hours

issue closedpinojs/pino-std-serializers

Not handling correctly `request.url` when inject an invalid URL

We recently had a problem with pino in hapi, because hapi is unable to create the request.url object when the URL is invalid, see this gist

closed time in 2 hours

rtrys

pull request commentmcollina/undici

Fast socket2

You can use those to write to any file descriptor.

ronag

comment created time in 2 hours

pull request commentmcollina/undici

Fast socket2

Something around 5%? Probably not worth it. Have you tried going with fs.write and writev and bypassing the wrap?

ronag

comment created time in 3 hours

push eventmcollina/fastify-gql

Matteo Collina

commit sha d06d0004b70f01d19c62b2bd1a6e0df2fdd68897

Fix flaky test

view details

push time in 7 hours

push eventmcollina/fastify-gql

Matteo Collina

commit sha d80cb9cfd7fe32820f027e9748821cfdf2b8c112

remove var

view details

push time in 7 hours

pull request commentmcollina/fastify-gql

Added logging to the default error formatter

Seems like a side effect that may not be evident to users, and thus they'd fail to reimplement it when they use a custom formatter.

This come from experience. There is a significant amount of devs that asked for a similar feature to be removed from Fastify. If I move it outside of the errorFormatter, I would need to add a new option. By putting it in the errorFormatter, I leave it to the user by default.

mcollina

comment created time in 7 hours

issue closedfastify/help

Can't start the server

You have already researched for similar issues?

Yes, but I didn't find anything related to this issue.

What are you trying to achieve or the steps to reproduce?

When I started to create a simple app with Fastify version 3.2.0, It gives me some errors. But after downgrading to version 2.15.3, problem solved

// simple hello world index.js

const fastify = require("fastify")({
  logger: true,
});

// Declare a route
fastify.get("/", function (request, reply) {
  reply.send({ hello: "world" });
});

// Run the server!
fastify.listen(3000, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
  fastify.log.info(`server listening on ${address}`);
});

What was the result you received?

The result with version 3.2.1:

{"level":50,"time":1597419681847,"pid":6792,"hostname":"MY-PC-NAME","generatedMessage":false,"name":"AssertionError [ERR_ASSERTION]","code":"ERR_ASSERTION","actual":false,"expected":true,"operator":"==","stack":"AssertionError [ERR_ASSERTION]: Version should be a string
at Router._on ([PATH-TO-PROJECT]\\node_modules\\find-my-way\\index.js:98:5)
at Router.on ([PATH-TO-PROJECT]\\node_modules\\find-my-way\\index.js:73:8)
at Object.afterRouteAdded ([PATH-TO-PROJECT]\\node_modules\\fastify\\lib\\route.js:221:16)
at after ([PATH-TO-PROJECT]\\node_modules\\fastify\\lib\\route.js:167:25
at Object._encapsulateThreeParam ([PATH-TO-PROJECT]\\node_modules\\avvio\\boot.js:545:7)
at Boot.timeoutCall ([PATH-TO-PROJECT]\\node_modules\\avvio\\boot.js:447:5)
at Boot.callWithCbOrNextTick ([PATH-TO-PROJECT]\\node_modules\\avvio\\boot.js:428:19)
at Boot._after ([PATH-TO-PROJECT]\\node_modules\\avvio\\boot.js:273:26)
at Plugin.exec ([PATH-TO-PROJECT]\\node_modules\\avvio\\plugin.js:131:17)
at Boot.loadPlugin ([PATH-TO-PROJECT]\\node_modules\\avvio\\plugin.js:266:10)","type":"Error","msg":"Version should be a string"}

What did you expect?

Anything but not an error.

Context

  • node version: 10.20.1
  • fastify version: >=3.2.0
  • os: Windows
  • I start the server using nodemon

closed time in 7 hours

Narixius

issue commentfastify/help

Can't start the server

This is fixed already, update your dependencies. Sorry for the problem :(

Narixius

comment created time in 7 hours

issue commentnodejs/node

Absolute Windows paths are handled as invalid URL path in ESM import()

The problem here is that I had absolutely not clue on why some code I wrote was not working on windows as the code was working smoothly on Linux and Mac. The developer experience for this was far from great, because the only way to debug this would be to have a Windows machine

One other option we can consider here would be to improve the error message in the case of an absolute windows path.

I think this would be the bare minimum change that improve the developer experience.

StarpTech

comment created time in 8 hours

issue closedfastify/help

fastify-request-context is not working for POST API calls

import fastify from 'fastify';
const { fastifyRequestContextPlugin } = require('fastify-request-context');
const server = fastify({
    logger: true
});
const preValidationFn = (req, reply, done): any => {
    req.requestContext.set('hello', 'hello world');
    console.log(req.requestContext.get('hello'));
    done();
};
const handlerFn = (req, reply): any => {
    console.log(req.requestContext.get('hello'));
    reply.send('hello world');
};
server.route({
    url: '/test',
    method: ['GET', 'POST'],
    preValidation: preValidationFn,
    handler: handlerFn
});

server.register(fastifyRequestContextPlugin);
console.log('Starting fastify Typescript server ');
server.listen(8085, '0.0.0.0', (err, address): void => {
    if (err) {
        console.warn(err);
        process.exit(1);
    }
    console.info(`Server listening at ${address}`);
});


process.on('uncaughtException', error => {
    console.error(error);
});
process.on('unhandledRejection', error => {
    console.error(error);
});

This is my fastify server written in typescript while using the fastify-request-context plugin I am able to access the context of fastify request when I am requesting the resource using the GET method, But I am not able to access the context of fastify request if I am requesting the resource using POST method

This is the stackoverflow link

https://stackoverflow.com/questions/63325150/fastify-request-context-is-not-working-for-post-api-calls

closed time in 8 hours

rahul2123

push eventmcollina/fastify-gql

Matteo Collina

commit sha c2c7390ce679d51f5a3f2593a856863ae05bcb9c

add final assertion on number of errors

view details

push time in 8 hours

push eventmcollina/fastify-gql

Matteo Collina

commit sha 502aa83ebd45da227b2a5646fd965373dd1c04ab

100% code coverage

view details

push time in 8 hours

PR opened mcollina/fastify-gql

Reviewers
Added logging to the default error formatter

As titled

+55 -14

0 comment

5 changed files

pr created time in 9 hours

push eventmcollina/fastify-gql

push time in 9 hours

create barnchmcollina/fastify-gql

branch : default-error-formatter-logging

created branch time in 9 hours

push eventmcollina/fastify-gql

Matteo Collina

commit sha b34eee7367b02d3fcdbfdd12fd4794766e55fc3d

Added logging to the default error formatter

view details

push time in 9 hours

Pull request review commentfastify/fastify-request-context

Fix context loss when async storage is instantiated early in the request lifecycle

 const requestContext = { function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext)+  const hook = opts.hook || 'onRequest' -  fastify.addHook('onRequest', (req, res, done) => {+  fastify.addHook(hook, (req, res, done) => {     als.runWith(() => {-      done()+      const asyncResource = new AsyncResource('fastify-request-context')+      req.asyncResource = asyncResource

I would probably store this in a symbol instead

kibertoad

comment created time in 9 hours

Pull request review commentfastify/fastify-request-context

Fix context loss when async storage is instantiated early in the request lifecycle

 const requestContext = { function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext)+  const hook = opts.hook || 'onRequest'

You should add

fastify.decorateRequest('asyncResource', null)
kibertoad

comment created time in 9 hours

push eventpinojs/hapi-pino

Adarsh K R

commit sha 72bec1076dca3209ed04c66fb0b46c719b5918f9

Filter out logs based on event tags (#115)

view details

push time in 9 hours

PR merged pinojs/hapi-pino

feat: Filter out logs based on event tags

Added a few feature - which enables us to filter the logs bases event tags.

+73 -2

6 comments

3 changed files

adarshkr

pr closed time in 9 hours

issue commentgoogleapis/nodejs-logging

pino plugin please

@naseemkullah I think so, yes! See https://www.npmjs.com/package/@elastic/ecs-pino-format as an example for a custom config for a specific cloud provider.

naseemkullah

comment created time in 11 hours

pull request commentpinojs/hapi-pino

feat: Filter out logs based on event tags

Can you rebase? This now conflicts with master.

adarshkr

comment created time in 11 hours

Pull request review commentfastify/fastify-request-context

Fix context loss when async storage is instantiated early in the request lifecycle

 function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext) -  fastify.addHook('onRequest', (req, res, done) => {+  fastify.addHook(opts.hook || 'onRequest', (req, res, done) => {

That's possible, the core request is available.

kibertoad

comment created time in 11 hours

push eventpinojs/hapi-pino

Paulo Vieira

commit sha 817dc7d2ad9519617f7be978848fc0508fd26ff5

feature: ignoreFunc (closes #112) (#116)

view details

push time in 11 hours

issue closedpinojs/hapi-pino

proposal for a new option: ignoreFunc

Currently hapi-pino provides ignorePaths and ignoreTags. They are useful to a certain degree, but for some cases it's still impossible to silent hapi-pino for some routes.

The use case I have in mind are routes for static files (which are usually defined with path: /foo/bar/{file*}). I want those to be silent. I can add a tag to these routes and use that tag in ignoreTags. That will work for the "request completed" log, however the "request start" log will still happen (because that log is defined in the onRequest extension point, and at that point the route is not yet located).

I'd like to propose a 3rd ignore option:

options.ignoreFunc: (options, Request) => boolean

It would be a simple addition to the internal isLoggingIgnored function: if option.ignoreFunc is present, it will execute and return the value; else, it will proceed with the current logic (which will check ignorePaths and ignoreTags, and also returns a boolean).

These 3 ignore options wouldn't be compatible obviously (either use ignorePaths/ignoreTags or ignoreFunc).

This way hapi-pino would provide the maximum flexibility to the user. If there's interest in this feature I would make a pr.

Thanks for considering.

closed time in 11 hours

paulovieira

PR merged pinojs/hapi-pino

feature: ignoreFunc (closes #112)
+168 -0

1 comment

3 changed files

paulovieira

pr closed time in 11 hours

Pull request review commentfastify/fastify-request-context

Fix context loss when async storage is instantiated early in the request lifecycle

 function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext) -  fastify.addHook('onRequest', (req, res, done) => {+  fastify.addHook(opts.hook || 'onRequest', (req, res, done) => {

I think you can call done of the callback form and get that expected result.

kibertoad

comment created time in 11 hours

Pull request review commentfastify/fastify-request-context

Fix context loss when async storage is instantiated early in the request lifecycle

 function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext) -  fastify.addHook('onRequest', (req, res, done) => {+  fastify.addHook(opts.hook || 'onRequest', (req, res, done) => {

Do you think that monkey-patching request EE from the plugin is an acceptable solution?

Not really. I think we should attach the context to fastify request and call the preValidation callback with that attached.

I think this can be done by manually doing something inside the 'preValidation' hook. @puzpuzpuz do you think it would be possible to create a custom AsyncResource there and restore it in that way?

kibertoad

comment created time in 12 hours

issue closedfastify/fastify-bearer-auth

Add option to exclude a list of routes or prefixes

<!-- Before you submit an issue we recommend you visit Fastify Help and ask any questions you have or mention any problems you've had getting started with Fastify.

Please read this entire template before posting any issue. If you ignore these instructions and post an issue here that does not follow the instructions, your issue might be closed, locked, and assigned the missing discussion label. -->

🚀 Feature Proposal

Add a new plugin option to exclude a list of routes prefixes from the auth check.

Motivation

Sometimes you want to have security set to all routes except 1 or few routes. This option will simplify this process and avoid to have to register the plugin for all the routes except the one you want to exclude.

I am currently working on a side project and I would like to have fastify-swagger enabled in a staging or test environment however still secure those.

Example

fastify.register(bearerAuthPlugin, {
    keys: new Set(keys),
    excludePrefixes: enableSwagger ? ['/documentation'] : undefined
});

closed time in 13 hours

francescorivola

issue commentpinojs/pino-elasticsearch

README: instructions in "Setup and Testing" are unclear

Does the docker-compose up command accept an argument for a custom docker compose config filename?

Yes, I think it is

docker-compose -f docker-compose-v7.yml up

But I can be wrong, take a look at the docs.

gr2m

comment created time in 13 hours

issue commentpinojs/pino-elasticsearch

replace `fast-json-parse` with JSON.parse()

send a PR, no real need

gr2m

comment created time in 13 hours

issue commentpinojs/pino-elasticsearch

README: instructions in "Setup and Testing" are unclear

But there is no docker-compose.yml file, there are currently five files starting matching docker-compose-*.yml. I'm not exactly sure what to do with that, maybe you could amend the instructions?

We use multiple docker-compose to test against different ElasticSearch versions. Can you send a PR to fix?

gr2m

comment created time in 13 hours

push eventfastify/fastify-routes-stats

dependabot-preview[bot]

commit sha 699a0f6987f318c81fe96c62a62eedceeb23a8b2

Bump summary from 1.0.0 to 2.0.0 (#19) Bumps [summary](https://github.com/AndreasMadsen/summary) from 1.0.0 to 2.0.0. - [Release notes](https://github.com/AndreasMadsen/summary/releases) - [Commits](https://github.com/AndreasMadsen/summary/commits) Signed-off-by: dependabot-preview[bot] <support@dependabot.com> Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>

view details

push time in 13 hours

PR merged fastify/fastify-routes-stats

Bump summary from 1.0.0 to 2.0.0 dependencies

Bumps summary from 1.0.0 to 2.0.0. <details> <summary>Commits</summary> <ul> <li>See full diff in <a href="https://github.com/AndreasMadsen/summary/commits">compare view</a></li> </ul> </details> <br />

Dependabot compatibility score

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.

Dependabot will merge this PR once CI passes on it, as requested by @mcollina.


Note: This repo was added to Dependabot recently, so you'll receive a maximum of 5 PRs for your first few update runs. Once an update run creates fewer than 5 PRs we'll remove that limit.

You can always request more updates by clicking Bump now in your Dependabot dashboard.

<details> <summary>Dependabot commands and options</summary> <br />

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot merge will merge this PR after your CI passes on it
  • @dependabot squash and merge will squash and merge this PR after your CI passes on it
  • @dependabot cancel merge will cancel a previously requested merge and block automerging
  • @dependabot reopen will reopen this PR if it is closed
  • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
  • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • @dependabot badge me will comment on this PR with code to add a "Dependabot enabled" badge to your readme

Additionally, you can set the following in the .dependabot/config.yml file in this repo:

  • Update frequency
  • Out-of-range updates (receive only lockfile updates, if desired)
  • Security updates (receive only security updates, if desired)

</details>

+1 -1

0 comment

1 changed file

dependabot-preview[bot]

pr closed time in 13 hours

pull request commentfastify/fastify

add PROJECT_CHARTER

Let's leave it like this and see if the CPC needs some changes first.

Eomm

comment created time in 13 hours

pull request commentpinojs/hapi-pino

feat: Filter out logs based on event tags

The build was successful. Just code coverage is dropped by 0.07% because of if check.

No worries

adarshkr

comment created time in 15 hours

pull request commentpinojs/hapi-pino

feat: Filter out logs based on event tags

CI is failing, can you take a look?

adarshkr

comment created time in a day

issue commentnodejs/node

Absolute Windows paths are handled as invalid URL path in ESM import()

cc @nodejs/modules

StarpTech

comment created time in a day

pull request commentfastify/fastify

add PROJECT_CHARTER

@Eomm this should have had approval by the OpenJS Foundation CPC before landing :)

Eomm

comment created time in a day

issue commentmcollina/undici

Pre-connecting

@ronag I think that's not sustainable. Most load balancer would consider this similar to DoS attack

ronag

comment created time in a day

Pull request review commentfastify/fastify

Test: reach 100% coverage

 test('stream with content type should not send application/octet-stream', t => {   }) }) +// test('stream should log error when headers sent but not body', t => {+//   t.plan(6)++//   const fastify = require('../..')()+//   const fs = require('fs')+//   const path = require('path')++//   var streamPath = path.join(__dirname, '..', '..', 'package.json')+//   var stream = fs.createReadStream(streamPath)+//   // var buf = fs.readFileSync(streamPath)++//   fastify.get('/', function (req, reply) {+//     reply.log.warn = function mockWarn (message) {+//       t.equal(message, 'response will send, but you shouldn\'t use res.writeHead in stream mode')+//     }+//     reply.raw.writeHead(200, {+//       location: '/'+//     })++//     reply.raw.close()+//     reply.send(stream)+//   })++//   fastify.listen(0, err => {+//     t.error(err)+//     fastify.server.unref()+//     sget({+//       method: 'GET',+//       url: 'http://localhost:' + fastify.server.address().port+//     // eslint-disable-next-line handle-callback-err+//     }, (err, response, body) => {+//       // t.error(err)+//       // t.strictEqual(response.headers.location, '/')+//       // t.strictEqual(response.headers['Content-Type'], undefined)+//       // t.deepEqual(body, buf)+//     })+//   })+// })

remove?

MetCoder95

comment created time in a day

Pull request review commentfastify/fastify

Test: reach 100% coverage

 test('onClose should keep the context', t => {   }) }) -test('Should return error while closing - injection', t => {+test('Should return error while closing (promise) - injection', t => {+  t.plan(4)+  const fastify = Fastify()++  fastify.addHook('onClose', (instance, done) => {+    setTimeout(done, 150)

+1

MetCoder95

comment created time in a day

pull request commentfastify/fastify-cookie

ability to filter out requests / avoid setting cookie header

Can you please describe a bit your setup? Have you got some routes you need to send the cookies and some routes you don't?

patrickmichalina

comment created time in a day

pull request commentfastify/fastify-cookie

ability to filter out requests / avoid setting cookie header

Normally filtering is expensive compared to do something only when needed. Can you please articulate why you can't just avoid to call setCookie() when you do not need it? Also why would you not create a new decorator that wrapped reply.setCookie() and apply that filtering?

patrickmichalina

comment created time in a day

created tagpinojs/pino

tagv6.5.1

🌲 super fast, all natural json logger 🌲

created time in a day

release pinojs/pino

v6.5.1

released time in a day

push eventpinojs/pino

Matteo Collina

commit sha 95856d1198a4067f9916a2b7e636b71f58bebeb2

Bumped v6.5.1

view details

push time in a day

issue commentgoogleapis/nodejs-logging

pino plugin please

I'm happy to assist/review.

naseemkullah

comment created time in a day

startedmikeal/dagdb

started time in a day

push eventmcollina/sonic-boom

Matteo Collina

commit sha 3b773bcdf8ac1ca63fb009b1cff9eaa0048318f5

Bumped v1.0.3

view details

push time in a day

issue commentfastify/fastify-bearer-auth

Add TypeScript definitions

Yes!

ricardo-devis-agullo

comment created time in a day

issue closedfastify/fastify-bearer-auth

Add TypeScript definitions

🚀 Feature Proposal

Add an index.d.ts with Typescript type definitions.

Motivation

To use it on Typescript projects.

I can do a PR for this if you are ok with it.

closed time in a day

ricardo-devis-agullo

pull request commentfastify/fastify

Adds support for named imports in ESM context

I think we could close this for now as it seems we will be waiting until exports is more mature.

fox1t

comment created time in a day

issue commentnearform/graphql-hooks

TypeError: Cannot read property 'useGETForQueries' of undefined

We are currently quite busy. If you send a PR we'll be happy to review, otherwise it would have to wait for a bit.

medev21

comment created time in a day

Pull request review commentfastify/fastify-request-context

Support specifying alternate hook for the plugin

 function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext) -  fastify.addHook('onRequest', (req, res, done) => {+  fastify.addHook(opts.hook || 'onRequest', (req, res, done) => {

onRequest happens before preValidation.

I don't think it should be reinitialized, but probably something must be done to retain the context.

kibertoad

comment created time in a day

Pull request review commentfastify/fastify-request-context

Support specifying alternate hook for the plugin

+const fastify = require('fastify')+const request = require('superagent')+const { fastifyRequestContextPlugin } = require('../lib/requestContextPlugin')+const { TestService } = require('./internal/testService')++function initAppPostWithPrevalidation(endpoint) {+  return new Promise((resolve) => {+    const app = fastify({ logger: true })+    app.register(fastifyRequestContextPlugin, { hook: 'preValidation' })++    const preValidationFn = (req, reply, done) => {+      const requestId = Number.parseInt(req.body.requestId)+      req.requestContext.set('testKey', `testValue${requestId}`)+      done()+    }++    app.route({+      url: '/',+      method: ['GET', 'POST'],+      preValidation: preValidationFn,+      handler: endpoint,+    })++    app.listen(8085, '0.0.0.0', (err, address) => {+      if (err) {+        console.warn(err)+        process.exit(1)+      }+      console.info(`Server listening at ${address}`)+      resolve(app)+    })+  })+}++describe('requestContextPlugin E2E', () => {+  let app+  afterEach(() => {+    return app.close()+  })++  it('correctly preserves values set in prevalidation phase within single POST request', () => {+    expect.assertions(2)++    let testService+    let responseCounter = 0+    return new Promise((resolveResponsePromise) => {+      const promiseRequest2 = new Promise((resolveRequest2Promise) => {+        const promiseRequest1 = new Promise((resolveRequest1Promise) => {

oh ok.

kibertoad

comment created time in a day

issue commentfastify/fastify-autoload

error with esm on windows

@StarpTech can you open an issue on node core on this and tag me on it? Thanks. This is very confusing.

amis-shokoohi

comment created time in a day

issue closedfastify/fastify-autoload

error with esm on windows

I was following @mcollina tutorial for Fastify, and I faced with an error related to fastify-autoload plugin:

Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:781:11)
    at Loader.resolve (internal/modules/esm/loader.js:85:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)
    at Loader.import (internal/modules/esm/loader.js:164:28)
    at importModuleDynamically (internal/modules/cjs/loader.js:1199:27)
    at exports.importModuleDynamicallyCallback (internal/process/esm_loader.js:30:14)
    at loadPlugin (C:\Users\amis\Desktop\fastify3-test\node_modules\fastify-autoload\index.js:117:5)
    at C:\Users\amis\Desktop\fastify3-test\node_modules\fastify-autoload\index.js:27:12
    at Array.map (<anonymous>)
    at fastifyAutoload (C:\Users\amis\Desktop\fastify3-test\node_modules\fastify-autoload\index.js:26:29) {
  code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
}

I'm running Node v14.7.0 on Windows 10. This is how the app looks like:

app.js
import fastify from 'fastify'
import autoload from 'fastify-autoload'
import { join } from 'desm'

export default function (opts) {
    const app = fastify(opts)

    app.register(autoload, {
        dir: join(import.meta.url, 'routes')
    })

    return app
}
/routes/hello.js
export default async function (app) {
    app.get('/', async function (req, rep) {
        return { hello: 'world' }
    })
}

closed time in a day

amis-shokoohi

issue commentfastify/fastify-autoload

error with esm on windows

Released as v3.0.8!

amis-shokoohi

comment created time in a day

created tagfastify/fastify-autoload

tagv3.0.8

Require all plugins in a directory

created time in a day

release fastify/fastify-autoload

v3.0.8

released time in a day

push eventfastify/fastify-autoload

Matteo Collina

commit sha 1f65f5a5a9c3655f9ae0dc6284927d1279462dc0

Bumped v3.0.8

view details

push time in a day

Pull request review commentfastify/fastify-request-context

Support specifying alternate hook for the plugin

+const fastify = require('fastify')+const request = require('superagent')+const { fastifyRequestContextPlugin } = require('../lib/requestContextPlugin')+const { TestService } = require('./internal/testService')++function initAppPostWithPrevalidation(endpoint) {+  return new Promise((resolve) => {+    const app = fastify({ logger: true })+    app.register(fastifyRequestContextPlugin, { hook: 'preValidation' })++    const preValidationFn = (req, reply, done) => {+      const requestId = Number.parseInt(req.body.requestId)+      req.requestContext.set('testKey', `testValue${requestId}`)+      done()+    }++    app.route({+      url: '/',+      method: ['GET', 'POST'],+      preValidation: preValidationFn,+      handler: endpoint,+    })++    app.listen(8085, '0.0.0.0', (err, address) => {+      if (err) {+        console.warn(err)+        process.exit(1)+      }+      console.info(`Server listening at ${address}`)+      resolve(app)+    })+  })+}++describe('requestContextPlugin E2E', () => {+  let app+  afterEach(() => {+    return app.close()+  })++  it('correctly preserves values set in prevalidation phase within single POST request', () => {+    expect.assertions(2)++    let testService+    let responseCounter = 0+    return new Promise((resolveResponsePromise) => {+      const promiseRequest2 = new Promise((resolveRequest2Promise) => {+        const promiseRequest1 = new Promise((resolveRequest1Promise) => {

please use async functions instead.

kibertoad

comment created time in a day

Pull request review commentfastify/fastify-request-context

Support specifying alternate hook for the plugin

+const fastify = require('fastify')+const request = require('superagent')+const { fastifyRequestContextPlugin } = require('../lib/requestContextPlugin')+const { TestService } = require('./internal/testService')++function initAppPostWithPrevalidation(endpoint) {+  return new Promise((resolve) => {+    const app = fastify({ logger: true })+    app.register(fastifyRequestContextPlugin, { hook: 'preValidation' })++    const preValidationFn = (req, reply, done) => {+      const requestId = Number.parseInt(req.body.requestId)+      req.requestContext.set('testKey', `testValue${requestId}`)+      done()+    }++    app.route({+      url: '/',+      method: ['GET', 'POST'],+      preValidation: preValidationFn,+      handler: endpoint,+    })++    app.listen(8085, '0.0.0.0', (err, address) => {

please set 0 as the port and use app.server.address() to get the actual port. There is no need to use 0.0.0.0 either.

kibertoad

comment created time in a day

Pull request review commentfastify/fastify-request-context

Support specifying alternate hook for the plugin

 function plugin(fastify, opts, next) {   fastify.decorate('requestContext', requestContext)   fastify.decorateRequest('requestContext', requestContext) -  fastify.addHook('onRequest', (req, res, done) => {+  fastify.addHook(opts.hook || 'onRequest', (req, res, done) => {

I think we might want to run this on multiple hooks as well, maybe it should be an array?

kibertoad

comment created time in a day

Pull request review commentfastify/fastify-request-context

Support specifying alternate hook for the plugin

+const fastify = require('fastify')+const request = require('superagent')+const { fastifyRequestContextPlugin } = require('../lib/requestContextPlugin')+const { TestService } = require('./internal/testService')++function initAppPostWithPrevalidation(endpoint) {+  return new Promise((resolve) => {

Do not wrap with a promise, use an async function. .listen() returns a promise if a callback is not passed in.

kibertoad

comment created time in a day

Pull request review commentmcollina/undici

fix: buffer check for jest

 function parseHeaders (headers, obj) {   return obj } +function isBuffer (buffer) {+  // See, https://github.com/mcollina/undici/pull/319+  return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)

I'm totally lost on why Buffer.isBuffer would work, but hey.

timsuchanek

comment created time in a day

Pull request review commentmcollina/undici

fix: buffer check for jest

+'use strict'++const { Client } = require('../..')+const { createServer } = require('http')+/* global test, expect */++test('should work in jest', async () => {+  const server = createServer((req, res) => {+    expect(req.url).toBe('/')+    expect(req.method).toBe('POST')+    expect(req.headers.host).toBe('localhost')+    res.setHeader('Content-Type', 'text/plain')+    res.end('hello')+  })+  await new Promise((resolve, reject) => {+    server.listen(0, async () => {

please just wrap server listen in a Promise, and do not use async functions inside new Promise.

timsuchanek

comment created time in a day

delete branch mcollina/sonic-boom

delete branch : small-perf

delete time in a day

push eventmcollina/sonic-boom

Matteo Collina

commit sha a2990472464a4d7cd07fb1826e233c70f135a7e6

Small perf improvement (5%) in sync mode (#42)

view details

push time in a day

PR opened mcollina/sonic-boom

Small perf improvement (5%) in sync mode
+11 -2

0 comment

2 changed files

pr created time in a day

push eventfastify/fastify-autoload

Amis Shokoohi

commit sha 9284b2dfa8388538c243dab76b38941d95c2b25a

Fixed "error with esm on windows #98" issue (#99)

view details

push time in a day

issue commentfastify/fastify-autoload

error with esm on windows

why the heck this works on Mac and Linux then? :)

amis-shokoohi

comment created time in a day

issue commentmcollina/undici

Doesn't work within jest

I would highly recommend to not use jest as it provides different globals for each test, making all those check fail. Anyway, a fix would be welcomed. Please also add a test for it.

timsuchanek

comment created time in a day

issue closedfastify/fastify

Refer to tsconfig/bases in typescript docs

🚀 Feature Proposal

https://github.com/tsconfig/bases includes the default examples for the fastify configuration. We should recommend it in our typescript documentation, and possibly use the relevant one across all of our plugins.

closed time in a day

mcollina

issue commentmcollina/undici

Pre-connecting

We'll need to predict when a slot will become free and if it is convenient to spawn a new socket or wait for one to become free. We would need to keep track the interval between two consecutive requests and how long it will take to serve them (ideally with hdr-histogram). We can then use the poisson distribution to model those phenomenons. Then use some math based on probability to compute a decision where to create a new socket or wait for one to become free. The whole algorithm must be incredibly fast, otherwise it would negate any benefits.

ronag

comment created time in a day

issue commentfastify/fastify-autoload

error with esm on windows

sure. I don't 100% understand the problem, but +1

amis-shokoohi

comment created time in a day

push eventpinojs/pino

Matteo Collina

commit sha 6c587ea7cdb8a429225c6f4f198829d58f76a41f

Update deps (#894) * Updated deps (execa) * updated through2 * Updated tape * updated airtap

view details

push time in a day

PR merged pinojs/pino

Update deps

As titled

+13 -13

0 comment

1 changed file

mcollina

pr closed time in a day

issue commentfastify/fastify-autoload

error with esm on windows

Nice, as supposed it worked! Now it would be nice to know why it was missing in the first place. Any clouds @mcollina ?

No idea. The above code is exactly doing what desm is doing. See

https://github.com/mcollina/desm/blob/master/index.js

amis-shokoohi

comment created time in a day

create barnchmcollina/sonic-boom

branch : small-perf

created branch time in 2 days

issue commentmcollina/fastify-gql

external subscriber

Can you please send a PR? I don't really understand the difference between that and what is in the repo.


I imagine the change to alter https://github.com/mcollina/fastify-gql/blob/60ef01f8ce82522403e6088c7dabd71e9d293bdc/lib/subscriber.js#L10 so that it calls itself multiple times for all the topics. An end user can quickly implement it as well with a Promise.all.

gtolarc

comment created time in 2 days

PR opened pinojs/pino

Reviewers
Update deps

As titled

+13 -13

0 comment

1 changed file

pr created time in 2 days

create barnchpinojs/pino

branch : update-deps

created branch time in 2 days

push eventpinojs/pino

Jesse Friedman

commit sha 62d5c6c9e72724cbf15701ee95dcd4d8acbee745

Clear cached parsed chindings when they're changed with .setBindings (fixes #890) (#893)

view details

push time in 2 days

PR merged pinojs/pino

Clear cached parsed chindings when they're changed with .setBindings

This fixes #890; see that issue for discussion.

+24 -0

0 comment

3 changed files

okofish

pr closed time in 2 days

issue closedpinojs/pino

logger.setBindings() doesn't clear logger[Symbol(pino.parsedChindings)]

#754 added a very useful logger.setBindings() method. But this doesn't play well with prettifiers, which appear to make use of a cached version of the bindings:

> let child=logger.child({foo: 123});

// pino.parsedChindings is undefined at start
> child.bindings()
{ foo: 123 }
> child[Pino.symbols.parsedChindingsSym]
undefined

// when the first log call is made, pino.parsedChindings gets populated
> child.info('hello')
[2020-08-11 23:12:27.349 +0000] INFO : hello
    foo: 123
> child[Pino.symbols.parsedChindingsSym]
{ pid: 16561, hostname: 'nutrimatic', foo: 123 }

// logger.setBindings doesn't update pino.parsedChindings
> child.setBindings({bar: 456})
> child.bindings()
{ foo: 123, bar: 456 }
> child[Pino.symbols.parsedChindingsSym]
{ pid: 16561, hostname: 'nutrimatic', foo: 123 }

// so subsequent logs don't include the new bindings
> child.info('hello')
[2020-08-11 23:13:24.553 +0000] INFO : hello
    foo: 123
> child[Pino.symbols.parsedChindingsSym]
{ pid: 16561, hostname: 'nutrimatic', foo: 123 }

// manually clearing pino.parsedChindings causes it to be regenerated on the next log call
> delete child[Pino.symbols.parsedChindingsSym]
> child.info('hello')
[2020-08-11 23:14:28.240 +0000] INFO : hello
    foo: 123
    bar: 456
> child[Pino.symbols.parsedChindingsSym]
{ pid: 16561, hostname: 'nutrimatic', foo: 123, bar: 456 }

Would it be "safe" (performance-wise) to have logger.setBindings() automatically clear pino.parserChindings so that the next log call causes it to update? I think this may be OK since said updating only happens when a prettifier is enabled, so it won't impact production situations where there's no prettifier. Alternatively, could we add an additional method that manually clears pino.parserChindings?

I can submit a PR for either of these approaches; I'm just not sure which is best.

closed time in 2 days

okofish

Pull request review commentpinojs/pino

Clear cached parsed chindings when they're changed with .setBindings

+global.process = { __proto__: process, pid: 123456 }+Date.now = function () { return 1459875739796 }+require('os').hostname = function () { return 'abcdefghijklmnopqr' }+var pino = require(require.resolve('./../../../'))+var log = pino({ prettyPrint: true }).child({ foo: 123 })+log.info('before')+log.setBindings({ foo: 456, bar: 789 })

Maybe it should be documented, anyway this PR does not add it.

okofish

comment created time in 2 days

Pull request review commentmcollina/undici

perf: improved pool balancing

 class Pool {       throw new InvalidArgumentError('invalid connections')     } +    this[kQueue] = []+    this[kPendingIdx] = 0     this[kClients] = Array.from({       length: connections || 10     }, () => new Client(url, options))++    for (const client of this[kClients]) {+      client.on('drain', () => {

Yes, something like client.on('drain', onDrain(this))

ronag

comment created time in 2 days

Pull request review commentmcollina/undici

perf: improved pool balancing

 class Pool {       throw new InvalidArgumentError('invalid connections')     } +    this[kQueue] = []+    this[kPendingIdx] = 0     this[kClients] = Array.from({       length: connections || 10     }, () => new Client(url, options))++    for (const client of this[kClients]) {+      client.on('drain', () => {

you don't need it, it is this in the function (if you remove the arrow).

ronag

comment created time in 2 days

push eventfastify/fastify

Maksim Sinik

commit sha 102654ecd9957035fcfe58958752314c0e6ede91

Adds support for plugin dynamic imports in TS projects (#2494)

view details

push time in 2 days

PR merged fastify/fastify

Adds support for plugin dynamic imports in TS projects

Fixes: https://github.com/fastify/fastify/issues/2403 The issue was because dynamic import in Typescript always imports an object that have .default property instead of assigning the default export to "top" level. In fact the compiler outputs this JS

fastify.register(Promise.resolve().then(() => __importStar(require("fastify-formbody"))));

for this ts

fastify.register(import("fastify-formbody"));

It compiles it like this because import() is implemented using require() and promises.

This PR works thanks to https://github.com/fastify/avvio/blob/76f83492819c0cbc64e6a255e92df11fe4f094fb/plugin.js#L245 that works if an object with .default property is passed.

Checklist

+13 -1

0 comment

3 changed files

fox1t

pr closed time in 2 days

issue closedfastify/fastify

ESM-style plugin import doesn't pass TypeScript type check.

🐛 Bug Report

To Reproduce

Pick any Fastify plugin (I'll use fastify-formbody for now):

fastify().register(import('fastify-formbody'));

TypeScript compiler gives the following error:

No overload matches this call.
  Overload 1 of 3, '(plugin: FastifyPluginCallback<FastifyPluginOptions>, opts?: FastifyRegisterOptions<FastifyPluginOptions>): FastifyInstance<...> & PromiseLike<...>', gave the following error.
    Argument of type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to parameter of type 'FastifyPluginCallback<FastifyPluginOptions>'.
      Type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' provides no match for the signature '(instance: FastifyInstance<RawServerBase, IncomingMessage | Http2ServerRequest, ServerResponse | Http2ServerResponse, FastifyLoggerInstance>, opts: FastifyPluginOptions, next: (err?: Error) => void): void'.
  Overload 2 of 3, '(plugin: FastifyPluginAsync<FastifyPluginOptions>, opts?: FastifyRegisterOptions<FastifyPluginOptions>): FastifyInstance<...> & PromiseLike<...>', gave the following error.
    Argument of type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to parameter of type 'FastifyPluginAsync<FastifyPluginOptions>'.
      Type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' provides no match for the signature '(instance: FastifyInstance<RawServerBase, IncomingMessage | Http2ServerRequest, ServerResponse | Http2ServerResponse, FastifyLoggerInstance>, opts: FastifyPluginOptions): Promise<...>'.
  Overload 3 of 3, '(plugin: FastifyPluginCallback<FastifyPluginOptions> | FastifyPluginAsync<FastifyPluginOptions>, opts?: FastifyRegisterOptions<...>): FastifyInstance<...> & PromiseLike<...>', gave the following error.
    Argument of type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to parameter of type 'FastifyPluginCallback<FastifyPluginOptions> | FastifyPluginAsync<FastifyPluginOptions>'.
      Type 'Promise<typeof import(".../node_modules/fastify-formbody/formbody")>' is not assignable to type 'FastifyPluginAsync<FastifyPluginOptions>'.

Expected behavior

There should be no errors.

We can use as any to bypass this problem but not sure it's the best thing to do.

Your Environment

  • node version: 14
  • fastify version: 3.0.1
  • os: Mac

closed time in 2 days

hongyiweiwu
more