-
-
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
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
202624b
feat(core): Add shared `flushIfServerless` function
s1gr1d 4478ec6
fix import
s1gr1d 788f799
accept direct waitUntil function
s1gr1d 2cf8428
make params optional
s1gr1d f703845
add standard flush in cloudflare again
s1gr1d 5360260
remove unused imports
s1gr1d ed97658
revert vercel-specific functionality
s1gr1d 036c380
fix tests solidstart
s1gr1d 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
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; | ||
cursor[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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); | ||
} | ||
} |
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,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); | ||
}); | ||
}); |
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
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.
This comment was marked as outdated.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.