Skip to content

async with AsyncHook doesn't propagate context properly. #4125

@obecny

Description

@obecny

Environment

Knex version: ^0.21.6
Database + version: postgresql 12,13
OS: osx
Node: 8,10,12,14,15

Bug

Context is lost when using async
1.

      const movies = await knex('movies').select('*')
      ctx.body = {
        status: 'success',
        data: movies
      }

Versus
2.

      const p = knex('movies').select('*')
      return p.then((movies)=> {
        ctx.body = {
          status: 'success',
          data: movies
        }
      })

This is based on this test app
https://github.com/akshah123/koa-test-app

More context
When using opentelemetry with postgres, knex and koa the spans generated by pg plugin are not tied to spans generated in koa plugin. This is because await knex('movies').select('*') doesn't propagate correctly the context when using AsyncHook. It works only when using AsyncLocalStorage from async_hooks which is not available in earliest version of node. The only alternative for older node seems to be to use "Promise based approach" (point 2). Also AsyncLocalStorage had some other bugs and can be treated as "stable" for node version >= 14.8.0. This means for all other version AsyncHook is being used and then have this bug.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions