Use compiled module (working with hacked bundle!)

This commit is contained in:
Adria Navarro 2024-01-16 17:27:24 +01:00
parent 17339b7b50
commit 807e9f1687
1 changed files with 40 additions and 15 deletions

View File

@ -14,18 +14,20 @@ export function init() {
setJSRunner((js: string, ctx: Record<string, any>) => { setJSRunner((js: string, ctx: Record<string, any>) => {
return tracer.trace("runJS", {}, span => { return tracer.trace("runJS", {}, span => {
const bbCtx = context.getCurrentContext()! const bbCtx = context.getCurrentContext()!
if (!bbCtx.jsIsolate) { let { jsContext, jsIsolate } = bbCtx
bbCtx.jsIsolate = new ivm.Isolate({ memoryLimit: 64 }) // if (!jsIsolate) {
bbCtx.jsContext = bbCtx.jsIsolate.createContextSync() jsIsolate = new ivm.Isolate({ memoryLimit: 64 })
const helpersModule = bbCtx.jsIsolate.compileModuleSync(helpersSource) jsContext = jsIsolate.createContextSync()
helpersModule.instantiateSync(bbCtx.jsContext, specifier => { const helpersModule = jsIsolate.compileModuleSync(helpersSource)
helpersModule.instantiateSync(jsContext, specifier => {
throw new Error(`No imports allowed. Required: ${specifier}`) throw new Error(`No imports allowed. Required: ${specifier}`)
}) })
} // }
const perRequestLimit = env.JS_PER_REQUEST_TIME_LIMIT_MS const perRequestLimit = env.JS_PER_REQUEST_TIME_LIMIT_MS
if (perRequestLimit) { if (perRequestLimit) {
const cpuMs = Number(bbCtx.jsIsolate.cpuTime) / 1e6 const cpuMs = Number(jsIsolate.cpuTime) / 1e6
if (cpuMs > perRequestLimit) { if (cpuMs > perRequestLimit) {
throw new Error( throw new Error(
`CPU time limit exceeded (${cpuMs}ms > ${perRequestLimit}ms)` `CPU time limit exceeded (${cpuMs}ms > ${perRequestLimit}ms)`
@ -33,19 +35,42 @@ export function init() {
} }
} }
const global = bbCtx.jsContext!.global const global = jsContext!.global
for (const [key, value] of Object.entries(ctx)) { for (const [key, value] of Object.entries(ctx)) {
if (typeof value === "function") { if (key === "helpers") {
// Can't copy functions into the isolate, so we just ignore them // Can't copy the native helpers into the isolate. We just ignore them as they are handled properly from the helpersSource
continue continue
} }
global.setSync(key, new ivm.ExternalCopy(value).copyInto()) global.setSync(key, value)
} }
const script = bbCtx.jsIsolate.compileScriptSync(js) const script = jsIsolate.compileModuleSync(
return script.runSync(bbCtx.jsContext!, { `import helpers from "compiled_module";${js};cb(run());`,
{}
)
script.instantiateSync(jsContext!, specifier => {
if (specifier === "compiled_module") {
return helpersModule
}
throw new Error(`"${specifier}" import not allowed`)
})
let result
global.setSync(
"cb",
new ivm.Callback((value: any) => {
result = value
})
)
script.evaluateSync({
timeout: env.JS_PER_EXECUTION_TIME_LIMIT_MS, timeout: env.JS_PER_EXECUTION_TIME_LIMIT_MS,
}) })
return result
}) })
}) })
} }