Skip to content

feat(core): Add orgId option to init and DSC (sentry-org_id in baggage) #16305

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 5 commits into from
May 16, 2025
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 .size-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ module.exports = [
path: 'packages/browser/build/npm/esm/index.js',
import: createImport('init'),
gzip: true,
limit: '24 KB',
limit: '25 KB',
},
{
name: '@sentry/browser - with treeshaking flags',
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as Sentry from '@sentry/node';
import { loggingTransport, startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests';

export type TestAPIResponse = { test_data: { host: string; 'sentry-trace': string; baggage: string } };

Sentry.init({
dsn: 'https://public@o01234987.ingest.sentry.io/1337',
release: '1.0',
environment: 'prod',
tracesSampleRate: 1.0,
transport: loggingTransport,
});

import cors from 'cors';
import express from 'express';
import * as http from 'http';

const app = express();

app.use(cors());

app.get('/test/express', (_req, res) => {
const headers = http
.get({
hostname: 'example.com',
})
.getHeaders();

res.send({ test_data: headers });
});

Sentry.setupExpressErrorHandler(app);

startExpressServerAndSendPortToRunner(app);
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as Sentry from '@sentry/node';
import { loggingTransport, startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests';

export type TestAPIResponse = { test_data: { host: string; 'sentry-trace': string; baggage: string } };

Sentry.init({
dsn: 'https://public@public.ingest.sentry.io/1337',
release: '1.0',
environment: 'prod',
tracesSampleRate: 1.0,
transport: loggingTransport,
});

import cors from 'cors';
import express from 'express';
import * as http from 'http';

const app = express();

app.use(cors());

app.get('/test/express', (_req, res) => {
const headers = http
.get({
hostname: 'example.com',
})
.getHeaders();

res.send({ test_data: headers });
});

Sentry.setupExpressErrorHandler(app);

startExpressServerAndSendPortToRunner(app);
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as Sentry from '@sentry/node';
import { loggingTransport, startExpressServerAndSendPortToRunner } from '@sentry-internal/node-integration-tests';

export type TestAPIResponse = { test_data: { host: string; 'sentry-trace': string; baggage: string } };

Sentry.init({
dsn: 'https://public@o0000987.ingest.sentry.io/1337',
release: '1.0',
environment: 'prod',
orgId: '01234987',
tracesSampleRate: 1.0,
transport: loggingTransport,
});

import cors from 'cors';
import express from 'express';
import * as http from 'http';

const app = express();

app.use(cors());

app.get('/test/express', (_req, res) => {
const headers = http
.get({
hostname: 'example.com',
})
.getHeaders();

res.send({ test_data: headers });
});

Sentry.setupExpressErrorHandler(app);

startExpressServerAndSendPortToRunner(app);
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { afterAll, expect, test } from 'vitest';
import { cleanupChildProcesses, createRunner } from '../../../../utils/runner';
import type { TestAPIResponse } from './server';

afterAll(() => {
cleanupChildProcesses();
});

test('should include explicitly set org_id in the baggage header', async () => {
const runner = createRunner(__dirname, 'server.ts').start();

const response = await runner.makeRequest<TestAPIResponse>('get', '/test/express');
expect(response).toBeDefined();

const baggage = response?.test_data.baggage;
expect(baggage).toContain('sentry-org_id=01234987');
});

test('should extract org_id from DSN host when not explicitly set', async () => {
const runner = createRunner(__dirname, 'server-no-explicit-org-id.ts').start();

const response = await runner.makeRequest<TestAPIResponse>('get', '/test/express');
expect(response).toBeDefined();

const baggage = response?.test_data.baggage;
expect(baggage).toContain('sentry-org_id=01234987');
});

test('should set undefined org_id when it cannot be extracted', async () => {
const runner = createRunner(__dirname, 'server-no-org-id.ts').start();

const response = await runner.makeRequest<TestAPIResponse>('get', '/test/express');
expect(response).toBeDefined();

const baggage = response?.test_data.baggage;
expect(baggage).not.toContain('sentry-org_id');
});
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,7 @@ describe('browserTracingIntegration', () => {
sampleRand: expect.any(Number),
dsc: {
release: undefined,
org_id: undefined,
environment: 'production',
public_key: 'examplePublicKey',
sample_rate: '1',
Expand Down Expand Up @@ -773,6 +774,7 @@ describe('browserTracingIntegration', () => {
sampleRand: expect.any(Number),
dsc: {
release: undefined,
org_id: undefined,
environment: 'production',
public_key: 'examplePublicKey',
sample_rate: '0',
Expand Down Expand Up @@ -898,6 +900,7 @@ describe('browserTracingIntegration', () => {
expect(dynamicSamplingContext).toBeDefined();
expect(dynamicSamplingContext).toStrictEqual({
release: undefined,
org_id: undefined,
environment: 'production',
public_key: 'examplePublicKey',
sample_rate: '1',
Expand Down
11 changes: 10 additions & 1 deletion packages/core/src/tracing/dynamicSamplingContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
baggageHeaderToDynamicSamplingContext,
dynamicSamplingContextToSentryBaggageHeader,
} from '../utils-hoist/baggage';
import { extractOrgIdFromDsnHost } from '../utils-hoist/dsn';
import { addNonEnumerableProperty } from '../utils-hoist/object';
import { getCapturedScopesOnSpan } from './utils';

Expand Down Expand Up @@ -44,7 +45,14 @@ export function freezeDscOnSpan(span: Span, dsc: Partial<DynamicSamplingContext>
export function getDynamicSamplingContextFromClient(trace_id: string, client: Client): DynamicSamplingContext {
const options = client.getOptions();

const { publicKey: public_key } = client.getDsn() || {};
const { publicKey: public_key, host } = client.getDsn() || {};

let org_id: string | undefined;
if (options.orgId) {
org_id = String(options.orgId);
} else if (host) {
org_id = extractOrgIdFromDsnHost(host);
}

// Instead of conditionally adding non-undefined values, we add them and then remove them if needed
// otherwise, the order of baggage entries changes, which "breaks" a bunch of tests etc.
Expand All @@ -53,6 +61,7 @@ export function getDynamicSamplingContextFromClient(trace_id: string, client: Cl
release: options.release,
public_key,
trace_id,
org_id,
};

client.emit('createDsc', dsc);
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/types-hoist/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export type DynamicSamplingContext = {
replay_id?: string;
sampled?: string;
sample_rand?: string;
org_id?: string;
};

// https://github.com/getsentry/relay/blob/311b237cd4471042352fa45e7a0824b8995f216f/relay-server/src/envelope.rs#L154
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/types-hoist/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,14 @@ export interface ClientOptions<TO extends BaseTransportOptions = BaseTransportOp
*/
tracePropagationTargets?: TracePropagationTargets;

/**
* The organization ID of the current SDK. The organization ID is a string containing only numbers. This ID is used to
* propagate traces to other Sentry services.
*
* The SDK tries to automatically extract the organization ID from the DSN. With this option, you can override it.
*/
orgId?: `${number}` | number;

/**
* Function to compute tracing sample rate dynamically and filter unwanted traces.
*
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/utils-hoist/dsn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import type { DsnComponents, DsnLike, DsnProtocol } from '../types-hoist/dsn';
import { DEBUG_BUILD } from './../debug-build';
import { consoleSandbox, logger } from './logger';

/** Regular expression used to extract org ID from a DSN host. */
const ORG_ID_REGEX = /^o(\d+)\./;

/** Regular expression used to parse a Dsn. */
const DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;

Expand Down Expand Up @@ -114,6 +117,18 @@ function validateDsn(dsn: DsnComponents): boolean {
return true;
}

/**
* Extract the org ID from a DSN host.
*
* @param host The host from a DSN
* @returns The org ID if found, undefined otherwise
*/
export function extractOrgIdFromDsnHost(host: string): string | undefined {
const match = host.match(ORG_ID_REGEX);

return match?.[1];
}

/**
* Creates a valid Sentry Dsn object, identifying a Sentry instance and project.
* @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source
Expand Down
Loading
Loading