-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
s1gr1d
wants to merge
2
commits into
develop
Choose a base branch
from
sig/flushIfServerless-core
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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
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
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
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,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); | ||
} | ||
} |
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,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); | ||
}); | ||
}); |
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
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
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.
There was a problem hiding this comment.
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
toawait flushIfServerless()
introduces blocking behavior in serverless environments other than Vercel or Cloudflare (e.g., AWS Lambda, Google Cloud Functions). WhileflushIfServerless
uses non-blocking approaches for Vercel/Cloudflare, it falls back to a blockingawait flush()
in other environments, potentially impacting middleware performance and response times.Locations (1)
packages/astro/src/server/middleware.ts#L233-L234
Fix in Cursor • Fix in Web