Repository navigation
feat(core): Add getTraceServerTimingHeader and isSharedCacheable
#26325
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(', '); | ||
| } | ||
|
|
||
| // 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; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.