Skip to content

Commit 44c52d9

Browse files
isaacsJPeer264
authored andcommitted
feat: pg orchestrion instrumentation
Add orchestrion instrumentation for Node, Deno, and Bun, covering the `pg` module. This basically copies exactly what the `mysql` integration does, but for postgres. fix: #20764 fix: JS-2415
1 parent efc96b1 commit 44c52d9

3 files changed

Lines changed: 194 additions & 0 deletions

File tree

‎packages/deno/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@
3131
"@sentry/core": "10.63.0",
3232
"@sentry/server-utils": "10.63.0"
3333
},
34+
"devDependencies": {
35+
"mysql": "^2.18.1",
36+
"pg": "8.16.0"
37+
},
3438
"scripts": {
3539
"deno-types": "node ./scripts/download-deno-types.mjs",
3640
"build": "run-s build:transpile build:types",
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
// <reference lib="deno.ns" />
2+
3+
import { tracingChannel } from 'node:diagnostics_channel';
4+
import type { TransactionEvent } from '@sentry/core';
5+
import { assert } from 'https://deno.land/std@0.212.0/assert/assert.ts';
6+
import { assertEquals } from 'https://deno.land/std@0.212.0/assert/assert_equals.ts';
7+
import { assertExists } from 'https://deno.land/std@0.212.0/assert/assert_exists.ts';
8+
import type { DenoClient } from '../build/esm/index.js';
9+
import { getCurrentScope, getGlobalScope, getIsolationScope, init, startSpan } from '../build/esm/index.js';
10+
11+
function resetGlobals(): void {
12+
getCurrentScope().clear();
13+
getCurrentScope().setClient(undefined);
14+
getIsolationScope().clear();
15+
getGlobalScope().clear();
16+
}
17+
18+
/** See `deno-redis.test.ts` same sink shape, deduped for clarity. */
19+
function transactionSink(): {
20+
beforeSendTransaction: (event: TransactionEvent) => null;
21+
waitFor: (predicate: (event: TransactionEvent) => boolean) => Promise<TransactionEvent>;
22+
} {
23+
const transactions: TransactionEvent[] = [];
24+
const waiters: { predicate: (e: TransactionEvent) => boolean; resolve: (e: TransactionEvent) => void }[] = [];
25+
return {
26+
beforeSendTransaction(event) {
27+
transactions.push(event);
28+
for (let i = waiters.length - 1; i >= 0; i--) {
29+
const w = waiters[i]!;
30+
if (w.predicate(event)) {
31+
waiters.splice(i, 1);
32+
w.resolve(event);
33+
}
34+
}
35+
return null;
36+
},
37+
waitFor(predicate) {
38+
const already = transactions.find(predicate);
39+
if (already) return Promise.resolve(already);
40+
return new Promise<TransactionEvent>(resolve => {
41+
waiters.push({ predicate, resolve });
42+
});
43+
},
44+
};
45+
}
46+
47+
function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {
48+
let timer: ReturnType<typeof setTimeout> | undefined;
49+
const timeout = new Promise<T>((_, reject) => {
50+
timer = setTimeout(() => reject(new Error(`Timed out waiting for ${what} after ${ms}ms`)), ms);
51+
});
52+
return Promise.race([p, timeout]).finally(() => {
53+
if (timer !== undefined) clearTimeout(timer);
54+
});
55+
}
56+
57+
Deno.test('denoPostgresIntegration: included in default integrations (Deno 2.8.0+)', () => {
58+
resetGlobals();
59+
const client = init({ dsn: 'https://username@domain/123' }) as DenoClient;
60+
const names = client.getOptions().integrations.map(i => i.name);
61+
assert(names.includes('DenoPostgres'), `DenoPostgres should be in defaults, got ${names.join(', ')}`);
62+
});
63+
64+
// The orchestrion runtime hook (`@sentry/deno/import`) only works as a FIRST
65+
// import inside the entry graph in Deno 2.8.0 through 2.8.2.
66+
// TODO: revisit a `--import` or `--preload` approach once Deno 2.8.3 ships.
67+
Deno.test('@sentry/deno/import: transforms pg so it publishes the orchestrion channel', async () => {
68+
const scenario = new URL('./orchestrion-postgres/scenario.mjs', import.meta.url);
69+
70+
// packages/deno, where node_modules resolves
71+
const cwd = new URL('../', import.meta.url);
72+
73+
const command = new Deno.Command('deno', {
74+
args: ['run', '--allow-all', scenario.pathname],
75+
cwd: cwd.pathname,
76+
stdout: 'piped',
77+
stderr: 'piped',
78+
});
79+
80+
const { code, stdout, stderr } = await command.output();
81+
const out = new TextDecoder().decode(stdout);
82+
const err = new TextDecoder().decode(stderr);
83+
84+
assertEquals(code, 0, `scenario exited ${code}\nstdout:\n${out}\nstderr:\n${err}`);
85+
86+
const line = out.split('\n').find(l => l.startsWith('SCENARIO')) ?? '';
87+
assert(line, `no SCENARIO line in output:\n${out}\nstderr:\n${err}`);
88+
// The injected channel fired on `client.query()`
89+
// proves pg was transformed...
90+
assert(line.includes('events=start'), `expected channel 'start' event, got: ${line}`);
91+
// ...with the real SQL forwarded through the channel context.
92+
assert(line.includes('statement=SELECT 1 AS solution'), `expected forwarded SQL, got: ${line}`);
93+
// The runtime hook set its detection marker at boot.
94+
assert(line.includes('"runtime":true'), `expected runtime marker, got: ${line}`);
95+
});
96+
97+
// Exercises the SDK path e2e: `init()` wires `denoPostgresIntegration`
98+
// (which installs the AsyncLocalStorage context strategy and subscribes to
99+
// the channel), and we drive the `orchestrion:pg:query` channel manually,
100+
// the same events the orchestrion transform publishes around
101+
// `client.query()`, so no live database is needed. Asserting a nested `db`
102+
// span proves the subscriber, the emitted attributes, AND the
103+
// context-strategy wiring all work.
104+
Deno.test('denoPostgresIntegration: orchestrion:pg:query channel produces a nested db span', async () => {
105+
resetGlobals();
106+
const sink = transactionSink();
107+
init({
108+
dsn: 'https://username@domain/123',
109+
tracesSampleRate: 1,
110+
beforeSendTransaction: sink.beforeSendTransaction,
111+
});
112+
113+
const channel = tracingChannel('orchestrion:pg:query');
114+
115+
// The shared context object orchestrion reuses across the lifecycle events
116+
//
117+
// `arguments[0]` is the SQL; `self.connectionParameters` is pg's resolved
118+
// connection config.
119+
const ctx = {
120+
arguments: ['SELECT 1 AS solution'],
121+
self: { connectionParameters: { host: '127.0.0.1', port: 5432, database: 'mydb', user: 'root' } },
122+
};
123+
124+
// Callback-success order published by orchestrion's transform:
125+
// start -> end -> asyncStart -> asyncEnd (the span closes on asyncEnd).
126+
startSpan({ name: 'parent', op: 'test' }, () => {
127+
channel.start.runStores(ctx, () => {
128+
channel.end.publish(ctx);
129+
});
130+
channel.asyncStart.runStores(ctx, () => {
131+
channel.asyncEnd.publish(ctx);
132+
});
133+
});
134+
135+
const parent = await withTimeout(
136+
sink.waitFor(t => t.transaction === 'parent'),
137+
5000,
138+
"'parent' transaction",
139+
);
140+
141+
const pgSpan = parent.spans?.find(s => s.op === 'db');
142+
assertExists(pgSpan, `expected a db child span, got ops: ${parent.spans?.map(s => s.op).join(', ')}`);
143+
assertEquals(pgSpan!.description, 'SELECT 1 AS solution');
144+
assertEquals(pgSpan!.data?.['db.system'], 'postgresql');
145+
assertEquals(pgSpan!.data?.['db.statement'], 'SELECT 1 AS solution');
146+
assertEquals(pgSpan!.data?.['net.peer.name'], '127.0.0.1');
147+
assertEquals(pgSpan!.data?.['net.peer.port'], 5432);
148+
assertEquals(pgSpan!.data?.['db.user'], 'root');
149+
assertEquals(pgSpan!.data?.['sentry.origin'], 'auto.db.orchestrion.postgres');
150+
});
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Spawned by orchestrion-postgres.test.ts via `deno run`.
2+
//
3+
// Importing `@sentry/deno/import` FIRST registers the orchestrion module hook,
4+
// so the subsequent `pg` import is transformed to publish to the
5+
// `orchestrion:pg:query` tracing channel. `client.query()` publishes `start`
6+
// synchronously, so no live database is needed.
7+
import '@sentry/deno/import';
8+
9+
import { tracingChannel } from 'node:diagnostics_channel';
10+
const { default: pg } = await import('pg');
11+
12+
const events = [];
13+
let statement = '';
14+
15+
tracingChannel('orchestrion:pg:query').subscribe({
16+
start(message) {
17+
events.push('start');
18+
const first = message?.arguments?.[0];
19+
statement = typeof first === 'string' ? first : '';
20+
},
21+
end() {
22+
events.push('end');
23+
},
24+
asyncStart() {},
25+
asyncEnd() {
26+
events.push('asyncEnd');
27+
},
28+
error() {},
29+
});
30+
31+
const client = new pg.Client({ host: '127.0.0.1', user: 'root', database: 'mydb' });
32+
try {
33+
client.query('SELECT 1 AS solution', () => {});
34+
} catch {
35+
// No live server, `start` has already published synchronously by now.
36+
}
37+
38+
const marker = globalThis.__SENTRY_ORCHESTRION__ ?? null;
39+
// eslint-disable-next-line no-console
40+
console.log(`SCENARIO events=${events.join(',')} statement=${statement} marker=${JSON.stringify(marker)}`);

0 commit comments

Comments
 (0)