Use wrapper for queries

This commit is contained in:
Adria Navarro 2024-02-08 00:46:50 +01:00
parent 7693a1fc69
commit e4285e30f1
1 changed files with 10 additions and 51 deletions

View File

@ -1,63 +1,22 @@
import ivm from "isolated-vm"
import env from "../environment"
import { IsolatedVM } from "../jsRunner/vm"
const JS_TIMEOUT_MS = 1000
class ScriptRunner {
vm: IsolatedVM
#code
constructor(script: string, context: any) {
const code = `let fn = () => {\n${script}\n}; results.out = fn();`
this.vm = new IsolatedVM({ memoryLimit: 8 })
this.vm.context = {
...context,
results: { out: "" },
}
this.vm.code = code
this.#code = `let fn = () => {\n${script}\n}; results.out = fn();`
}
execute() {
this.vm.runScript()
const results = this.vm.getValue("results")
return results.out
}
}
class IsolatedVM {
isolate: ivm.Isolate
vm: ivm.Context
#jail: ivm.Reference
script: any
constructor({ memoryLimit }: { memoryLimit: number }) {
this.isolate = new ivm.Isolate({ memoryLimit })
this.vm = this.isolate.createContextSync()
this.#jail = this.vm.global
this.#jail.setSync("global", this.#jail.derefInto())
}
getValue(key: string) {
const ref = this.vm.global.getSync(key, { reference: true })
const result = ref.copySync()
ref.release()
const vm = new IsolatedVM({
memoryLimit: env.JS_RUNNER_MEMORY_LIMIT,
timeout: JS_TIMEOUT_MS,
}).withHelpers()
const result = vm.execute(this.#code)
return result
}
set context(context: Record<string, any>) {
for (let key in context) {
this.#jail.setSync(key, this.copyRefToVm(context[key]))
}
}
set code(code: string) {
this.script = this.isolate.compileScriptSync(code)
}
runScript() {
this.script.runSync(this.vm, { timeout: JS_TIMEOUT_MS })
}
copyRefToVm(value: Object): ivm.Copy<Object> {
return new ivm.ExternalCopy(value).copyInto({ release: true })
}
}
export default ScriptRunner