Skip to content

feat(core): Add shared flushIfServerless function #17177

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 8 commits into from
Jul 30, 2025
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context, GLOBAL_OBJ, flush, debug, vercelWaitUntil } from '@sentry/core';
import { Context, flushIfServerless } from '@sentry/core';
import * as SentryNode from '@sentry/node';
import { H3Error } from 'h3';
import type { CapturedErrorContext } from 'nitropack';
Expand Down Expand Up @@ -53,31 +53,3 @@ function extractErrorContext(errorContext: CapturedErrorContext): Context {

return ctx;
}

async function flushIfServerless(): Promise<void> {
const isServerless =
!!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions
!!process.env.LAMBDA_TASK_ROOT || // AWS Lambda
!!process.env.VERCEL ||
!!process.env.NETLIFY;

// @ts-expect-error This is not typed
if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {
vercelWaitUntil(flushWithTimeout());
} else if (isServerless) {
await flushWithTimeout();
}
}

async function flushWithTimeout(): Promise<void> {
const sentryClient = SentryNode.getClient();
const isDebug = sentryClient ? sentryClient.getOptions().debug : false;

try {
isDebug && debug.log('Flushing events...');
await flush(2000);
isDebug && debug.log('Done flushing events');
} catch (e) {
isDebug && debug.log('Error while flushing events:\n', e);
}
}
15 changes: 2 additions & 13 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import type { RequestEventData, Scope, SpanAttributes } from '@sentry/core';
import {
addNonEnumerableProperty,
debug,
extractQueryParamsFromUrl,
flushIfServerless,
objectify,
stripUrlQueryAndFragment,
vercelWaitUntil,
winterCGRequestToRequestData,
} from '@sentry/core';
import {
captureException,
continueTrace,
flush,
getActiveSpan,
getClient,
getCurrentScope,
Expand Down Expand Up @@ -233,16 +231,7 @@ async function instrumentRequest(
);
return res;
} finally {
vercelWaitUntil(
(async () => {
// Flushes pending Sentry events with a 2-second timeout and in a way that cannot create unhandled promise rejections.
try {
await flush(2000);
} catch (e) {
debug.log('Error while flushing events:\n', e);
}
})(),
);
await flushIfServerless();

This comment was marked as outdated.

}
// TODO: flush if serverless (first extract function)
},
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ export { callFrameToStackFrame, watchdogTimer } from './utils/anr';
export { LRUMap } from './utils/lru';
export { generateTraceId, generateSpanId } from './utils/propagationContext';
export { vercelWaitUntil } from './utils/vercelWaitUntil';
export { flushIfServerless } from './utils/flushIfServerless';
export { SDK_VERSION } from './utils/version';
export { getDebugImagesForResources, getFilenameToDebugIdMap } from './utils/debug-ids';
export { escapeStringForRegex } from './vendor/escapeStringForRegex';
Expand Down
77 changes: 77 additions & 0 deletions packages/core/src/utils/flushIfServerless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { flush } from '../exports';
import { debug } from './debug-logger';
import { vercelWaitUntil } from './vercelWaitUntil';
import { GLOBAL_OBJ } from './worldwide';

type MinimalCloudflareContext = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
waitUntil(promise: Promise<any>): void;
};

async function flushWithTimeout(timeout: number): Promise<void> {
try {
debug.log('Flushing events...');
await flush(timeout);
debug.log('Done flushing events');
} catch (e) {
debug.log('Error while flushing events:\n', e);
}
}

/**
* Flushes the event queue with a timeout in serverless environments to ensure that events are sent to Sentry before the
* serverless function execution ends.
*
* The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.
*
* This function is aware of the following serverless platforms:
* - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).
* If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).
* - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.
* - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables
* and uses a regular `await flush()`.
*
* @internal This function is supposed for internal Sentry SDK usage only.
* @hidden
*/
export async function flushIfServerless(
params: // eslint-disable-next-line @typescript-eslint/no-explicit-any
| { timeout?: number; cloudflareWaitUntil?: (task: Promise<any>) => void }
| { timeout?: number; cloudflareCtx?: MinimalCloudflareContext } = {},
): Promise<void> {
const { timeout = 2000 } = params;

if ('cloudflareWaitUntil' in params && typeof params?.cloudflareWaitUntil === 'function') {
params.cloudflareWaitUntil(flushWithTimeout(timeout));
return;
}

if ('cloudflareCtx' in params && typeof params.cloudflareCtx?.waitUntil === 'function') {
params.cloudflareCtx.waitUntil(flushWithTimeout(timeout));
return;
}

// @ts-expect-error This is not typed
if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {
// Vercel has a waitUntil equivalent that works without execution context
vercelWaitUntil(flushWithTimeout(timeout));
return;
}

if (typeof process === 'undefined') {
return;
}

const isServerless =
!!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions
!!process.env.LAMBDA_TASK_ROOT || // AWS Lambda
!!process.env.K_SERVICE || // Google Cloud Run
!!process.env.CF_PAGES || // Cloudflare Pages
!!process.env.VERCEL ||
!!process.env.NETLIFY;

if (isServerless) {
// Use regular flush for environments without a generic waitUntil mechanism
await flushWithTimeout(timeout);
}
}
128 changes: 128 additions & 0 deletions packages/core/test/lib/utils/flushIfServerless.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import * as flushModule from '../../../src/exports';
import { flushIfServerless } from '../../../src/utils/flushIfServerless';
import * as vercelWaitUntilModule from '../../../src/utils/vercelWaitUntil';
import { GLOBAL_OBJ } from '../../../src/utils/worldwide';

describe('flushIfServerless', () => {
let originalProcess: typeof process;

beforeEach(() => {
vi.resetAllMocks();
originalProcess = global.process;
});

afterEach(() => {
vi.restoreAllMocks();
});

test('should bind context (preserve `this`) when calling waitUntil from the Cloudflare execution context', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);

// Mock Cloudflare context with `waitUntil` (which should be called if `this` is bound correctly)
const mockCloudflareCtx = {
contextData: 'test-data',
waitUntil: function (promise: Promise<unknown>) {
// This will fail if 'this' is not bound correctly
expect(this.contextData).toBe('test-data');
return promise;
},
};

const waitUntilSpy = vi.spyOn(mockCloudflareCtx, 'waitUntil');

await flushIfServerless({ cloudflareCtx: mockCloudflareCtx });

expect(waitUntilSpy).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(2000);
});

test('should use cloudflare waitUntil when valid cloudflare context is provided', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const mockCloudflareCtx = {
waitUntil: vi.fn(),
};

await flushIfServerless({ cloudflareCtx: mockCloudflareCtx, timeout: 5000 });

expect(mockCloudflareCtx.waitUntil).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(5000);
});

test('should use cloudflare waitUntil when Cloudflare `waitUntil` is provided', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const mockCloudflareCtx = {
waitUntil: vi.fn(),
};

await flushIfServerless({ cloudflareWaitUntil: mockCloudflareCtx.waitUntil, timeout: 5000 });

expect(mockCloudflareCtx.waitUntil).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(5000);
});

test('should ignore cloudflare context when waitUntil is not a function (and use Vercel waitUntil instead)', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const vercelWaitUntilSpy = vi.spyOn(vercelWaitUntilModule, 'vercelWaitUntil').mockImplementation(() => {});

// Mock Vercel environment
// @ts-expect-error This is not typed
GLOBAL_OBJ[Symbol.for('@vercel/request-context')] = { get: () => ({ waitUntil: vi.fn() }) };

const mockCloudflareCtx = {
waitUntil: 'not-a-function', // Invalid waitUntil
};

// @ts-expect-error Using the wrong type here on purpose
await flushIfServerless({ cloudflareCtx: mockCloudflareCtx });

expect(vercelWaitUntilSpy).toHaveBeenCalledTimes(1);
expect(flushMock).toHaveBeenCalledWith(2000);
});

test('should handle multiple serverless environment variables simultaneously', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);

global.process = {
...originalProcess,
env: {
...originalProcess.env,
LAMBDA_TASK_ROOT: '/var/task',
VERCEL: '1',
NETLIFY: 'true',
CF_PAGES: '1',
},
};

await flushIfServerless({ timeout: 4000 });

expect(flushMock).toHaveBeenCalledWith(4000);
});

test('should use default timeout when not specified', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);
const mockCloudflareCtx = {
waitUntil: vi.fn(),
};

await flushIfServerless({ cloudflareCtx: mockCloudflareCtx });

expect(flushMock).toHaveBeenCalledWith(2000);
});

test('should handle zero timeout value', async () => {
const flushMock = vi.spyOn(flushModule, 'flush').mockResolvedValue(true);

global.process = {
...originalProcess,
env: {
...originalProcess.env,
LAMBDA_TASK_ROOT: '/var/task',
},
};

await flushIfServerless({ timeout: 0 });

expect(flushMock).toHaveBeenCalledWith(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ import {
vercelWaitUntil,
withIsolationScope,
} from '@sentry/core';
import { flushSafelyWithTimeout } from '../common/utils/responseEnd';
import { DEBUG_BUILD } from './debug-build';
import { isNotFoundNavigationError, isRedirectNavigationError } from './nextNavigationErrorUtils';
import { flushSafelyWithTimeout } from './utils/responseEnd';

interface Options {
formData?: FormData;
Expand Down
2 changes: 1 addition & 1 deletion packages/nextjs/src/common/wrapMiddlewareWithSentry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ import {
winterCGRequestToRequestData,
withIsolationScope,
} from '@sentry/core';
import { flushSafelyWithTimeout } from '../common/utils/responseEnd';
import type { EdgeRouteHandler } from '../edge/types';
import { flushSafelyWithTimeout } from './utils/responseEnd';

/**
* Wraps Next.js middleware with Sentry error and performance instrumentation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import {
} from '@sentry/core';
import { isNotFoundNavigationError, isRedirectNavigationError } from '../common/nextNavigationErrorUtils';
import type { ServerComponentContext } from '../common/types';
import { flushSafelyWithTimeout } from '../common/utils/responseEnd';
import { TRANSACTION_ATTR_SENTRY_TRACE_BACKFILL } from './span-attributes-with-logic-attached';
import { flushSafelyWithTimeout } from './utils/responseEnd';
import { commonObjectToIsolationScope, commonObjectToPropagationContext } from './utils/tracingUtils';
import { getSanitizedRequestUrl } from './utils/urls';

Expand Down
4 changes: 2 additions & 2 deletions packages/nuxt/src/runtime/hooks/captureErrorHook.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { captureException, getClient, getCurrentScope } from '@sentry/core';
import { captureException, flushIfServerless, getClient, getCurrentScope } from '@sentry/core';
// eslint-disable-next-line import/no-extraneous-dependencies
import { H3Error } from 'h3';
import type { CapturedErrorContext } from 'nitropack/types';
import { extractErrorContext, flushIfServerless } from '../utils';
import { extractErrorContext } from '../utils';

/**
* Hook that can be added in a Nitro plugin. It captures an error and sends it to Sentry.
Expand Down
10 changes: 8 additions & 2 deletions packages/nuxt/src/runtime/plugins/sentry.server.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { debug, getDefaultIsolationScope, getIsolationScope, withIsolationScope } from '@sentry/core';
import {
debug,
flushIfServerless,
getDefaultIsolationScope,
getIsolationScope,
withIsolationScope,
} from '@sentry/core';
// eslint-disable-next-line import/no-extraneous-dependencies
import { type EventHandler } from 'h3';
// eslint-disable-next-line import/no-extraneous-dependencies
import { defineNitroPlugin } from 'nitropack/runtime';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
import { sentryCaptureErrorHook } from '../hooks/captureErrorHook';
import { updateRouteBeforeResponse } from '../hooks/updateRouteBeforeResponse';
import { addSentryTracingMetaTags, flushIfServerless } from '../utils';
import { addSentryTracingMetaTags } from '../utils';

export default defineNitroPlugin(nitroApp => {
nitroApp.h3App.handler = patchEventHandler(nitroApp.h3App.handler);
Expand Down
32 changes: 1 addition & 31 deletions packages/nuxt/src/runtime/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ClientOptions, Context, SerializedTraceData } from '@sentry/core';
import { captureException, debug, flush, getClient, getTraceMetaTags, GLOBAL_OBJ, vercelWaitUntil } from '@sentry/core';
import { captureException, debug, getClient, getTraceMetaTags } from '@sentry/core';
import type { VueOptions } from '@sentry/vue/src/types';
import type { CapturedErrorContext } from 'nitropack/types';
import type { NuxtRenderHTMLContext } from 'nuxt/app';
Expand Down Expand Up @@ -85,33 +85,3 @@ export function reportNuxtError(options: {
});
});
}

async function flushWithTimeout(): Promise<void> {
try {
debug.log('Flushing events...');
await flush(2000);
debug.log('Done flushing events');
} catch (e) {
debug.log('Error while flushing events:\n', e);
}
}

/**
* Flushes if in a serverless environment
*/
export async function flushIfServerless(): Promise<void> {
const isServerless =
!!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions
!!process.env.LAMBDA_TASK_ROOT || // AWS Lambda
!!process.env.K_SERVICE || // Google Cloud Run
!!process.env.CF_PAGES || // Cloudflare
!!process.env.VERCEL ||
!!process.env.NETLIFY;

// @ts-expect-error This is not typed
if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {
vercelWaitUntil(flushWithTimeout());
} else if (isServerless) {
await flushWithTimeout();
}
}
Loading
Loading