openpgpjs / argon2id

Argon2id (RFC 9106) implementation in JS & WebAssembly, optimised for both performance and bundle size
MIT License
27 stars 4 forks source link

Re-loading the Wasm module #4

Closed mitar closed 9 months ago

mitar commented 9 months ago

I do not get the section about memory usage. Could you please provide an example how can one reload the wasm module to clear the memory? So a complete example of loading the module, computing a hash, and then clearing the memory?

mitar commented 9 months ago

I think I figured it out. But it is not about reloading the module and more about re-instantiatating a module? I made the following code:

const simdModule = await WebAssembly.compileStreaming(fetch(simdURL))
const noSimdModule = await WebAssembly.compileStreaming(fetch(noSimdURL))

async function getSIMD(importObject: WebAssembly.Imports) {
  return { instance: await WebAssembly.instantiate(simdModule, importObject), module: simdModule }
}
 async function getNoSIMD(importObject: WebAssembly.Imports) {
  return { instance: await WebAssembly.instantiate(noSimdModule, importObject), module: noSimdModule }
}

I can then call setupWasm every time I need to hash and my understanding is that after that instance if garbage collected, memory and everything is freed?

From what I see you need only instance, so not sure why you require loaded to return WebAssemblyInstantiatedSource which returns both the instance and the module? Now I have to attach module myself in the functions above, because WebAssembly.instantiate with module as a parameter does not return it. I think this is a bad API design for WebAssembly.instantiate. It would simple to just pass module through and have same return value as when you pass a byte array to WebAssembly.instantiate. Anyway, I do not think you should be requiring WebAssemblyInstantiatedSource, but the instance itself?

larabr commented 9 months ago

Hi, reloading the module simply means calling the default export (loadWasm()) again, and getting a new computeHash instance as a result. You also need to make sure you are not keeping around the reference to another, previously returned computeHash function.

so not sure why you require loaded to return WebAssemblyInstantiatedSource which returns both the instance and the module? Now I have to attach module myself in the functions above, because WebAssembly.instantiate with module as a parameter does not return it. I think this is a bad API design for WebAssembly.instantiate.

The API was designed based on our use-cases, so I guess we might simply have missed this second overload of WebAssembly.instantiate. If it's not needed as you say (which I think can be confirmed easily by not passing any module, silencing the TS check), then feel free to open a PR that fixes the type declaration 🙂 . But to be honest, I don't think we'll make a new release just to fix the types.