Skip to content

feat(react-router): Automatically flush on serverless for loaders/actions #17233

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

Closed
wants to merge 6 commits into from
Closed
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
8 changes: 7 additions & 1 deletion packages/react-router/src/server/wrapSentryHandleRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { context } from '@opentelemetry/api';
import { getRPCMetadata, RPCType } from '@opentelemetry/core';
import { ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';
import {
flushIfServerless,
getActiveSpan,
getRootSpan,
getTraceMetaTags,
Expand Down Expand Up @@ -58,10 +59,15 @@ export function wrapSentryHandleRequest(originalHandle: OriginalHandleRequest):
});
}

return originalHandle(request, responseStatusCode, responseHeaders, routerContext, loadContext);
try {
return await originalHandle(request, responseStatusCode, responseHeaders, routerContext, loadContext);
} finally {
await flushIfServerless();
}
};
}

// todo(v11): remove this
/** @deprecated Use `wrapSentryHandleRequest` instead. */
export const sentryHandleRequest = wrapSentryHandleRequest;

Expand Down
27 changes: 16 additions & 11 deletions packages/react-router/src/server/wrapServerAction.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions';
import type { SpanAttributes } from '@sentry/core';
import {
flushIfServerless,
getActiveSpan,
getRootSpan,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
Expand Down Expand Up @@ -59,17 +60,21 @@ export function wrapServerAction<T>(options: SpanOptions = {}, actionFn: (args:
}
}

return startSpan(
{
name,
...options,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.react-router.action',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'function.react-router.action',
...options.attributes,
try {
return await startSpan(
{
name,
...options,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.react-router.action',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'function.react-router.action',
...options.attributes,
},
},
},
() => actionFn(args),
);
() => actionFn(args),
);
} finally {
await flushIfServerless();
}
};
}
27 changes: 16 additions & 11 deletions packages/react-router/src/server/wrapServerLoader.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SEMATTRS_HTTP_TARGET } from '@opentelemetry/semantic-conventions';
import type { SpanAttributes } from '@sentry/core';
import {
flushIfServerless,
getActiveSpan,
getRootSpan,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
Expand Down Expand Up @@ -59,17 +60,21 @@ export function wrapServerLoader<T>(options: SpanOptions = {}, loaderFn: (args:
}
}
}
return startSpan(
{
name,
...options,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.react-router.loader',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'function.react-router.loader',
...options.attributes,
try {
return await startSpan(
{
name,
...options,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.react-router.loader',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'function.react-router.loader',
...options.attributes,
},
},
},
() => loaderFn(args),
);
() => loaderFn(args),
);
} finally {
await flushIfServerless();
}
};
}
154 changes: 101 additions & 53 deletions packages/react-router/test/server/wrapSentryHandleRequest.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { RPCType } from '@opentelemetry/core';
import { ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';
import {
flushIfServerless,
getActiveSpan,
getRootSpan,
getTraceMetaTags,
Expand All @@ -15,13 +16,13 @@ vi.mock('@opentelemetry/core', () => ({
RPCType: { HTTP: 'http' },
getRPCMetadata: vi.fn(),
}));

vi.mock('@sentry/core', () => ({
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE: 'sentry.source',
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN: 'sentry.origin',
getActiveSpan: vi.fn(),
getRootSpan: vi.fn(),
getTraceMetaTags: vi.fn(),
flushIfServerless: vi.fn(),
}));

describe('wrapSentryHandleRequest', () => {
Expand Down Expand Up @@ -62,7 +63,8 @@ describe('wrapSentryHandleRequest', () => {
(getActiveSpan as unknown as ReturnType<typeof vi.fn>).mockReturnValue(mockActiveSpan);
(getRootSpan as unknown as ReturnType<typeof vi.fn>).mockReturnValue(mockRootSpan);
const getRPCMetadata = vi.fn().mockReturnValue(mockRpcMetadata);
vi.mocked(vi.importActual('@opentelemetry/core')).getRPCMetadata = getRPCMetadata;
(vi.importActual('@opentelemetry/core') as unknown as { getRPCMetadata: typeof getRPCMetadata }).getRPCMetadata =
getRPCMetadata;

const routerContext = {
staticHandlerContext: {
Expand Down Expand Up @@ -110,7 +112,8 @@ describe('wrapSentryHandleRequest', () => {
(getActiveSpan as unknown as ReturnType<typeof vi.fn>).mockReturnValue(null);

const getRPCMetadata = vi.fn().mockReturnValue(mockRpcMetadata);
vi.mocked(vi.importActual('@opentelemetry/core')).getRPCMetadata = getRPCMetadata;
(vi.importActual('@opentelemetry/core') as unknown as { getRPCMetadata: typeof getRPCMetadata }).getRPCMetadata =
getRPCMetadata;

const routerContext = {
staticHandlerContext: {
Expand All @@ -122,6 +125,55 @@ describe('wrapSentryHandleRequest', () => {

expect(getRPCMetadata).not.toHaveBeenCalled();
});

test('should call flushIfServerless on successful execution', async () => {
const originalHandler = vi.fn().mockResolvedValue('success response');
const wrappedHandler = wrapSentryHandleRequest(originalHandler);

const request = new Request('https://example.com');
const responseStatusCode = 200;
const responseHeaders = new Headers();
const routerContext = { staticHandlerContext: { matches: [] } } as any;
const loadContext = {} as any;

await wrappedHandler(request, responseStatusCode, responseHeaders, routerContext, loadContext);

expect(flushIfServerless).toHaveBeenCalled();
});

test('should call flushIfServerless even when original handler throws an error', async () => {
const mockError = new Error('Handler failed');
const originalHandler = vi.fn().mockRejectedValue(mockError);
const wrappedHandler = wrapSentryHandleRequest(originalHandler);

const request = new Request('https://example.com');
const responseStatusCode = 200;
const responseHeaders = new Headers();
const routerContext = { staticHandlerContext: { matches: [] } } as any;
const loadContext = {} as any;

await expect(
wrappedHandler(request, responseStatusCode, responseHeaders, routerContext, loadContext),
).rejects.toThrow('Handler failed');

expect(flushIfServerless).toHaveBeenCalled();
});

test('should propagate errors from original handler', async () => {
const mockError = new Error('Test error');
const originalHandler = vi.fn().mockRejectedValue(mockError);
const wrappedHandler = wrapSentryHandleRequest(originalHandler);

const request = new Request('https://example.com');
const responseStatusCode = 500;
const responseHeaders = new Headers();
const routerContext = { staticHandlerContext: { matches: [] } } as any;
const loadContext = {} as any;

await expect(wrappedHandler(request, responseStatusCode, responseHeaders, routerContext, loadContext)).rejects.toBe(
mockError,
);
});
});

describe('getMetaTagTransformer', () => {
Expand All @@ -132,68 +184,64 @@ describe('getMetaTagTransformer', () => {
);
});

test('should inject meta tags before closing head tag', done => {
const outputStream = new PassThrough();
const bodyStream = new PassThrough();
const transformer = getMetaTagTransformer(bodyStream);
test('should inject meta tags before closing head tag', () => {
return new Promise<void>(resolve => {
const bodyStream = new PassThrough();
const transformer = getMetaTagTransformer(bodyStream);

let outputData = '';
outputStream.on('data', chunk => {
outputData += chunk.toString();
});
let outputData = '';
bodyStream.on('data', chunk => {
outputData += chunk.toString();
});

outputStream.on('end', () => {
expect(outputData).toContain('<meta name="sentry-trace" content="test-trace-id"></head>');
expect(outputData).not.toContain('</head></head>');
done();
});
bodyStream.on('end', () => {
expect(outputData).toContain('<meta name="sentry-trace" content="test-trace-id"></head>');
expect(outputData).not.toContain('</head></head>');
resolve();
});

transformer.pipe(outputStream);

bodyStream.write('<html><head></head><body>Test</body></html>');
bodyStream.end();
transformer.write('<html><head></head><body>Test</body></html>');
transformer.end();
});
});

test('should not modify chunks without head closing tag', done => {
const outputStream = new PassThrough();
const bodyStream = new PassThrough();
const transformer = getMetaTagTransformer(bodyStream);
test('should not modify chunks without head closing tag', () => {
return new Promise<void>(resolve => {
const bodyStream = new PassThrough();
const transformer = getMetaTagTransformer(bodyStream);

let outputData = '';
outputStream.on('data', chunk => {
outputData += chunk.toString();
});

outputStream.on('end', () => {
expect(outputData).toBe('<html><body>Test</body></html>');
expect(getTraceMetaTags).toHaveBeenCalled();
done();
});
let outputData = '';
bodyStream.on('data', chunk => {
outputData += chunk.toString();
});

transformer.pipe(outputStream);
bodyStream.on('end', () => {
expect(outputData).toBe('<html><body>Test</body></html>');
resolve();
});

bodyStream.write('<html><body>Test</body></html>');
bodyStream.end();
transformer.write('<html><body>Test</body></html>');
transformer.end();
});
});

test('should handle buffer input', done => {
const outputStream = new PassThrough();
const bodyStream = new PassThrough();
const transformer = getMetaTagTransformer(bodyStream);
test('should handle buffer input', () => {
return new Promise<void>(resolve => {
const bodyStream = new PassThrough();
const transformer = getMetaTagTransformer(bodyStream);

let outputData = '';
outputStream.on('data', chunk => {
outputData += chunk.toString();
});
let outputData = '';
bodyStream.on('data', chunk => {
outputData += chunk.toString();
});

outputStream.on('end', () => {
expect(outputData).toContain('<meta name="sentry-trace" content="test-trace-id"></head>');
done();
});
bodyStream.on('end', () => {
expect(outputData).toContain('<meta name="sentry-trace" content="test-trace-id"></head>');
resolve();
});

transformer.pipe(outputStream);

bodyStream.write(Buffer.from('<html><head></head><body>Test</body></html>'));
bodyStream.end();
transformer.write(Buffer.from('<html><head></head><body>Test</body></html>'));
transformer.end();
});
});
});
Loading