Skip to content

feat(browser): Add debugId sync APIs between web worker and main thread #16981

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jul 17, 2025
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
self._sentryDebugIds = {
'Error at http://sentry-test.io/worker.js': 'worker-debug-id-789',
};

self.postMessage({
_sentryMessage: true,
_sentryDebugIds: self._sentryDebugIds,
});

self.addEventListener('message', event => {
if (event.data.type === 'throw-error') {
throw new Error('Worker error for testing');
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as Sentry from '@sentry/browser';

// Initialize Sentry with webWorker integration
Sentry.init({
dsn: 'https://[email protected]/1337',
});

const worker = new Worker('/worker.js');

Sentry.addIntegration(Sentry.webWorkerIntegration({ worker }));

const btn = document.getElementById('errWorker');

btn.addEventListener('click', () => {
worker.postMessage({
type: 'throw-error',
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="errWorker">Throw error in worker</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { expect } from '@playwright/test';
import type { Event } from '@sentry/core';
import { sentryTest } from '../../../utils/fixtures';
import { getFirstSentryEnvelopeRequest } from '../../../utils/helpers';

sentryTest('Assigns web worker debug IDs when using webWorkerIntegration', async ({ getLocalTestUrl, page }) => {
const bundle = process.env.PW_BUNDLE as string | undefined;
if (bundle != null && !bundle.includes('esm') && !bundle.includes('cjs')) {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });

const errorEventPromise = getFirstSentryEnvelopeRequest<Event>(page, url);

page.route('**/worker.js', route => {
route.fulfill({
path: `${__dirname}/assets/worker.js`,
});
});

const button = page.locator('#errWorker');
await button.click();

const errorEvent = await errorEventPromise;

expect(errorEvent.debug_meta?.images).toBeDefined();

const debugImages = errorEvent.debug_meta?.images || [];

expect(debugImages.length).toBe(1);

debugImages.forEach(image => {
expect(image.type).toBe('sourcemap');
expect(image.debug_id).toEqual('worker-debug-id-789');
expect(image.code_file).toEqual('http://sentry-test.io/worker.js');
});
});
2 changes: 1 addition & 1 deletion dev-packages/e2e-tests/lib/copyToTemp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function fixPackageJson(cwd: string): void {

// 2. Fix volta extends
if (!packageJson.volta) {
throw new Error('No volta config found, please provide one!');
throw new Error("No volta config found, please add one to the test app's package.json!");
Copy link
Member Author

Choose a reason for hiding this comment

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

adjusted this message because I didn't realize the volta config needed to be added to the e2e test apps. Might be a me-problem but I think the message is now fool-proof :D

}

if (typeof packageJson.volta.extends === 'string') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@sentry:registry=http://127.0.0.1:4873
@sentry-internal:registry=http://127.0.0.1:4873
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
<button id="trigger-error" type="button" style="background-color: #dc3545; color: white">
Trigger Worker Error
</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "browser-webworker-vite",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "rm -rf dist && tsc && vite build",
"preview": "vite preview --port 3030",
"test": "playwright test",
"test:build": "pnpm install && pnpm build",
"test:assert": "pnpm test"
},
"devDependencies": {
"@playwright/test": "~1.53.2",
"@sentry-internal/test-utils": "link:../../../test-utils",
"typescript": "~5.8.3",
"vite": "^7.0.4"
},
"dependencies": {
"@sentry/browser": "latest || *",
"@sentry/vite-plugin": "^3.5.0"
},
"volta": {
"node": "20.19.2",
"yarn": "1.22.22",
"pnpm": "9.15.9"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { getPlaywrightConfig } from '@sentry-internal/test-utils';

const config = getPlaywrightConfig({
startCommand: `pnpm preview`,
eventProxyFile: 'start-event-proxy.mjs',
eventProxyPort: 3031,
port: 3030,
});

export default config;
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import MyWorker from './worker.ts?worker';
import * as Sentry from '@sentry/browser';

Sentry.init({
dsn: import.meta.env.PUBLIC_E2E_TEST_DSN,
environment: import.meta.env.MODE || 'development',
tracesSampleRate: 1.0,
debug: true,
integrations: [Sentry.browserTracingIntegration()],
tunnel: 'http://localhost:3031/', // proxy server
});

const worker = new MyWorker();

Sentry.addIntegration(Sentry.webWorkerIntegration({ worker }));

worker.addEventListener('message', event => {
// this is part of the test, do not delete
console.log('received message from worker:', event.data.msg);
});

document.querySelector<HTMLButtonElement>('#trigger-error')!.addEventListener('click', () => {
worker.postMessage({
msg: 'TRIGGER_ERROR',
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import * as Sentry from '@sentry/browser';

// type cast necessary because TS thinks this file is part of the main
// thread where self is of type `Window` instead of `Worker`
Sentry.registerWebWorker({ self: self as unknown as Worker });

// Let the main thread know the worker is ready
self.postMessage({
msg: 'WORKER_READY',
});

self.addEventListener('message', event => {
if (event.data.msg === 'TRIGGER_ERROR') {
// This will throw an uncaught error in the worker
throw new Error(`Uncaught error in worker`);
}
});
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: 'browser-webworker-vite',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { expect, test } from '@playwright/test';
import { waitForError, waitForTransaction } from '@sentry-internal/test-utils';

test('captures an error with debug ids and pageload trace context', async ({ page }) => {
const errorEventPromise = waitForError('browser-webworker-vite', async event => {
return !event.type && !!event.exception?.values?.[0];
});

const transactionPromise = waitForTransaction('browser-webworker-vite', transactionEvent => {
return !!transactionEvent?.transaction && transactionEvent.contexts?.trace?.op === 'pageload';
});

await page.goto('/');

await page.locator('#trigger-error').click();

await page.waitForTimeout(1000);

const errorEvent = await errorEventPromise;
const transactionEvent = await transactionPromise;

const pageloadTraceId = transactionEvent.contexts?.trace?.trace_id;
const pageloadSpanId = transactionEvent.contexts?.trace?.span_id;

expect(errorEvent.exception?.values).toHaveLength(1);
expect(errorEvent.exception?.values?.[0]?.value).toBe('Uncaught Error: Uncaught error in worker');
expect(errorEvent.exception?.values?.[0]?.stacktrace?.frames).toHaveLength(1);
expect(errorEvent.exception?.values?.[0]?.stacktrace?.frames?.[0]?.filename).toMatch(/worker-.+\.js$/);

expect(errorEvent.transaction).toBe('/');
expect(transactionEvent.transaction).toBe('/');

expect(errorEvent.request).toEqual({
url: 'http://localhost:3030/',
headers: expect.any(Object),
});

expect(errorEvent.contexts?.trace).toEqual({
trace_id: pageloadTraceId,
span_id: pageloadSpanId,
});

expect(errorEvent.debug_meta).toEqual({
images: [
{
code_file: expect.stringMatching(/http:\/\/localhost:3030\/assets\/worker-.+\.js/),
debug_id: expect.stringMatching(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/),
type: 'sourcemap',
},
],
});
});

test("user worker message handlers don't trigger for sentry messages", async ({ page }) => {
const workerReadyPromise = new Promise<number>(resolve => {
let workerMessageCount = 0;
page.on('console', msg => {
if (msg.text().startsWith('received message from worker:')) {
workerMessageCount++;
}

if (msg.text() === 'received message from worker: WORKER_READY') {
resolve(workerMessageCount);
}
});
});

await page.goto('/');

const workerMessageCount = await workerReadyPromise;

expect(workerMessageCount).toBe(1);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { sentryVitePlugin } from '@sentry/vite-plugin';
import { defineConfig } from 'vite';

export default defineConfig({
build: {
sourcemap: 'hidden',
envPrefix: ['PUBLIC_'],
},

plugins: [
sentryVitePlugin({
org: process.env.E2E_TEST_SENTRY_ORG_SLUG,
project: process.env.E2E_TEST_SENTRY_PROJECT,
authToken: process.env.E2E_TEST_AUTH_TOKEN,
}),
],

worker: {
plugins: () => [
...sentryVitePlugin({
org: process.env.E2E_TEST_SENTRY_ORG_SLUG,
project: process.env.E2E_TEST_SENTRY_PROJECT,
authToken: process.env.E2E_TEST_AUTH_TOKEN,
}),
],
},

envPrefix: ['PUBLIC_'],
});
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,4 @@ export { openFeatureIntegration, OpenFeatureIntegrationHook } from './integratio
export { unleashIntegration } from './integrations/featureFlags/unleash';
export { statsigIntegration } from './integrations/featureFlags/statsig';
export { diagnoseSdkConnectivity } from './diagnose-sdk';
export { webWorkerIntegration, registerWebWorker } from './integrations/webWorker';
Loading
Loading