Skip to content

Commit 292331d

Browse files
authored
fix: track background work pre batchers (#423)
1 parent 296e8fe commit 292331d

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

src/run/next.cts

+34-7
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,46 @@ const ResponseCache = require('next/dist/server/response-cache/index.js').defaul
2222
const originalGet = ResponseCache.prototype.get
2323
ResponseCache.prototype.get = function get(...getArgs: unknown[]) {
2424
if (!this.didAddBackgroundWorkTracking) {
25-
const originalBatcherBatch = this.batcher.batch
26-
this.batcher.batch = async (key: string, fn: (...args: unknown[]) => unknown) => {
27-
const trackedFn = async (...workFnArgs: unknown[]) => {
28-
const workPromise = fn(...workFnArgs)
25+
if (typeof this.batcher !== 'undefined') {
26+
const originalBatcherBatch = this.batcher.batch
27+
this.batcher.batch = async (key: string, fn: (...args: unknown[]) => unknown) => {
28+
const trackedFn = async (...workFnArgs: unknown[]) => {
29+
const workPromise = fn(...workFnArgs)
30+
const requestContext = getRequestContext()
31+
if (requestContext && workPromise instanceof Promise) {
32+
requestContext.trackBackgroundWork(workPromise)
33+
}
34+
return await workPromise
35+
}
36+
37+
return originalBatcherBatch.call(this.batcher, key, trackedFn)
38+
}
39+
} else if (typeof this.pendingResponses !== 'undefined') {
40+
const backgroundWork = new Map<string, () => void>()
41+
42+
const originalPendingResponsesSet = this.pendingResponses.set
43+
this.pendingResponses.set = async (key: string, value: unknown) => {
2944
const requestContext = getRequestContext()
30-
if (requestContext && workPromise instanceof Promise) {
45+
if (requestContext && !this.pendingResponses.has(key)) {
46+
const workPromise = new Promise<void>((_resolve) => {
47+
backgroundWork.set(key, _resolve)
48+
})
49+
3150
requestContext.trackBackgroundWork(workPromise)
3251
}
33-
return await workPromise
52+
return originalPendingResponsesSet.call(this.pendingResponses, key, value)
3453
}
3554

36-
return originalBatcherBatch.call(this.batcher, key, trackedFn)
55+
const originalPendingResponsesDelete = this.pendingResponses.delete
56+
this.pendingResponses.delete = async (key: string) => {
57+
const _resolve = backgroundWork.get(key)
58+
if (_resolve) {
59+
_resolve()
60+
}
61+
return originalPendingResponsesDelete.call(this.pendingResponses, key)
62+
}
3763
}
64+
3865
this.didAddBackgroundWorkTracking = true
3966
}
4067
return originalGet.apply(this, getArgs)

0 commit comments

Comments
 (0)