Use wrapper for queries
This commit is contained in:
parent
7693a1fc69
commit
e4285e30f1
|
@ -1,63 +1,22 @@
|
||||||
import ivm from "isolated-vm"
|
import env from "../environment"
|
||||||
|
import { IsolatedVM } from "../jsRunner/vm"
|
||||||
|
|
||||||
const JS_TIMEOUT_MS = 1000
|
const JS_TIMEOUT_MS = 1000
|
||||||
|
|
||||||
class ScriptRunner {
|
class ScriptRunner {
|
||||||
vm: IsolatedVM
|
#code
|
||||||
|
|
||||||
constructor(script: string, context: any) {
|
constructor(script: string, context: any) {
|
||||||
const code = `let fn = () => {\n${script}\n}; results.out = fn();`
|
this.#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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
execute() {
|
execute() {
|
||||||
this.vm.runScript()
|
const vm = new IsolatedVM({
|
||||||
const results = this.vm.getValue("results")
|
memoryLimit: env.JS_RUNNER_MEMORY_LIMIT,
|
||||||
return results.out
|
timeout: JS_TIMEOUT_MS,
|
||||||
}
|
}).withHelpers()
|
||||||
}
|
const result = vm.execute(this.#code)
|
||||||
|
|
||||||
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()
|
|
||||||
return result
|
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
|
export default ScriptRunner
|
||||||
|
|
Loading…
Reference in New Issue