Skip to content

Commit d158946

Browse files
committed
feat: introduce new option requestsPerForcedGC
1 parent 840c22b commit d158946

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

src/listener.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,14 @@ export const getRequestListener = (
203203
errorHandler?: CustomErrorHandler
204204
overrideGlobalObjects?: boolean
205205
autoCleanupIncoming?: boolean
206+
requestsPerForcedGC?: number
206207
} = {}
207208
) => {
208209
const autoCleanupIncoming = options.autoCleanupIncoming ?? true
210+
const requestsPerForcedGC = options.requestsPerForcedGC ?? 0
211+
let requestCount = 0
212+
const gc = global.gc as () => void
213+
209214
if (options.overrideGlobalObjects !== false && global.Request !== LightweightRequest) {
210215
Object.defineProperty(global, 'Request', {
211216
value: LightweightRequest,
@@ -214,6 +219,9 @@ export const getRequestListener = (
214219
value: LightweightResponse,
215220
})
216221
}
222+
if (requestsPerForcedGC && !gc) {
223+
throw new Error('`global.gc` is not available. Please run node with `--expose-gc` flag.')
224+
}
217225

218226
return async (
219227
incoming: IncomingMessage | Http2ServerRequest,
@@ -281,6 +289,14 @@ export const getRequestListener = (
281289
}
282290
})
283291
}
292+
293+
if (requestsPerForcedGC) {
294+
requestCount++
295+
if (requestCount >= requestsPerForcedGC) {
296+
gc()
297+
requestCount = 0
298+
}
299+
}
284300
})
285301

286302
res = fetchCallback(req, { incoming, outgoing } as HttpBindings) as

src/server.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export const createAdaptorServer = (options: Options): ServerType => {
99
hostname: options.hostname,
1010
overrideGlobalObjects: options.overrideGlobalObjects,
1111
autoCleanupIncoming: options.autoCleanupIncoming,
12+
requestsPerForcedGC: options.requestsPerForcedGC,
1213
})
1314
// ts will complain about createServerHTTP and createServerHTTP2 not being callable, which works just fine
1415
// eslint-disable-next-line @typescript-eslint/no-explicit-any

src/types.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export type Options = {
7171
fetch: FetchCallback
7272
overrideGlobalObjects?: boolean
7373
autoCleanupIncoming?: boolean
74+
requestsPerForcedGC?: number
7475
port?: number
7576
hostname?: string
7677
} & ServerOptions

0 commit comments

Comments
 (0)