Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions dev-packages/node-integration-tests/suites/tracing/neon/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,14 @@ function expectedDbSpan({
statement,
status = 'ok',
batchSize,
returnedRows,
}: {
name: string;
operation: string;
statement: string;
status?: 'ok' | 'error';
batchSize?: number;
returnedRows?: number;
}): unknown {
return expect.objectContaining({
attributes: expect.objectContaining({
Expand All @@ -56,6 +58,7 @@ function expectedDbSpan({
[DB_QUERY_SUMMARY]: attr(name),
[DB_OPERATION_NAME]: attr(operation),
...(batchSize ? { [DB_OPERATION_BATCH_SIZE]: attr(batchSize, 'integer') } : {}),
...(returnedRows !== undefined ? { 'db.response.returned_rows': attr(returnedRows, 'integer') } : {}),
}),
is_segment: false,
name,
Expand Down Expand Up @@ -91,30 +94,44 @@ describeWithDockerCompose('neon auto instrumentation', { workingDirectory: [__di
const neonSpans = getNeonSpans(spans);
expect(neonSpans.every(span => span.parent_span_id === segment!.span_id)).toBe(true);
expect(neonSpans).toEqual([
expectedDbSpan({ name: 'CREATE TABLE "User"', operation: 'CREATE', statement: CREATE_USER_TABLE_STATEMENT }),
expectedDbSpan({
name: 'CREATE TABLE "User"',
operation: 'CREATE',
statement: CREATE_USER_TABLE_STATEMENT,
returnedRows: 0,
}),
// Without `fullResults` a query resolves to its rows only, so an INSERT reports no affected rows.
expectedDbSpan({
name: 'INSERT "User"',
operation: 'INSERT',
statement: 'INSERT INTO "User" ("email", "name") VALUES ($1, $2)',
returnedRows: 0,
}),
expectedDbSpan({
name: 'SELECT "User"',
operation: 'SELECT',
statement: 'SELECT * FROM "User" WHERE "name" = $1',
returnedRows: 1,
}),
expectedDbSpan({
name: 'SELECT "User"; SELECT "User"',
operation: 'BATCH SELECT',
statement: 'SELECT "email" FROM "User"; SELECT "name" FROM "User"',
batchSize: 2,
returnedRows: 2,
}),
expectedDbSpan({
name: 'SELECT "does_not_exist_table"',
operation: 'SELECT',
statement: 'SELECT * FROM "does_not_exist_table"',
status: 'error',
}),
expectedDbSpan({ name: 'DROP TABLE "User"', operation: 'DROP', statement: 'DROP TABLE "User"' }),
expectedDbSpan({
name: 'DROP TABLE "User"',
operation: 'DROP',
statement: 'DROP TABLE "User"',
returnedRows: 0,
}),
]);
});
});
Expand All @@ -135,20 +152,36 @@ describeWithDockerCompose('neon auto instrumentation', { workingDirectory: [__di
const neonSpans = getNeonSpans(spans);
expect(neonSpans.every(span => span.parent_span_id === segment!.span_id)).toBe(true);
expect(neonSpans).toEqual([
expectedDbSpan({ name: 'CREATE TABLE "User"', operation: 'CREATE', statement: CREATE_USER_TABLE_STATEMENT }),
expectedDbSpan({
name: 'CREATE TABLE "User"',
operation: 'CREATE',
statement: CREATE_USER_TABLE_STATEMENT,
returnedRows: 0,
}),
expectedDbSpan({
name: 'INSERT "User"',
operation: 'INSERT',
statement: 'INSERT INTO "User" ("email", "name") VALUES ($1, $2)',
returnedRows: 1,
}),
expectedDbSpan({
name: 'SELECT "User"',
operation: 'SELECT',
statement: 'SELECT * FROM "User"',
returnedRows: 1,
}),
expectedDbSpan({ name: 'SELECT "User"', operation: 'SELECT', statement: 'SELECT * FROM "User"' }),
expectedDbSpan({
name: 'SELECT "does_not_exist_table"',
operation: 'SELECT',
statement: 'SELECT * FROM "does_not_exist_table"',
status: 'error',
}),
expectedDbSpan({ name: 'DROP TABLE "User"', operation: 'DROP', statement: 'DROP TABLE "User"' }),
expectedDbSpan({
name: 'DROP TABLE "User"',
operation: 'DROP',
statement: 'DROP TABLE "User"',
returnedRows: 0,
}),
]);
});
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import * as Sentry from '@sentry/node';
import { waitForConnection } from '@sentry-internal/node-integration-tests';
import pg from 'pg';

const { Client, Query } = pg;

const connectionConfig = { port: 5494, user: 'test', password: 'test', database: 'tests' };
const client = new Client(connectionConfig);

async function run() {
// Gate on the DB actually accepting a connection before opening the span (see `waitForConnection`).
await waitForConnection(async () => {
const probe = new Client(connectionConfig);
await probe.connect();
await probe.end();
});

await Sentry.startSpan(
{
name: 'Test Transaction',
op: 'transaction',
},
async () => {
try {
await client.connect();

await client.query('SELECT * FROM generate_series(1, 3) AS single');

// A multi-statement query resolves to one result per statement
await client.query('SELECT 1 AS one; SELECT * FROM generate_series(1, 2) AS multi');

await new Promise((resolve, reject) => {
client.query('SELECT * FROM generate_series(1, 4) AS callback', (err, res) =>
err ? reject(err) : resolve(res),
);
});

// A streamed `Submittable` reports its result on `'end'` instead of resolving it
await new Promise((resolve, reject) => {
const query = client.query(new Query('SELECT * FROM generate_series(1, 5) AS streamed'));
query.on('end', resolve);
query.on('error', reject);
});
} finally {
await client.end();
}
},
);
}

run();
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import { afterAll, describe, expect } from 'vitest';
import { EXPECTED_SDK_NAME, supports } from '../../../utils';
import { cleanupChildProcesses, createEsmAndCjsTests, describeWithDockerCompose } from '../../../utils/runner';

const DB_RESPONSE_RETURNED_ROWS = 'db.response.returned_rows';

const COMMON_DB_ATTRIBUTES = {
[SENTRY_IS_LOCALHOST]: { type: 'boolean', value: false },
[DB_CONNECTION_STRING]: { type: 'string', value: expect.stringMatching(/^postgresql:\/\/localhost:\d+\/tests$/) },
Expand Down Expand Up @@ -89,6 +91,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[SENTRY_OP]: { type: 'string', value: DB },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'INSERT "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'INSERT' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 1 },
},
name: 'INSERT "User"',
status: 'ok',
Expand All @@ -104,6 +107,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[SENTRY_OP]: { type: 'string', value: DB },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'SELECT "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'SELECT' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 1 },
},
name: 'SELECT "User"',
status: 'ok',
Expand Down Expand Up @@ -150,6 +154,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
},
[DB_QUERY_SUMMARY]: { type: 'string', value: 'CREATE TABLE "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'CREATE' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 0 },
},
},
{
Expand All @@ -163,6 +168,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[DB_QUERY_TEXT]: { type: 'string', value: 'DROP TABLE "User"' },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'DROP TABLE "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'DROP' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 0 },
},
},
]),
Expand Down Expand Up @@ -226,6 +232,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[SENTRY_OP]: { type: 'string', value: DB },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'INSERT "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'INSERT' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 1 },
},
name: 'INSERT "User"',
status: 'ok',
Expand All @@ -241,6 +248,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[SENTRY_OP]: { type: 'string', value: DB },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'SELECT "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'SELECT' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 1 },
},
name: 'SELECT "User"',
status: 'ok',
Expand All @@ -260,6 +268,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
},
[DB_QUERY_SUMMARY]: { type: 'string', value: 'CREATE TABLE "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'CREATE' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 0 },
},
},
{
Expand All @@ -273,6 +282,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[DB_QUERY_TEXT]: { type: 'string', value: 'DROP TABLE "User"' },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'DROP TABLE "User"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'DROP' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 0 },
},
},
]),
Expand Down Expand Up @@ -427,6 +437,39 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [

// Deno: with a module load hook installed, Deno compiles a native addon (`libpq`) as JavaScript.
// Bun: the `libpq` addon needs the Node symbol `node::EmitAsyncInit`, which Bun does not provide.
describe('returned rows', () => {
const querySpanWithRows = (alias: string, rows: number): unknown =>
expect.objectContaining({
attributes: expect.objectContaining({
[DB_QUERY_TEXT]: { type: 'string', value: expect.stringContaining(`AS ${alias}`) },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: rows },
}),
status: 'ok',
});

createEsmAndCjsTests(__dirname, 'scenario-returned-rows.mjs', 'instrument.mjs', (createTestRunner, test) => {
test(
'records `db.response.returned_rows` for promise, multi-statement, callback, and streamed queries',
{ timeout: 90_000 },
async () => {
await createTestRunner()
.expect({
span: {
items: expect.arrayContaining([
querySpanWithRows('single', 3),
querySpanWithRows('multi', 3),
querySpanWithRows('callback', 4),
querySpanWithRows('streamed', 5),
]),
},
})
.start()
.completed();
},
);
});
});

describe.runIf(supports({ max: 25, runtimes: ['node'] }))('pg-native', () => {
const EXPECTED_SPANS = {
items: expect.arrayContaining([
Expand Down Expand Up @@ -459,6 +502,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[SENTRY_OP]: { type: 'string', value: DB },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'INSERT "NativeUser"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'INSERT' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 1 },
[SERVER_ADDRESS]: { type: 'string', value: '127.0.0.1' },
[DB_CONNECTION_STRING]: {
type: 'string',
Expand All @@ -479,6 +523,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[SENTRY_OP]: { type: 'string', value: DB },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'SELECT "NativeUser"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'SELECT' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 1 },
[SERVER_ADDRESS]: { type: 'string', value: '127.0.0.1' },
[DB_CONNECTION_STRING]: {
type: 'string',
Expand Down Expand Up @@ -507,6 +552,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
},
[DB_QUERY_SUMMARY]: { type: 'string', value: 'CREATE TABLE "NativeUser"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'CREATE' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 0 },
},
},
{
Expand All @@ -524,6 +570,7 @@ describeWithDockerCompose('postgres auto instrumentation', { workingDirectory: [
[DB_QUERY_TEXT]: { type: 'string', value: 'DROP TABLE "NativeUser"' },
[DB_QUERY_SUMMARY]: { type: 'string', value: 'DROP TABLE "NativeUser"' },
[DB_OPERATION_NAME]: { type: 'string', value: 'DROP' },
[DB_RESPONSE_RETURNED_ROWS]: { type: 'integer', value: 0 },
},
},
]),
Expand Down
31 changes: 25 additions & 6 deletions packages/server-utils/src/integrations/neon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { CHANNELS } from '../orchestrion/channels';
import { neonModuleNames } from '../orchestrion/config/neon';
import { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';
import { bindTracingChannelToSpan } from '../tracing-channel';
import { bindPgQueryChannel, getConnectionAttributes } from './pg';
import { bindPgQueryChannel, getConnectionAttributes, setReturnedRows } from './pg';

const INTEGRATION_NAME = 'Neon' as const;
const ORIGIN = 'auto.db.neon';
Expand All @@ -37,6 +37,8 @@ interface NeonSqlTemplate {
interface NeonHttpQueryContext {
// `[queryData, opts]` for a single query, `[queryData[], opts[]]` for a `transaction()` batch.
arguments: unknown[];
// Per statement: the rows array, or `{ rowCount, rows, ... }` with `fullResults`. A batch resolves to an array of these.
result?: unknown;
}

interface NeonResolveConnectionContext {
Expand All @@ -61,11 +63,24 @@ function instrumentNeon(): void {
// the pg span shape.
bindPgQueryChannel(CHANNELS.NEON_QUERY, { origin: ORIGIN });

bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<NeonHttpQueryContext>(CHANNELS.NEON_HTTP_QUERY), data => {
const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));
httpQuerySpans.add(span);
return span;
});
bindTracingChannelToSpan(
diagnosticsChannel.tracingChannel<NeonHttpQueryContext>(CHANNELS.NEON_HTTP_QUERY),
data => {
const span = startInactiveSpan(httpQuerySpanOptions(data.arguments));
httpQuerySpans.add(span);
return span;
},
{
beforeSpanEnd(span, data) {
if ('error' in data) {
return;
}
const { result } = data;
const isBatch = Array.isArray(data.arguments[0]);
setReturnedRows(span, isBatch && Array.isArray(result) ? result.map(toPgResult) : toPgResult(result));
},
},
);

// The connection string is resolved inside the HTTP executor, so the query span is active
// when this settles. The executor's own context never sees the string.
Expand Down Expand Up @@ -118,6 +133,10 @@ function httpQuerySpanOptions(args: unknown[]): Parameters<typeof startInactiveS
return { name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_POSTGRESQL), onlyIfParent: true, attributes };
}

function toPgResult(result: unknown): unknown {
return Array.isArray(result) ? { rows: result } : result;
}

// OTel names a batch `BATCH <op>` when every statement shares one operation, plain `BATCH` otherwise.
function getBatchOperationName(statements: ReturnType<typeof getSqlQueryAttributes>[]): string {
const operations = new Set(statements.map(s => s[DB_OPERATION_NAME]?.toUpperCase()));
Expand Down
Loading
Loading