Add diagnostics_channel TracingChannel support
This PR introduces tracing channels support to pg-pool and pg querying methods as discussed in #3619
I haven't yet run a benchmark, but without active tracing or subscribers the overhead is non-existent so existing users shouldn't be affected. The overhead would come from the consumers of the diag channels published here which is done anyways via monkey patching.
I added the following channels:
| Channel | Type | Package | Description |
|---|---|---|---|
pg:query | TracingChannel | pg | Query lifecycle (start, end, error with async context) |
pg:connection | TracingChannel | pg | Client connection lifecycle |
pg:pool:connect | TracingChannel | pg-pool | Pool connection acquisition lifecycle |
pg:pool:release | Channel | pg-pool | Client released back to pool |
pg:pool:remove | Channel | pg-pool | Client removed from pool |
I understand there may be hesitation given that AI tooling was used in the implementation. To be clear, this isn't a drive-by contribution. I designed the channel layout, wrote the proposal document, and iterated through multiple rounds to handle real edge cases (Node 18 compat, preserving custom Promise types, hasSubscribers guards). The AI assisted with the code, but the approach and decisions are mine.
Usage
Instrumentations will only need to subscribe to tracing channels to create traces, logs or metrics:
import { tracingChannel } from 'diagnostics_channel'
tracingChannel('pg:query').subscribe({
start({ query, client }) {
// start span
// query: { text, name, rowMode }
// client: { database, host, port, user, processID, ssl }
},
asyncEnd({ query, result }) {
// end span
// result: { rowCount, command }
},
error({ query, error }) {
// record error on span
},
})
This is part of a broader initiative to bring TracingChannel support to the most widely used Node.js database and cache libraries. The same pattern has already been merged and shipped in:
I have been directly involved in those prior implementations and I'm happy to own this through to release, address any feedback, and provide whatever support is needed. Would love to hear your thoughts.
Supersedes #3624.
Summary by cubic
Adds TracingChannel support to pg and pg-pool so instrumentation libraries can subscribe to query and connection lifecycle events without monkey-patching.
- Exposes
pg:query,pg:connection, andpg:pool:connectTracingChannels pluspg:pool:releaseandpg:pool:removechannels. - Emits structured context (query details, client info, result metadata) and guards publishing with a
shouldTracecheck so there's no overhead when no subscribers exist. - Handles Node 18's missing aggregated
hasSubscribersgetter by treatingundefinedas possibly subscribed, and usestraceCallbackinstead oftracePromiseto preserve custom Promise types.