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
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ export { getTraceData } from './utils/traceData';
export { matchesTracePropagationTargets, shouldPropagateTraceForUrl } from './utils/tracePropagationTargets';
export { getTraceMetaTags } from './utils/meta';
export { _INTERNAL_CACHE_ORIGIN_META_TAG_NAME } from './utils/cacheOrigin';
export { getTraceServerTimingHeader, isSharedCacheable } from './utils/serverTiming';
export { debounce } from './utils/debounce';
export { uniq } from './utils/array';
export { makeWeakRef, derefWeakRef } from './utils/weakRef';
Expand Down
83 changes: 83 additions & 0 deletions packages/core/src/utils/serverTiming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import type { SerializedTraceData } from '../types/tracing';
import { safeDateNow } from './randomSafeContext';
import { getTraceData } from './traceData';

/**
* Returns the value of a `Server-Timing` response header that carries the current trace data.
*
* The browser SDK reads it off the document response to continue the trace of the server request in
* the pageload span. Unlike the meta tags of `getTraceMetaTags`, the header reaches the browser before
* any HTML, so the pageload never has to wait for a tag. The value holds up to two entries,
* `sentry-trace` and `baggage`, and is empty without trace data.
*
* @example
* ```js
* response.setHeader('Server-Timing', getTraceServerTimingHeader());
* ```
*/
export function getTraceServerTimingHeader(traceData?: SerializedTraceData): string {
return Object.entries(traceData || getTraceData())
.filter(([, value]) => value)
.map(([key, value]) => `${key};desc="${value}"`)
.join(', ');
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

// Cache-control fields a CDN reads instead of `Cache-Control`.
const CDN_CACHE_CONTROL_HEADERS = [
'cdn-cache-control',
'cloudflare-cdn-cache-control',
'vercel-cdn-cache-control',
'surrogate-control',
];

/**
* Whether a cache in front of the app may store a response and serve it to other users. Such a
* response must not carry the trace of one request, in a `Server-Timing` header or otherwise, since
* the cache would hand it to every later visitor.
*
* A CDN that reads a targeted field ignores `Cache-Control`; a cache without targeted support reads
* `Cache-Control`. Any of them storing the response is enough.
*
* @param getHeader Reads a response header by its lowercase name.
*/
export function isSharedCacheable(getHeader: (name: string) => string | undefined): boolean {
for (const name of CDN_CACHE_CONTROL_HEADERS) {
const value = getHeader(name);
if (value !== undefined && sharedCachingVerdict(value.toLowerCase()) === true) {
return true;
}
}

const verdict = sharedCachingVerdict(getHeader('cache-control')?.toLowerCase() ?? '');
if (verdict !== undefined) {
return verdict;
}
// Without a lifetime in `Cache-Control`, a cache falls back to `Expires`.
const expires = getHeader('expires');
return expires !== undefined && Date.parse(expires) > safeDateNow();
}

/** Whether these directives let a shared cache reuse the response, or `undefined` when they say nothing. */
function sharedCachingVerdict(directives: string): boolean | undefined {
if (/\b(?:no-store|private)\b/.test(directives)) {
return false;
}
// A stale copy is served even after a zero lifetime.
if (/\b(?:stale-while-revalidate|stale-if-error)\s*=\s*[1-9]/.test(directives)) {
return true;
}
// `s-maxage` overrides `max-age` for shared caches. A zero lifetime means the cache revalidates
// every time, so it never serves this response to anyone else.
const sharedMaxAge = directives.match(/\bs-maxage\s*=\s*(\d+)/)?.[1];
if (sharedMaxAge !== undefined) {
return Number(sharedMaxAge) > 0;
}
if (/\bpublic\b/.test(directives)) {
return true;
}
const maxAge = directives.match(/\bmax-age\s*=\s*(\d+)/)?.[1];
if (maxAge !== undefined) {
return Number(maxAge) > 0;
}
return undefined;
}
124 changes: 124 additions & 0 deletions packages/core/test/lib/utils/serverTiming.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getTraceServerTimingHeader, isSharedCacheable } from '../../../src/utils/serverTiming';
import * as TraceDataModule from '../../../src/utils/traceData';

describe('getTraceServerTimingHeader', () => {
afterEach(() => {
vi.restoreAllMocks();
});

it('renders sentry-trace and baggage as Server-Timing entries', () => {
vi.spyOn(TraceDataModule, 'getTraceData').mockReturnValueOnce({
'sentry-trace': '12345678901234567890123456789012-1234567890123456-1',
baggage: 'sentry-environment=production',
});

expect(getTraceServerTimingHeader()).toBe(
'sentry-trace;desc="12345678901234567890123456789012-1234567890123456-1", baggage;desc="sentry-environment=production"',
);
});

it('leaves out baggage when the trace data has none', () => {
vi.spyOn(TraceDataModule, 'getTraceData').mockReturnValueOnce({
'sentry-trace': '12345678901234567890123456789012-1234567890123456-1',
baggage: undefined,
});

expect(getTraceServerTimingHeader()).toBe(
'sentry-trace;desc="12345678901234567890123456789012-1234567890123456-1"',
);
});

it('renders just the sentry-trace entry', () => {
vi.spyOn(TraceDataModule, 'getTraceData').mockReturnValueOnce({
'sentry-trace': '12345678901234567890123456789012-1234567890123456-1',
});

expect(getTraceServerTimingHeader()).toBe(
'sentry-trace;desc="12345678901234567890123456789012-1234567890123456-1"',
);
});

it('returns an empty string without trace data', () => {
vi.spyOn(TraceDataModule, 'getTraceData').mockReturnValueOnce({});

expect(getTraceServerTimingHeader()).toBe('');
});

it('uses provided traceData instead of calling getTraceData()', () => {
const getTraceDataSpy = vi.spyOn(TraceDataModule, 'getTraceData');

expect(
getTraceServerTimingHeader({
'sentry-trace': 'ab12345678901234567890123456789012-1234567890123456-1',
baggage: 'sentry-environment=staging',
}),
).toBe(
'sentry-trace;desc="ab12345678901234567890123456789012-1234567890123456-1", baggage;desc="sentry-environment=staging"',
);
expect(getTraceDataSpy).not.toHaveBeenCalled();
});
});

describe('isSharedCacheable', () => {
const withHeaders =
(headers: Record<string, string>) =>
(name: string): string | undefined =>
headers[name];

it.each([
's-maxage=31536000',
's-maxage=1, stale-while-revalidate=3599',
'max-age=0, stale-while-revalidate=60',
'max-age=0, stale-if-error=60',
'public, max-age=31536000, immutable',
'max-age=60',
])('reports a response a shared cache may store (%s)', cacheControl => {
expect(isSharedCacheable(withHeaders({ 'cache-control': cacheControl }))).toBe(true);
});

it.each([
'private, no-cache, no-store, max-age=0, must-revalidate',
'no-store',
'private, max-age=60',
'private, s-maxage=60',
's-maxage=0',
'max-age=0',
'max-age=0, stale-while-revalidate=0',
'no-cache',
'',
])('reports a response only the browser may store (%s)', cacheControl => {
expect(isSharedCacheable(withHeaders({ 'cache-control': cacheControl }))).toBe(false);
});

it.each(['cdn-cache-control', 'cloudflare-cdn-cache-control', 'vercel-cdn-cache-control', 'surrogate-control'])(
'reports a response a CDN stores on its own field (%s) even when Cache-Control forbids it',
name => {
expect(isSharedCacheable(withHeaders({ 'cache-control': 'private', [name]: 's-maxage=60' }))).toBe(true);
},
);

it('falls back to Cache-Control when the CDN field forbids caching', () => {
expect(
isSharedCacheable(withHeaders({ 'cache-control': 'public, max-age=60', 'cdn-cache-control': 'no-store' })),
).toBe(true);
});

it('reads an uppercase value', () => {
expect(isSharedCacheable(withHeaders({ 'cache-control': 'Public, Max-Age=60' }))).toBe(true);
});

it('falls back to a future Expires without a lifetime in Cache-Control', () => {
expect(isSharedCacheable(withHeaders({ expires: new Date(Date.now() + 60_000).toUTCString() }))).toBe(true);
expect(isSharedCacheable(withHeaders({ expires: new Date(Date.now() - 60_000).toUTCString() }))).toBe(false);
expect(isSharedCacheable(withHeaders({ expires: 'not a date' }))).toBe(false);
});

it('lets a zero lifetime in Cache-Control override a future Expires', () => {
expect(
isSharedCacheable(
withHeaders({ 'cache-control': 'max-age=0', expires: new Date(Date.now() + 60_000).toUTCString() }),
),
).toBe(false);
});
});
Loading