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 2 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,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://[email protected]/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://[email protected]/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,32 @@
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?.split(',').sort();

expect(baggage).toContain('sentry-org_id=01234987');
});

test('should extract org_id from DSN host when not explicitly set', async () => {
// This test requires a new server with different configuration
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?.split(',').sort();

expect(baggage).toContain('sentry-org_id=01234987');
});
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 = 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
7 changes: 7 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,13 @@ export interface ClientOptions<TO extends BaseTransportOptions = BaseTransportOp
*/
tracePropagationTargets?: TracePropagationTargets;

/**
* The organization ID of the current SDK.
*
* The SDK automatically extracts the organization ID from the DSN, if needed. With this option, you can override it.
*/
orgId?: string;

/**
* Function to compute tracing sample rate dynamically and filter unwanted traces.
*
Expand Down
18 changes: 18 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,21 @@ 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);

if (match?.[1]) {
return match[1];
}
return undefined;
}

/**
* 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
115 changes: 114 additions & 1 deletion packages/core/test/lib/tracing/dynamicSamplingContext.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import {
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
setCurrentClient,
} from '../../../src';
import { DEFAULT_ENVIRONMENT } from '../../../src/constants';
import { getDynamicSamplingContextFromSpan, SentrySpan, startInactiveSpan } from '../../../src/tracing';
import { freezeDscOnSpan } from '../../../src/tracing/dynamicSamplingContext';
import { freezeDscOnSpan, getDynamicSamplingContextFromClient } from '../../../src/tracing/dynamicSamplingContext';
import type { Span, SpanContextData } from '../../../src/types-hoist/span';
import type { TransactionSource } from '../../../src/types-hoist/transaction';
import { getDefaultTestClientOptions, TestClient } from '../../mocks/client';
Expand Down Expand Up @@ -178,3 +179,115 @@ describe('getDynamicSamplingContextFromSpan', () => {
});
});
});

describe('getDynamicSamplingContextFromClient', () => {
const TRACE_ID = '4b25bc58f14243d8b208d1e22a054164';
let client: TestClient;

beforeEach(() => {
vi.clearAllMocks();
});

afterEach(() => {
vi.resetAllMocks();
});

it('creates DSC with basic client information', () => {
client = new TestClient(
getDefaultTestClientOptions({
release: '1.0.0',
environment: 'test-env',
dsn: 'https://[email protected]/1',
}),
);

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(dsc).toEqual({
trace_id: TRACE_ID,
release: '1.0.0',
environment: 'test-env',
public_key: 'public',
org_id: undefined,
});
});

it('uses DEFAULT_ENVIRONMENT when environment is not specified', () => {
client = new TestClient(
getDefaultTestClientOptions({
release: '1.0.0',
dsn: 'https://[email protected]/1',
}),
);

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(dsc.environment).toBe(DEFAULT_ENVIRONMENT);
});

it('uses orgId from options when specified', () => {
client = new TestClient(
getDefaultTestClientOptions({
orgId: 'explicit-org-id',
dsn: 'https://[email protected]/1',
}),
);

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(dsc.org_id).toBe('explicit-org-id');
});

it('infers orgId from DSN host when not explicitly provided', () => {
client = new TestClient(
getDefaultTestClientOptions({
dsn: 'https://[email protected]/1',
}),
);

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(dsc.org_id).toBe('123456');
});

it('prioritizes explicit orgId over inferred from DSN', () => {
client = new TestClient(
getDefaultTestClientOptions({
orgId: 'explicit-org-id',
dsn: 'https://[email protected]/1',
}),
);

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(dsc.org_id).toBe('explicit-org-id');
});

it('handles missing DSN gracefully', () => {
client = new TestClient(
getDefaultTestClientOptions({
release: '1.0.0',
}),
);

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(dsc.public_key).toBeUndefined();
expect(dsc.org_id).toBeUndefined();
});

it('emits createDsc event with the generated DSC', () => {
client = new TestClient(
getDefaultTestClientOptions({
release: '1.0.0',
dsn: 'https://[email protected]/1',
}),
);

const emitSpy = vi.spyOn(client, 'emit');

const dsc = getDynamicSamplingContextFromClient(TRACE_ID, client);

expect(emitSpy).toHaveBeenCalledWith('createDsc', dsc);
});
});
36 changes: 34 additions & 2 deletions packages/core/test/utils-hoist/dsn.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { beforeEach, describe, expect, it, test, vi } from 'vitest';
import { DEBUG_BUILD } from '../../src/debug-build';
import { dsnToString, makeDsn } from '../../src/utils-hoist/dsn';
import { dsnToString, extractOrgIdFromDsnHost, makeDsn } from '../../src/utils-hoist/dsn';
import { logger } from '../../src/utils-hoist/logger';

function testIf(condition: boolean) {
Expand Down Expand Up @@ -215,3 +215,35 @@ describe('Dsn', () => {
});
});
});

describe('extractOrgIdFromDsnHost', () => {
it('extracts the org ID from a DSN host with standard format', () => {
expect(extractOrgIdFromDsnHost('o123456.sentry.io')).toBe('123456');
});

it('extracts numeric org IDs of different lengths', () => {
expect(extractOrgIdFromDsnHost('o1.ingest.sentry.io')).toBe('1');
expect(extractOrgIdFromDsnHost('o42.sentry.io')).toBe('42');
expect(extractOrgIdFromDsnHost('o9999999.sentry.io')).toBe('9999999');
});

it('returns undefined for hosts without an org ID prefix', () => {
expect(extractOrgIdFromDsnHost('sentry.io')).toBeUndefined();
expect(extractOrgIdFromDsnHost('example.com')).toBeUndefined();
});

it('returns undefined for hosts with invalid org ID format', () => {
expect(extractOrgIdFromDsnHost('oabc.sentry.io')).toBeUndefined();
expect(extractOrgIdFromDsnHost('o.sentry.io')).toBeUndefined();
expect(extractOrgIdFromDsnHost('oX123.sentry.io')).toBeUndefined();
});

it('handles different domain variations', () => {
expect(extractOrgIdFromDsnHost('o123456.ingest.sentry.io')).toBe('123456');
expect(extractOrgIdFromDsnHost('o123456.custom-domain.com')).toBe('123456');
});

it('handles empty string input', () => {
expect(extractOrgIdFromDsnHost('')).toBeUndefined();
});
});
Loading