Skip to content

Commit 2875b4f

Browse files
committed
this is better
1 parent 1e1c01c commit 2875b4f

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

packages/cloudflare/src/request.ts

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,14 @@ export function wrapRequestHandler(
5151

5252
const waitUntil = context?.waitUntil?.bind?.(context);
5353

54-
// Track flush promise to ensure it's only scheduled once
55-
let flushPromise: Promise<boolean> | null = null;
54+
// Track whether flush has been scheduled globally for this request
55+
let flushScheduled = false;
5656
const scheduleFlush = (timeout: number = 2000): void => {
57-
if (!flushPromise && waitUntil) {
58-
flushPromise = flush(timeout);
59-
waitUntil(flushPromise);
57+
if (flushScheduled || !waitUntil) {
58+
return;
6059
}
60+
flushScheduled = true;
61+
waitUntil(flush(timeout));
6162
};
6263

6364
const client = init({ ...options, ctx: context });
@@ -151,15 +152,12 @@ export function wrapRequestHandler(
151152
clearTimeout(timeout);
152153
reader.releaseLock();
153154
span.end();
155+
// Always schedule flush exactly once
156+
scheduleFlush();
154157
}
155158
})();
156159

157-
// Use waitUntil to keep context alive and flush after span ends
158-
if (waitUntil && !flushPromise) {
159-
flushPromise = streamMonitor.then(() => flush(2000));
160-
waitUntil(flushPromise);
161-
} else if (waitUntil && flushPromise) {
162-
// Just wait for the stream to complete
160+
if (waitUntil) {
163161
waitUntil(streamMonitor);
164162
}
165163

0 commit comments

Comments
 (0)