-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(tanstackstart-react): Add distributed tracing #21144
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
Show all changes
8 commits
Select commit
Hold shift + click to select a range
694bff8
feat(tanstackstart-react): Add distributed tracing via meta tag injec…
nicohrubec c8e927c
fix: Match original comment from Astro middleware
nicohrubec 295b57a
fix: Match Astro injectMetaTagsInResponse implementation 1:1
nicohrubec c5b8f10
fix: Use inline captureException with auto.http.tanstackstart mechanism
nicohrubec 0c8b118
fix: Rename bodyIterator to bodyReporter, add mechanism to outer catch
nicohrubec 94fb6a0
fix: Avoid calling controller.close() after controller.error()
nicohrubec 6fc3d11
test: Add unit test for stream error captureException, add changelog
nicohrubec 53a6c2b
ci: retrigger
nicohrubec 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
38 changes: 14 additions & 24 deletions
38
...packages/e2e-tests/test-applications/tanstackstart-react-cloudflare/src/routes/__root.tsx
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
36 changes: 36 additions & 0 deletions
36
...2e-tests/test-applications/tanstackstart-react-cloudflare/tests/trace-propagation.test.ts
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,36 @@ | ||
| import { expect, test } from '@playwright/test'; | ||
| import { waitForTransaction } from '@sentry-internal/test-utils'; | ||
|
|
||
| test.describe('Trace propagation', () => { | ||
| test('should inject metatags in ssr pageload', async ({ page }) => { | ||
| await page.goto('/'); | ||
|
|
||
| const sentryTraceContent = await page.getAttribute('meta[name="sentry-trace"]', 'content'); | ||
| expect(sentryTraceContent).toBeDefined(); | ||
| expect(sentryTraceContent).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-[01]$/); | ||
|
|
||
| const baggageContent = await page.getAttribute('meta[name="baggage"]', 'content'); | ||
| expect(baggageContent).toBeDefined(); | ||
| expect(baggageContent).toContain('sentry-environment=qa'); | ||
| expect(baggageContent).toContain('sentry-public_key='); | ||
| expect(baggageContent).toContain('sentry-trace_id='); | ||
| expect(baggageContent).toContain('sentry-sampled='); | ||
| }); | ||
|
|
||
| test('should have trace connection between server and client', async ({ page }) => { | ||
| const serverTxPromise = waitForTransaction('tanstackstart-react-cloudflare', transactionEvent => { | ||
| return transactionEvent?.contexts?.trace?.op === 'http.server' && transactionEvent?.transaction === 'GET /'; | ||
| }); | ||
|
|
||
| const clientTxPromise = waitForTransaction('tanstackstart-react-cloudflare', transactionEvent => { | ||
| return transactionEvent?.contexts?.trace?.op === 'pageload' && transactionEvent?.transaction === '/'; | ||
| }); | ||
|
|
||
| await page.goto('/'); | ||
|
|
||
| const serverTx = await serverTxPromise; | ||
| const clientTx = await clientTxPromise; | ||
|
|
||
| expect(clientTx.contexts?.trace?.trace_id).toBe(serverTx.contexts?.trace?.trace_id); | ||
| }); | ||
| }); |
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
41 changes: 41 additions & 0 deletions
41
dev-packages/e2e-tests/test-applications/tanstackstart-react/tests/trace-propagation.test.ts
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,41 @@ | ||
| import { expect, test } from '@playwright/test'; | ||
| import { waitForTransaction } from '@sentry-internal/test-utils'; | ||
|
|
||
| const usesManagedTunnelRoute = | ||
| (process.env.E2E_TEST_TUNNEL_ROUTE_MODE ?? 'off') !== 'off' || process.env.E2E_TEST_CUSTOM_TUNNEL_ROUTE === '1'; | ||
|
|
||
| test.skip(usesManagedTunnelRoute, 'Default e2e suites run only in the proxy variant'); | ||
|
|
||
| test.describe('Trace propagation', () => { | ||
| test('should inject metatags in ssr pageload', async ({ page }) => { | ||
| await page.goto('/'); | ||
|
|
||
| const sentryTraceContent = await page.getAttribute('meta[name="sentry-trace"]', 'content'); | ||
| expect(sentryTraceContent).toBeDefined(); | ||
| expect(sentryTraceContent).toMatch(/^[a-f0-9]{32}-[a-f0-9]{16}-[01]$/); | ||
|
|
||
| const baggageContent = await page.getAttribute('meta[name="baggage"]', 'content'); | ||
| expect(baggageContent).toBeDefined(); | ||
| expect(baggageContent).toContain('sentry-environment=qa'); | ||
| expect(baggageContent).toContain('sentry-public_key='); | ||
| expect(baggageContent).toContain('sentry-trace_id='); | ||
| expect(baggageContent).toContain('sentry-sampled='); | ||
| }); | ||
|
|
||
| test('should have trace connection between server and client', async ({ page }) => { | ||
| const serverTxPromise = waitForTransaction('tanstackstart-react', transactionEvent => { | ||
| return transactionEvent?.contexts?.trace?.op === 'http.server' && transactionEvent?.transaction === 'GET /'; | ||
| }); | ||
|
|
||
| const clientTxPromise = waitForTransaction('tanstackstart-react', transactionEvent => { | ||
| return transactionEvent?.contexts?.trace?.op === 'pageload' && transactionEvent?.transaction === '/'; | ||
| }); | ||
|
|
||
| await page.goto('/'); | ||
|
|
||
| const serverTx = await serverTxPromise; | ||
| const clientTx = await clientTxPromise; | ||
|
|
||
| expect(clientTx.contexts?.trace?.trace_id).toBe(serverTx.contexts?.trace?.trace_id); | ||
| }); | ||
| }); |
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 |
|---|---|---|
| @@ -1,11 +1,110 @@ | ||
| import { flushIfServerless } from '@sentry/core'; | ||
| import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/node'; | ||
| import { flushIfServerless, getTraceMetaTags } from '@sentry/core'; | ||
| import { | ||
| captureException, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_OP, | ||
| SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, | ||
| startSpan, | ||
| } from '@sentry/node'; | ||
| import { extractServerFunctionSha256 } from './utils'; | ||
|
|
||
| export type ServerEntry = { | ||
| fetch: (request: Request, opts?: unknown) => Promise<Response> | Response; | ||
| }; | ||
|
|
||
| /** | ||
| * This function optimistically assumes that the HTML coming in chunks will not be split | ||
| * within the <head> tag. If this still happens, we simply won't replace anything. | ||
| */ | ||
| function addMetaTagToHead(htmlChunk: string, metaTagsStr: string): string { | ||
| if (typeof htmlChunk !== 'string' || !metaTagsStr) { | ||
| return htmlChunk; | ||
| } | ||
|
|
||
| if (htmlChunk.includes('"sentry-trace"')) { | ||
| return htmlChunk; | ||
| } | ||
|
nicohrubec marked this conversation as resolved.
|
||
|
|
||
| // Skip quoted attribute values so we don't match <head> inside e.g. data-code="...<head>..." | ||
| let replaced = false; | ||
| return htmlChunk.replace(/"[^"]*"|'[^']*'|(<head>)/g, (match, headTag) => { | ||
| if (headTag && !replaced) { | ||
| replaced = true; | ||
| return `<head>${metaTagsStr}`; | ||
| } | ||
| return match; | ||
| }); | ||
| } | ||
|
|
||
| function injectMetaTagsInResponse(originalResponse: Response): Response { | ||
| try { | ||
| const contentType = originalResponse.headers.get('content-type'); | ||
|
|
||
| const isPageloadRequest = contentType?.startsWith('text/html'); | ||
| if (!isPageloadRequest) { | ||
| return originalResponse; | ||
| } | ||
|
|
||
| // Type case necessary b/c the body's ReadableStream type doesn't include | ||
| // the async iterator that is actually available in Node | ||
| // We later on use the async iterator to read the body chunks | ||
| // see https://github.com/microsoft/TypeScript/issues/39051 | ||
| const originalBody = originalResponse.body as NodeJS.ReadableStream | null; | ||
| if (!originalBody) { | ||
| return originalResponse; | ||
| } | ||
|
|
||
| const metaTagsStr = getTraceMetaTags(); | ||
| const decoder = new TextDecoder(); | ||
|
|
||
| const newResponseStream = new ReadableStream({ | ||
| start: async controller => { | ||
| // Assign to a new variable to avoid TS losing the narrower type checked above. | ||
| const body = originalBody; | ||
|
|
||
| async function* bodyReporter(): AsyncGenerator<string | Buffer> { | ||
| try { | ||
| for await (const chunk of body) { | ||
| yield chunk; | ||
| } | ||
| } catch (e) { | ||
| captureException(e, { | ||
| mechanism: { type: 'auto.http.tanstackstart', handled: false }, | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe you could also test that those exceptions are correctly captured. |
||
| }); | ||
| throw e; | ||
| } | ||
| } | ||
|
|
||
| let errored = false; | ||
| try { | ||
| for await (const chunk of bodyReporter()) { | ||
| const html = typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true }); | ||
| const modifiedHtml = addMetaTagToHead(html, metaTagsStr); | ||
| controller.enqueue(new TextEncoder().encode(modifiedHtml)); | ||
| } | ||
|
nicohrubec marked this conversation as resolved.
nicohrubec marked this conversation as resolved.
|
||
| } catch (e) { | ||
| errored = true; | ||
| controller.error(e); | ||
| } finally { | ||
| if (!errored) { | ||
| controller.close(); | ||
| } | ||
| } | ||
|
cursor[bot] marked this conversation as resolved.
|
||
| }, | ||
| }); | ||
|
|
||
| return new Response(newResponseStream, { | ||
| status: originalResponse.status, | ||
| statusText: originalResponse.statusText, | ||
| headers: new Headers(originalResponse.headers), | ||
| }); | ||
| } catch (e) { | ||
| captureException(e, { | ||
| mechanism: { type: 'auto.http.tanstackstart', handled: false }, | ||
| }); | ||
| throw e; | ||
| } | ||
| } | ||
|
nicohrubec marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * This function can be used to wrap the server entry request handler to add tracing to server-side functionality. | ||
| * You must explicitly define a server entry point in your application for this to work. This is done by passing the request handler to the `createServerEntry` function. | ||
|
|
@@ -62,7 +161,7 @@ export function wrapFetchWithSentry(serverEntry: ServerEntry): ServerEntry { | |
| ); | ||
| } | ||
|
|
||
| return await target.apply(thisArg, args); | ||
| return injectMetaTagsInResponse(await target.apply(thisArg, args)); | ||
| } finally { | ||
| await flushIfServerless(); | ||
| } | ||
|
|
||
Oops, something went wrong.
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.