Skip to content
Merged
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
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -998,7 +998,7 @@ jobs:
- name: Set up Deno
if:
matrix.test-application == 'deno' || matrix.test-application == 'deno-streamed' || matrix.test-application ==
'deno-redis' || matrix.test-application == 'hono-4'
'deno-redis' || matrix.test-application == 'hono-4' || matrix.test-application == 'deno-mysql'
uses: denoland/setup-deno@v2.0.4
with:
deno-version: ${{ matrix.deno-version || 'v2.8.0' }}
Expand Down
7 changes: 7 additions & 0 deletions dev-packages/e2e-tests/test-applications/deno-mysql/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"imports": {
"@sentry/deno": "npm:@sentry/deno",
"mysql": "npm:mysql@2.18.1"
},
"nodeModulesDir": "manual"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
services:
db:
image: mysql:8.0
restart: always
container_name: e2e-tests-deno-mysql
# The `mysql` 2.x driver doesn't speak MySQL 8's default
# `caching_sha2_password` auth, so force the legacy plugin.
command: ['--default-authentication-plugin=mysql_native_password']
ports:
- '3306:3306'
environment:
MYSQL_ROOT_PASSWORD: password
healthcheck:
test: ['CMD-SHELL', 'mysqladmin ping -h 127.0.0.1 -uroot -ppassword']
interval: 2s
timeout: 3s
retries: 30
start_period: 10s
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { execSync } from 'child_process';
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

export default async function globalSetup() {
// Start MySQL via Docker Compose. `--wait` blocks until the healthcheck
// in docker-compose.yml passes, so the Deno app can connect immediately.
execSync('docker compose up -d --wait', {
cwd: __dirname,
stdio: 'inherit',
});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { execSync } from 'child_process';
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

export default async function globalTeardown() {
execSync('docker compose down --volumes', {
cwd: __dirname,
stdio: 'inherit',
});
}
23 changes: 23 additions & 0 deletions dev-packages/e2e-tests/test-applications/deno-mysql/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "deno-mysql",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "docker compose up -d --wait && deno run --allow-net --allow-env --allow-read --allow-sys --allow-write src/app.ts",
"test": "playwright test",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install",
"test:assert": "pnpm test"
},
"dependencies": {
"@sentry/deno": "file:../../packed/sentry-deno-packed.tgz",
"mysql": "2.18.1"
},
"devDependencies": {
"@playwright/test": "~1.56.0",
"@sentry-internal/test-utils": "link:../../../test-utils"
},
"volta": {
"extends": "../../package.json"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { getPlaywrightConfig } from '@sentry-internal/test-utils';

const config = getPlaywrightConfig({
startCommand: `pnpm start`,
port: 3030,
});

export default {
...config,
globalSetup: './global-setup.mjs',
globalTeardown: './global-teardown.mjs',
};
66 changes: 66 additions & 0 deletions dev-packages/e2e-tests/test-applications/deno-mysql/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// `@sentry/deno/import` MUST be the very first import: it registers the
// orchestrion runtime hook, which transforms `mysql` (imported dynamically
// below) to publish the `orchestrion:mysql:query` diagnostics channel.
// In Deno 2.8.0–2.8.2 the hook only works as the first import in the entry graph.
import '@sentry/deno/import';
import * as Sentry from '@sentry/deno';

Sentry.init({
environment: 'qa',
dsn: Deno.env.get('E2E_TEST_DSN'),
debug: !!Deno.env.get('DEBUG'),
tunnel: 'http://localhost:3031/', // proxy server
tracesSampleRate: 1,
});

// Dynamic import AFTER init so the orchestrion hook (registered above) is in
// place to transform `mysql/lib/Connection.js`'s `query`, and so
// `denoMysqlIntegration` (wired by `init()`) is already subscribed.
const { default: mysql } = await import('mysql');

const connection = mysql.createConnection({
host: Deno.env.get('MYSQL_HOST') ?? '127.0.0.1',
port: Number(Deno.env.get('MYSQL_PORT') ?? 3306),
user: 'root',
password: 'password',
});

// Swallow connection errors (e.g. the DB container going away at teardown) so
// they don't become an uncaught exception that crashes the process on shutdown.
connection.on('error', (err: unknown) => {
// eslint-disable-next-line no-console
console.error('mysql connection error', err);
});

connection.connect((err: unknown) => {
if (err) {
// eslint-disable-next-line no-console
console.error('mysql connect error', err);
}
});

const port = 3030;

Deno.serve({ port, hostname: '0.0.0.0' }, async (req: Request) => {
const url = new URL(req.url);

// Runs two queries, the second NESTED inside the first's callback. mysql
// dispatches that callback from its socket data handler (a fresh async
// context), so the nested query's span only lands on this request's
// http.server transaction if `denoMysqlIntegration`'s AsyncLocalStorage
// context strategy restored the parent across the async boundary.
if (url.pathname === '/test-mysql') {
await new Promise<void>((resolve, reject) => {
connection.query('SELECT 1 + 1 AS solution', (err: unknown) => {
if (err) return reject(err);
connection.query('SELECT NOW()', (err2: unknown) => {
if (err2) return reject(err2);
resolve();
});
});
});
return Response.json({ status: 'ok' });
}

return new Response('Not found', { status: 404 });
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { startEventProxyServer } from '@sentry-internal/test-utils';

startEventProxyServer({
port: 3031,
proxyServerName: 'deno-mysql',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { expect, test } from '@playwright/test';
import { waitForTransaction } from '@sentry-internal/test-utils';

test('mysql queries emit a db span with orchestrion-channel attributes', async ({ baseURL }) => {
// Each incoming request gets a Sentry http.server transaction (via the
// default denoServeIntegration); the mysql queries run inside it, so their
// db spans attach to that transaction.
const transactionPromise = waitForTransaction('deno-mysql', event => {
return (
event?.contexts?.trace?.op === 'http.server' &&
(event.request?.url ?? '').includes('/test-mysql') &&
(event.spans?.some(span => span.op === 'db') ?? false)
);
});

const res = await fetch(`${baseURL}/test-mysql`);
expect(res.status).toBe(200);
await res.json();

const transaction = await transactionPromise;
const dbSpans = transaction.spans!.filter(span => span.op === 'db');

const firstQuery = dbSpans.find(span => span.description === 'SELECT 1 + 1 AS solution');
expect(firstQuery).toBeDefined();
expect(firstQuery!.data?.['sentry.origin']).toBe('auto.db.orchestrion.mysql');
expect(firstQuery!.data?.['db.system']).toBe('mysql');
expect(firstQuery!.data?.['db.statement']).toBe('SELECT 1 + 1 AS solution');
expect(firstQuery!.data?.['net.peer.port']).toBe(3306);
expect(firstQuery!.data?.['db.user']).toBe('root');
});

test('a nested query lands on the same transaction (AsyncLocalStorage context restored)', async ({ baseURL }) => {
// The second query runs inside the first query's callback — i.e. across
// mysql's async socket-callback dispatch. Both spans appearing on the SAME
// http.server transaction proves denoMysqlIntegration's context strategy
// restored the parent span across that async boundary (otherwise the nested
// query would start its own trace and never join this transaction).
const transactionPromise = waitForTransaction('deno-mysql', event => {
return (
event?.contexts?.trace?.op === 'http.server' &&
(event.request?.url ?? '').includes('/test-mysql') &&
(event.spans?.filter(span => span.op === 'db').length ?? 0) >= 2
);
});

const res = await fetch(`${baseURL}/test-mysql`);
expect(res.status).toBe(200);
await res.json();

const transaction = await transactionPromise;
const descriptions = transaction.spans!.filter(span => span.op === 'db').map(span => span.description);
expect(descriptions).toContain('SELECT 1 + 1 AS solution');
expect(descriptions).toContain('SELECT NOW()');
});
43 changes: 43 additions & 0 deletions packages/deno/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,46 @@ Sentry.captureEvent({
],
});
```

## Auto-instrumentation (experimental)

Some libraries (e.g. `mysql`) don't emit tracing signals on their
own. To instrument them, Sentry uses
[orchestrion](https://github.com/apm-js-collab/tracing-hooks) to
transform them at load time so they publish to
`node:diagnostics_channel`.

In Deno versions prior to 2.8.0, this is not available, as it
relies on `Module.registerHooks`, which was added in that
version.

As of Deno 2.8.3, you can use the `--import` or `--preload`
argument to `deno run` in order to enable these instrumentations.

```bash
$ deno run --import=@sentry/deno/import app.ts
Comment thread
isaacs marked this conversation as resolved.
```

> [!NOTE]
> In Deno versions **2.8.0** through **2.8.2**, a bug causes Deno

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: Is it worth to mention that it works in these two versions? I would be fine of just saying we are supporting everything after 2.8.3 with the --import option and don't go into much detail - but this is also ok.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I generally agree that I'd just say "we support deno 2.8.3 and above" and not really go into details for anything below that?

> to deadlock when a module hook is added in this way. As a
> workaround, you can import the loader explicitly, and then
> dynamically import your app to take advantage of the added
> module loading hooks.
>
> ```ts
> import 'npm:@sentry/deno/import';
> await import('./app.ts');
> ```

In both cases, your `app.ts` should simply load Sentry as usual:

```ts
// app.ts

// initialize Sentry as early as possible
import * as Sentry from 'npm:@sentry/deno';
Sentry.init({ dsn: '__DSN__' });

// ... the rest of the app...
```
10 changes: 9 additions & 1 deletion packages/deno/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"types": "./build/esm/index.d.ts",
"default": "./build/esm/index.js"
}
},
"./import": {
"import": "./build/import.mjs"
}
},
"publishConfig": {
Expand All @@ -28,6 +31,9 @@
"@sentry/core": "10.58.0",
"@sentry/server-utils": "10.58.0"
},
"devDependencies": {
"mysql": "^2.18.1"
Comment thread
isaacs marked this conversation as resolved.
},
"scripts": {
"deno-types": "node ./scripts/download-deno-types.mjs",
"build": "run-s build:transpile build:types",
Expand All @@ -51,7 +57,9 @@
"volta": {
"extends": "../../package.json"
},
"sideEffects": false,
"sideEffects": [
"./build/import.mjs"
],
"nx": {
"targets": {
"build:transpile": {
Expand Down
11 changes: 10 additions & 1 deletion packages/deno/rollup.npm.config.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
import { defineConfig } from 'rollup';
import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils';

export default makeNPMConfigVariants(makeBaseNPMConfig(), { emitCjs: false });
const orchestrionRuntimeHooks = [
defineConfig({
input: 'src/import.mjs',
external: /.*/,
output: { format: 'esm', file: 'build/import.mjs' },
}),
];

export default [...orchestrionRuntimeHooks, ...makeNPMConfigVariants(makeBaseNPMConfig(), { emitCjs: false })];
12 changes: 12 additions & 0 deletions packages/deno/src/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,25 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import type { Scope } from '@sentry/core';
import { getDefaultCurrentScope, getDefaultIsolationScope, setAsyncContextStrategy } from '@sentry/core';

let installed = false;

/**
* Sets the async context strategy to use AsyncLocalStorage.
*
* Idempotent: multiple integrations each call this from their `setupOnce`,
* but they must all share a single `AsyncLocalStorage` so context propagates
* between them. The first call wins, later calls are no-ops. This prevents
* orphaning an in-flight context if an integration is set up asynchronously.
*
* @internal Only exported to be used in higher-level Sentry packages
* @hidden Only exported to be used in higher-level Sentry packages
*/
export function setAsyncLocalStorageAsyncContextStrategy(): void {
if (installed) {
return;
}
installed = true;

const asyncStorage = new AsyncLocalStorage<{
scope: Scope;
isolationScope: Scope;
Expand Down
7 changes: 7 additions & 0 deletions packages/deno/src/denoVersion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,10 @@ export const HTTP_SERVER_DIAGNOSTICS_CHANNEL_SUPPORTED = gte(2, 8, 0);

/** Whether `node:diagnostics_channel.tracingChannel` exists (Deno 1.44.3+). */
export const TRACING_CHANNEL_SUPPORTED = gte(1, 44, 3);

/**
* Whether `Module.registerHooks` is available (Deno 2.8.0+), which the
* orchestrion runtime hook (`@sentry/deno/import`) needs to transform libraries
* like `mysql` so they publish to their tracing channels.
*/
export const MODULE_REGISTER_HOOKS_SUPPORTED = gte(2, 8, 0);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q/l: Connected to the other comment. Should we actually start supporting it form 2.8.3?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean, it's fine, I guess? Probably no one's going to be using Deno 2.8.0, but they did make a big announcement about it when it came out, and haven't been as noisy about the patches, so it's possible someone upgraded right away, but then is lagging behind, I guess?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok if they made big announcements it might be better as is.

31 changes: 31 additions & 0 deletions packages/deno/src/import.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* EXPERIMENTAL: orchestrion runtime hook for Deno.
*
* In Deno versions prior to 2.8.0, this is a no-op: it relies on
* `Module.registerHooks` (added in 2.8.0), so without it the channels are
* simply not injected (channel-based instrumentation is disabled, with a
* warning in debug builds). It does not crash.
*
* As of Deno 2.8.3, this can be loaded via `--import` or `--preload`
* argument to `deno run` in order to enable these instrumentations.
*
* For example:
*
* ```bash
* $ deno run --import=@sentry/deno/import app.ts
* ```
*
* In Deno 2.8.0 through 2.8.2, it can be loaded directly in an
* `init.ts` file that then loads the app via dynamic import.
*
* For example:
*
* ```ts
* // init.ts
* import '@sentry/deno/import';
* await import('./app.ts');
* ```
*
* @module
*/
import '@sentry/server-utils/orchestrion/import-hook';
Comment thread
isaacs marked this conversation as resolved.
Comment thread
isaacs marked this conversation as resolved.
1 change: 1 addition & 0 deletions packages/deno/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export { denoHttpIntegration } from './integrations/http';
export type { DenoHttpIntegrationOptions } from './integrations/http';
export { denoRedisIntegration } from './integrations/redis';
export type { DenoRedisIntegrationOptions } from './integrations/redis';
export { denoMysqlIntegration } from './integrations/mysql';
export { denoContextIntegration } from './integrations/context';
export { globalHandlersIntegration } from './integrations/globalhandlers';
export { normalizePathsIntegration } from './integrations/normalizepaths';
Expand Down
Loading
Loading