Skip to content

Commit 8e16917

Browse files
committed
feat(core): add cloudflare flushing logic to core util
1 parent 1df6ff9 commit 8e16917

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { GLOBAL_OBJ } from './worldwide';
2+
3+
export type MinimalCloudflareContext = {
4+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
5+
waitUntil(promise: Promise<any>): void;
6+
};
7+
8+
export const CloudflareContextKey = '__cloudflare-context__';
9+
10+
/**
11+
* Function that delays closing of a Cloudflare lambda until the provided promise is resolved.
12+
*/
13+
export function cloudflareWaitUntil(task: Promise<unknown>): boolean {
14+
try {
15+
const cfContextSymbol = Symbol.for(CloudflareContextKey);
16+
const globalWithCfContext = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
17+
[cfContextSymbol]: {
18+
ctx: MinimalCloudflareContext;
19+
};
20+
};
21+
22+
const context = globalWithCfContext[cfContextSymbol].ctx;
23+
24+
if (typeof context.waitUntil === 'function') {
25+
// eslint-disable-next-line no-console
26+
console.log('flushing with cf');
27+
context.waitUntil(task);
28+
return true;
29+
}
30+
31+
return false;
32+
} catch {
33+
return false;
34+
}
35+
}

packages/core/src/utils/flushIfServerless.ts

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,9 @@
11
import { flush } from '../exports';
2+
import { type MinimalCloudflareContext, CloudflareContextKey, cloudflareWaitUntil } from './cloudflareWaitUntil';
23
import { debug } from './debug-logger';
34
import { vercelWaitUntil } from './vercelWaitUntil';
45
import { GLOBAL_OBJ } from './worldwide';
56

6-
type MinimalCloudflareContext = {
7-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
8-
waitUntil(promise: Promise<any>): void;
9-
};
10-
117
async function flushWithTimeout(timeout: number): Promise<void> {
128
try {
139
debug.log('Flushing events...');
@@ -58,6 +54,14 @@ export async function flushIfServerless(
5854
return;
5955
}
6056

57+
// @ts-expect-error This is not typed
58+
if (GLOBAL_OBJ[Symbol.for(CloudflareContextKey)]) {
59+
// If the cloudflareWaitUntil function is available, use it to flush the events, if not then fallback to the regular flush
60+
if (cloudflareWaitUntil(flushWithTimeout(timeout))) {
61+
return;
62+
}
63+
}
64+
6165
if (typeof process === 'undefined') {
6266
return;
6367
}

0 commit comments

Comments
 (0)