From ba002f96492fd311cb0396262b4f77c2edb6f8f5 Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Fri, 2 Feb 2024 09:30:33 +0000 Subject: [PATCH] Clean up isolates when a request is finished. --- packages/backend-core/src/context/types.ts | 1 + packages/server/src/jsRunner/index.ts | 8 ++++++++ packages/server/src/middleware/cleanup.ts | 16 ++++++++++++++++ 3 files changed, 25 insertions(+) create mode 100644 packages/server/src/middleware/cleanup.ts diff --git a/packages/backend-core/src/context/types.ts b/packages/backend-core/src/context/types.ts index cc052ca505..dad1af3bf8 100644 --- a/packages/backend-core/src/context/types.ts +++ b/packages/backend-core/src/context/types.ts @@ -15,4 +15,5 @@ export type ContextMap = { jsContext: Context helpersModule: Module } + cleanup?: (() => void | Promise)[] } diff --git a/packages/server/src/jsRunner/index.ts b/packages/server/src/jsRunner/index.ts index 8e529d533d..9441a74d07 100644 --- a/packages/server/src/jsRunner/index.ts +++ b/packages/server/src/jsRunner/index.ts @@ -115,6 +115,14 @@ export function init() { } bbCtx.isolateRefs = { jsContext, jsIsolate, helpersModule } + if (!bbCtx.cleanup) { + bbCtx.cleanup = [] + } + bbCtx.cleanup.push(() => { + helpersModule.release() + jsContext.release() + jsIsolate.dispose() + }) } let { jsIsolate, jsContext, helpersModule } = bbCtx.isolateRefs! diff --git a/packages/server/src/middleware/cleanup.ts b/packages/server/src/middleware/cleanup.ts new file mode 100644 index 0000000000..5204d5cfb1 --- /dev/null +++ b/packages/server/src/middleware/cleanup.ts @@ -0,0 +1,16 @@ +import { Ctx } from "@budibase/types" +import { context } from "@budibase/backend-core" + +export default async (ctx: Ctx, next: any) => { + const resp = next() + + const current = context.getCurrentContext() + if (current?.cleanup) { + for (let fn of current.cleanup || []) { + await fn() + } + delete current.cleanup + } + + return resp +}