d-markey / squadron

Multithreading and worker thread pool for Dart / Flutter, to offload CPU-bound and heavy I/O tasks to Isolate or Web Worker threads.
https://pub.dev/packages/squadron
MIT License
79 stars 0 forks source link

Provide access to webworker instance. #20

Closed nullrocket closed 1 year ago

nullrocket commented 1 year ago

I know this might not make sense for the general case using squadron, but I need to install a message handler outside of squadron directly on the web worker itself at creation time to handle some pre-existing javascript shims when targeting the browser.

I forked squadron and just added my handler manually as a quick solution, but I'm wondering if it would make sense to provide a way to pass a call back that recieves the webworker directly when initializing the service.

Currently web worker creation looks like this. https://github.com/d-markey/squadron/blob/ccc11aa7f18aaecade60ac3bf13e52af6b302d6b/lib/src/browser/_channel.dart#L219-L222

I would like to do something like this, with onCreateWorker being a callback passed in at service instantiation.

 final channel = _JsChannel._(); 
 final com = web.MessageChannel(); 
 final worker = web.Worker(entryPoint); 
 onCreateWorker(worker);
d-markey commented 1 year ago

Hello @nullrocket,

I'll try and work something out but I'd like to make this cross-platform. I'm not sure this would make sense for Isolates but I'd like to ensure Squadron provides features that work on all platforms.

nullrocket commented 1 year ago

Hi, A few days after I submitted this issue I found I no longer needed it since recent updates to Safari eliminated the original reason for the workaround. Not to say that it wouldn't still be useful to have for other use cases, or if similar issues arise in the future.

The initial issue was a compound one specific to Safari.

  1. Safari would not correctly send SharedArrayBuffer over Message Ports, only directly using postMessage on the worker.
  2. Safari also wouldnt allow web workers to directly spawn children workers.

This combination of issues required an awkward orchestration of messages directly to the main thread to spawn children and bounce messages through the main thread, because of issue 1 above it couldn't be sent/bounced through Squadron because it needed to post directly to and from the worker, not a message port.

Spawning child workers wass fixed in Safari 16.4 and the other issue of sending SharedArrayBuffer correctly over message ports was fixed sometime in the 16 series releases, I'm not sure exactly which release.

I'm happy to pin support / compatibility for my own work to require Safari 16.4 in order to avoid the workarounds. So perhaps this issue is more of a feature request / nice to have than a need now.

d-markey commented 1 year ago

Thanks for the detailed feedback. I've almost completed implementing this feature so it will ship anyway in the next release. Could prove useful to someone else after all!