argon2-wasi icon indicating copy to clipboard operation
argon2-wasi copied to clipboard

Error when running in Cloudflare Workers

Open timothymiller opened this issue 1 year ago • 2 comments

I appreciate your work on this project. Without it, it would take much longer to hash passwords with plain javascript.

Unfortunately, I receive this error when I attempt to hash a password:

A hanging Promise was canceled. This happens when the worker runtime is waiting for a Promise from JavaScript to resolve, but has detected that the Promise cannot possibly ever resolve because all code and events related to the Promise's I/O context have already finished.

I'm on the latest version of workerd and miniflare.

Please let me know if you need anything from me.

timothymiller avatar Feb 12 '24 23:02 timothymiller

The talented @robmarsher has a solution. The bug is in the invoke function:

export async function invoke(args: string[]) {
  const stdout = new TransformStream()
  const stderr = new TransformStream()
  const wasi = new WASI({
    args: ['argon2-wasi.wasm', ...args],
    stdout: stdout.writable,
    stderr: stderr.writable,
  })
  const instance = new WebAssembly.Instance(argon2, {
    wasi_snapshot_preview1: wasi.wasiImport,
  })
  const promise = wasi.start(instance)
  const errors = stderr.readable.getReader().read()
  const ret = stdout.readable.getReader().read()
  const [errorsStream, resultStream, _] = await Promise.all([errors, ret, promise])
  const errorsValue = new TextDecoder().decode(errorsStream.value)
  if (errorsValue) {
    throw new Error(errorsValue)
  }
  const retValue = new TextDecoder().decode(resultStream.value)
  return retValue.trim()
}

timothymiller avatar Feb 12 '24 23:02 timothymiller

Yes, cloudflare's workerd seemed to suddenly not like the await wasi.start(instance) line. Locally with miniflare, I also saw an error - "The script will never generate a response". Setting up the stderr and stdout readable streams and then awaiting those together with the wasi.start got it working again.

I love how simple the code is for this project. Thank you so much for publishing it.

rmarscher avatar Feb 13 '24 00:02 rmarscher