Skip to content

Commit 9526eeb

Browse files
committed
add flush function
1 parent c56d84d commit 9526eeb

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

packages/astro/debug-build.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
declare const __DEBUG_BUILD__: boolean;
2+
3+
/**
4+
* This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.
5+
*
6+
* ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.
7+
*/
8+
export const DEBUG_BUILD = __DEBUG_BUILD__;

packages/astro/src/server/middleware.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
44
captureException,
55
continueTrace,
6+
flush,
67
getActiveSpan,
78
getClient,
89
getCurrentScope,
@@ -14,11 +15,14 @@ import {
1415
import type { Scope, SpanAttributes } from '@sentry/types';
1516
import {
1617
addNonEnumerableProperty,
18+
logger,
1719
objectify,
1820
stripUrlQueryAndFragment,
21+
vercelWaitUntil,
1922
winterCGRequestToRequestData,
2023
} from '@sentry/utils';
2124
import type { APIContext, MiddlewareResponseHandler } from 'astro';
25+
import { DEBUG_BUILD } from '../../debug-build';
2226

2327
type MiddlewareOptions = {
2428
/**
@@ -188,6 +192,8 @@ async function instrumentRequest(
188192
} catch (e) {
189193
sendErrorToSentry(e);
190194
throw e;
195+
} finally {
196+
vercelWaitUntil(flushSafelyWithTimeout());
191197
}
192198
// TODO: flush if serverless (first extract function)
193199
},
@@ -213,6 +219,19 @@ function addMetaTagToHead(htmlChunk: string): string {
213219
return htmlChunk.replace('<head>', content);
214220
}
215221

222+
/**
223+
* Flushes pending Sentry events with a 2-second timeout and in a way that cannot create unhandled promise rejections.
224+
*/
225+
export async function flushSafelyWithTimeout(): Promise<void> {
226+
try {
227+
DEBUG_BUILD && logger.log('Flushing events...');
228+
await flush(2000);
229+
DEBUG_BUILD && logger.log('Done flushing events');
230+
} catch (e) {
231+
DEBUG_BUILD && logger.log('Error while flushing events:\n', e);
232+
}
233+
}
234+
216235
/**
217236
* Interpolates the route from the URL and the passed params.
218237
* Best we can do to get a route name instead of a raw URL.

0 commit comments

Comments
 (0)