Search code examples
javascripttypescriptworkerdeno

How to avoid cached source code in Deno Workers


Good afternoon, I am developing a javascript code execution environment based on the Deno Workers. I also have a Oak web server that handles requests for code change in a script and the compilation and execution of these.

The problem begins when I request the execution of a script (for example console.log ()) and later I modify said code, when trying to execute this script again, Deno executes the Worker before the change, and only considers the change once I restart the Oak server.

export class Runner {
    private task: Task;

    constructor(task: Task) {
        this.task = task;
    }

    async run() {
        new Worker(
            new URL(await joinPath(`tasks/${this.task.id}/output.js`), import.meta.url).href,
            { type: "module" }
        );
    }
}

The Runner class is in charge of initializing the Worker, for each execution request a new instance of Runner is generated and, therefore, of the Worker.

// oak router
router.get("/api/tasks/:id/run", async ctx => {
        const id: any = ctx.params.id;

        if (!id) ctx.throw(500);

        const task: Task = await get(id);
        const compiler: Compiler = new Compiler(task);
        const runner: Runner = new Runner(task);

        await compiler.compile();
        await runner.run();

        ctx.response.body = 'ok';
    });

This is the function that processes the request, which in turn instantiates the Runner class.

Thank you very much in advance.


Solution

  • There's an open issue for this, the cache will be invalidated in the future for dynamic loads.

    A workaround now is to add a querystring in the URL. And change it on every call to new Worker.

    let v = 0;
    export class Runner {
        private task: Task;
    
        constructor(task: Task) {
            this.task = task;
        }
    
        async run() {
            new Worker(
                new URL(await joinPath(`tasks/${this.task.id}/output.js?v=${v++}`), import.meta.url).href,
                { type: "module" }
            );
        }
    }