MCPcopy Create free account
hub / github.com/Kong/insomnia / getWorker

Function getWorker

packages/insomnia/src/scripting/run-script-quickjs.ts:54–114  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

52};
53
54const getWorker = (): Worker => {
55 if (worker) {
56 return worker;
57 }
58 // eslint-disable-next-line @typescript-eslint/ban-ts-comment -- see templating-handler.ts's identical pattern
59 // @ts-ignore -- inso transpiles to commonjs so doesn't play nice with this
60 const instance = new Worker(new URL('quickjs-script.worker.ts', import.meta.url), { type: 'module' });
61
62 instance.addEventListener('message', (event: MessageEvent<WorkerResponse>) => {
63 const { id } = event.data;
64 const request = pending.get(id);
65 if (!request) {
66 return;
67 }
68 pending.delete(id);
69 if ('error' in event.data) {
70 const err = new Error(event.data.error.message);
71 if (event.data.error.name) {
72 err.name = event.data.error.name;
73 }
74 if (event.data.error.stack) {
75 err.stack = event.data.error.stack;
76 }
77 request.reject(err);
78 } else {
79 request.resolve(event.data.result);
80 }
81
82 // The engine aborted its WASM module while cleaning up (see the script engine's
83 // ENGINE_FAULT_MESSAGE). The run above is still valid and has already been settled, but this
84 // worker caches that module for every later script, so take it out of rotation. Retiring after
85 // settling means the caller never sees this as a failure.
86 if (event.data.engineFaulted) {
87 retireWorker(instance);
88 } else {
89 terminateIfDrained(instance);
90 }
91 });
92
93 // A crash in the worker's global scope (e.g. an unhandled rejection outside our own try/catch)
94 // otherwise leaves every in-flight caller hanging forever. Reject them and drop the worker so the
95 // next call gets a fresh one instead of reusing a dead thread.
96 instance.addEventListener('error', event => {
97 const err = new Error(`QuickJS sandbox worker crashed: ${event.message}`);
98 // Only this worker's runs — a retired worker draining alongside a live one must not take the
99 // live one's callers down with it.
100 pending.forEach((request, id) => {
101 if (request.instance === instance) {
102 pending.delete(id);
103 request.reject(err);
104 }
105 });
106 retiring.delete(instance);
107 if (worker === instance) {
108 worker = null;
109 }
110 });
111

Callers 1

runScriptInQuickJsFunction · 0.85

Calls 6

retireWorkerFunction · 0.85
terminateIfDrainedFunction · 0.85
rejectMethod · 0.80
getMethod · 0.65
addEventListenerMethod · 0.45
resolveMethod · 0.45

Tested by

no test coverage detected