Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,14 @@ export const getRequestListener = (
errorHandler?: CustomErrorHandler
overrideGlobalObjects?: boolean
autoCleanupIncoming?: boolean
requestsPerForcedGC?: number
} = {}
) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true
const requestsPerForcedGC = options.requestsPerForcedGC ?? 0
let requestCount = 0
const gc = global.gc as () => void

if (options.overrideGlobalObjects !== false && global.Request !== LightweightRequest) {
Object.defineProperty(global, 'Request', {
value: LightweightRequest,
Expand All @@ -214,6 +219,9 @@ export const getRequestListener = (
value: LightweightResponse,
})
}
if (requestsPerForcedGC && !gc) {
throw new Error('`global.gc` is not available. Please run node with `--expose-gc` flag.')
}

return async (
incoming: IncomingMessage | Http2ServerRequest,
Expand Down Expand Up @@ -281,6 +289,14 @@ export const getRequestListener = (
}
})
}

if (requestsPerForcedGC) {
requestCount++
if (requestCount >= requestsPerForcedGC) {
gc()
requestCount = 0
}
}
})

res = fetchCallback(req, { incoming, outgoing } as HttpBindings) as
Expand Down
1 change: 1 addition & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export const createAdaptorServer = (options: Options): ServerType => {
hostname: options.hostname,
overrideGlobalObjects: options.overrideGlobalObjects,
autoCleanupIncoming: options.autoCleanupIncoming,
requestsPerForcedGC: options.requestsPerForcedGC,
})
// ts will complain about createServerHTTP and createServerHTTP2 not being callable, which works just fine
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export type Options = {
fetch: FetchCallback
overrideGlobalObjects?: boolean
autoCleanupIncoming?: boolean
requestsPerForcedGC?: number
port?: number
hostname?: string
} & ServerOptions
Expand Down
Loading