Last active
March 6, 2023 12:41
-
-
Save aachyee/068ab888c4e84892b281be97a69f7479 to your computer and use it in GitHub Desktop.
General eval worker with timeout in deno.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // eval_worker.ts | |
| // General eval worker with timeout in deno. | |
| /// <reference lib="deno.worker" /> | |
| /* | |
| Usage: | |
| import {waitForEvalWorkerResponse} from "./eval_worker.ts" | |
| // await waitForEvalWorkerResponse ( 'javascript code...', 3000 ) | |
| try { | |
| const source1 = 'await fetch("https://api.github.com/users/octocat").then((response)=>{return response.json()}).catch(err=>{return err})'; | |
| const result1 = await waitForEvalWorkerResponse(source1, 3000); | |
| console.log(result1); //=>output JSON | |
| const source2 = 'await (async ()=>{const wait = msec => new Promise(resolve => setTimeout(()=>{resolve()}, msec));console.log("script start");await wait(2000);console.log("2 seconds have passed.");console.log("script end");return 123000+456})()'; | |
| const result2 = await waitForEvalWorkerResponse(source2, 3000); | |
| console.log(result2); //=>123456 | |
| } catch(err) { | |
| console.error(err); | |
| } | |
| */ | |
| const WORKER_PATH: string = "./eval_worker.ts"; | |
| const TIMEOUT_MSEC: number = 3000; | |
| const workerURL: URL = new URL(WORKER_PATH, import.meta.url).href; | |
| export async function waitForEvalWorkerResponse( | |
| source: string, | |
| timeoutMSec: number = TIMEOUT_MSEC) { | |
| const worker: Worker = new Worker(workerURL, { type: "module", deno: false }); | |
| return new Promise((resolve, reject) => { | |
| worker.onmessage = ({ data }) => { | |
| clearTimeout(timerId); | |
| worker.terminate(); | |
| if ( data instanceof Error) { | |
| reject(data); | |
| } else { | |
| resolve(data); | |
| } | |
| }; | |
| worker.postMessage(source); | |
| const timerId = setTimeout(() => { | |
| worker.terminate(); | |
| reject(new Error(`Worker operation timeout (${timeoutMSec} msec)`)); | |
| }, timeoutMSec); | |
| }); | |
| } | |
| self.onmessage = async (e) => { | |
| const AsyncFunction = async function () {}.constructor; | |
| await self.postMessage( await AsyncFunction(`'use strict'; return ${e.data}`)() ); | |
| await self.close(); | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment