Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC - Handle when Worker is unsupported #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 25 additions & 3 deletions src/index.js
@@ -1,4 +1,3 @@

/** TODO:
* - pooling (+ load balancing by tracking # of open calls)
* - queueing (worth it? sortof free via postMessage already)
Expand All @@ -23,11 +22,34 @@ export default function workerize(code, options) {
if (typeof code==='function') code = `(${Function.prototype.toString.call(code)})(${exportsObjName})`;
code = toCjs(code, exportsObjName, exports) + `\n(${Function.prototype.toString.call(setup)})(self,${exportsObjName},{})`;
let url = URL.createObjectURL(new Blob([code])),
worker = new Worker(url, options),
term = worker.terminate,
callbacks = {},
counter = 0,
worker,
term,
i;

try {
worker = new Worker(url, options);
term = worker.terminate;
} catch (err) {
// TODO: How to indicate the fallback? console.warn? Property on the export?
// TODO: What's the right way to access the original exports?
const originalExports = new Function(code + `\nreturn ${exportsObjName}`)();
// TODO: Is this the full API? Do we need to add anything else?
worker = {
kill() {},
terminate() {},
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we implement these methods to remove the proxied methods on the worker? Or fine as no-op?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH I'm tempted to not even emulate these since they do nothing. Doing an existence-test for worker.terminate would be a decent way to know if the worker got inlined or not.

expose(methodName) {
worker[i] = function() {
return Promise.resolve().then(() => originalExports[i]([].slice.call(arguments)));
};
},
};
// TODO: Extract to function since it's used below or fine as is?
for (i in exports) if (!(i in worker)) worker.expose(i);
return worker;
}

worker.kill = signal => {
worker.postMessage({ type: 'KILL', signal });
setTimeout(worker.terminate);
Expand Down