srijs / rusha

High-performance pure-javascript SHA1 implementation suitable for large binary data, reaching up to half the native speed.
https://npmjs.org/rusha
MIT License
277 stars 32 forks source link

Disabling web worker automagic when required() #42

Closed xuset closed 6 years ago

xuset commented 7 years ago

If rusha is included in a web worker through require('rusha'), it is probably safe to say that the automatic listening for message events is not needed.

Closes #39

JamesKyburz commented 7 years ago

This won't work if the service worker is using browserified code :(

This because module.exports will be defined and the message event listener for the webworker will never be run.

How about exiting early in the webworker on message handler?

  if (!event.data.id) return;
  if (!event.data.data || !event.data.file) return;

The file option is because of my pull request :)

Not 100% perfect I know but would be an improvement.

If this is only a problem when requiring rusha in a serviceworker using some other check. eg. typeof ServiceWorkerGlobalScope which seams only available in a serviceworker worker.

JamesKyburz commented 7 years ago

this pull request would mean hashing is never attempted if the message payload doesn't have a data or file property.

xuset commented 7 years ago

This won't work if the service worker is using browserified code :(

Yeah that's a good point. The idea I had at the time was that if rusha was in some dependency tree then attaching the message listener was probably not wanted. This pr was more of a half measure than anything.

Doing the early return also seems like a half measure to me since the properties id, file, and data are commonly used names. So using these names could potentially result in rusha handling non-intended messages. This gets more complicated when someone isn't using the rusha package directly but rather rusha is deep in some dependency tree. So they have no knowledge that rusha attaches the message listener, and that they cannot send messsages with those property names defined unless they actually want rusha to handle the message.

JamesKyburz commented 7 years ago

The automatic listening of message allows a webworker to be created on the fly.


var reader = new window.FileReader()
reader.onerror = cb
reader.onload = () => {
  var worker = createWorker(rusha)
  worker.addEventListener('message', (e) => {
    // ...
    worker.revoke()
  })
  worker.postMessage({ id: file.name, data: reader.result })
}
reader.readAsArrayBuffer(file)

function createWorker (src) {
  var blob = new window.Blob([src], { type: 'text/javascript' })
  var workerUrl = window.URL.createObjectURL(blob)
  var worker = new window.Worker(workerUrl)
  worker.revoke = () => URL.revokeObjectURL(workerUrl)
  return worker
}

How about disabling the automatic event listener when inside a service worker?

This could be done by checking if self.Clients is defined.