Skip to content

Commit 1e1c01c

Browse files
committed
another attempt
1 parent 2a0173e commit 1e1c01c

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

packages/cloudflare/src/request.ts

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

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

54-
// Track whether flush has been scheduled to prevent duplicate calls
55-
let flushScheduled = false;
54+
// Track flush promise to ensure it's only scheduled once
55+
let flushPromise: Promise<boolean> | null = null;
5656
const scheduleFlush = (timeout: number = 2000): void => {
57-
if (!flushScheduled && waitUntil) {
58-
flushScheduled = true;
59-
waitUntil(flush(timeout));
57+
if (!flushPromise && waitUntil) {
58+
flushPromise = flush(timeout);
59+
waitUntil(flushPromise);
6060
}
6161
};
6262

@@ -155,9 +155,12 @@ export function wrapRequestHandler(
155155
})();
156156

157157
// Use waitUntil to keep context alive and flush after span ends
158-
if (waitUntil) {
159-
flushScheduled = true;
160-
waitUntil(streamMonitor.then(() => flush(2000)));
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
163+
waitUntil(streamMonitor);
161164
}
162165

163166
// Return response with client stream

0 commit comments

Comments
 (0)