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

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Blocking Behavior in Non-Vercel Serverless Environments

The change from vercelWaitUntil to await flushIfServerless() introduces blocking behavior in serverless environments other than Vercel or Cloudflare (e.g., AWS Lambda, Google Cloud Functions). While flushIfServerless uses non-blocking approaches for Vercel/Cloudflare, it falls back to a blocking await flush() in other environments, potentially impacting middleware performance and response times.

Locations (1)

Fix in CursorFix in Web

}
// TODO: flush if serverless (first extract function)
},
Expand Down
15 changes: 5 additions & 10 deletions packages/cloudflare/src/handler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
captureException,
flush,
flushIfServerless,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
Expand Down Expand Up @@ -74,7 +74,6 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
const [event, env, context] = args;
return withIsolationScope(isolationScope => {
const options = getFinalOptions(optionsCallback(env), env);
const waitUntil = context.waitUntil.bind(context);

const client = init({ ...options, ctx: context });
isolationScope.setClient(client);
Expand All @@ -100,7 +99,7 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
throw e;
} finally {
waitUntil(flush(2000));
await flushIfServerless({ cloudflareCtx: context });
}
},
);
Expand All @@ -117,7 +116,6 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
const [emailMessage, env, context] = args;
return withIsolationScope(isolationScope => {
const options = getFinalOptions(optionsCallback(env), env);
const waitUntil = context.waitUntil.bind(context);

const client = init({ ...options, ctx: context });
isolationScope.setClient(client);
Expand All @@ -141,7 +139,7 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
throw e;
} finally {
waitUntil(flush(2000));
await flushIfServerless({ cloudflareCtx: context });
}
},
);
Expand All @@ -159,7 +157,6 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM

return withIsolationScope(isolationScope => {
const options = getFinalOptions(optionsCallback(env), env);
const waitUntil = context.waitUntil.bind(context);

const client = init({ ...options, ctx: context });
isolationScope.setClient(client);
Expand Down Expand Up @@ -191,7 +188,7 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
throw e;
} finally {
waitUntil(flush(2000));
await flushIfServerless({ cloudflareCtx: context });
}
},
);
Expand All @@ -210,8 +207,6 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
return withIsolationScope(async isolationScope => {
const options = getFinalOptions(optionsCallback(env), env);

const waitUntil = context.waitUntil.bind(context);

const client = init({ ...options, ctx: context });
isolationScope.setClient(client);

Expand All @@ -223,7 +218,7 @@ export function withSentry<Env = unknown, QueueHandlerMessage = unknown, CfHostM
captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
throw e;
} finally {
waitUntil(flush(2000));
await flushIfServerless({ cloudflareCtx: context });
}
});
},
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
72 changes: 72 additions & 0 deletions packages/core/src/utils/flushIfServerless.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
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.
* - 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: {
timeout?: number;
cloudflareCtx?: MinimalCloudflareContext;
} = {},
): Promise<void> {
const { timeout = 2000, cloudflareCtx } = params;

if (cloudflareCtx && typeof cloudflareCtx.waitUntil === 'function') {
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);
}
}
116 changes: 116 additions & 0 deletions packages/core/test/lib/utils/flushIfServerless.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
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', 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 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);
});
});
5 changes: 2 additions & 3 deletions packages/nextjs/src/common/captureRequestError.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { RequestEventData } from '@sentry/core';
import { captureException, headersToDict, vercelWaitUntil, withScope } from '@sentry/core';
import { flushSafelyWithTimeout } from './utils/responseEnd';
import { captureException, flushIfServerless, headersToDict, withScope } from '@sentry/core';

type RequestInfo = {
path: string;
Expand Down Expand Up @@ -41,6 +40,6 @@ export function captureRequestError(error: unknown, request: RequestInfo, errorC
},
});

vercelWaitUntil(flushSafelyWithTimeout());
flushIfServerless().catch(() => /* no-op */ {});
});
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { captureException, httpRequestToRequestData, vercelWaitUntil, withScope } from '@sentry/core';
import { captureException, flushIfServerless, httpRequestToRequestData, withScope } from '@sentry/core';
import type { NextPageContext } from 'next';
import { flushSafelyWithTimeout } from '../utils/responseEnd';

type ContextOrProps = {
req?: NextPageContext['req'];
Expand Down Expand Up @@ -54,5 +53,5 @@ export async function captureUnderscoreErrorException(contextOrProps: ContextOrP
});
});

vercelWaitUntil(flushSafelyWithTimeout());
flushIfServerless().catch(() => /* no-op */ {});
}
Loading
Loading