WICG / webusb

Connecting hardware to the web.
https://wicg.github.io/webusb/
Other
1.32k stars 132 forks source link

Can't detect device disconnection when `transferIn` is waiting incoming data #219

Open yume-chan opened 2 years ago

yume-chan commented 2 years ago

In a polling design, transferIn is continuously called to receive incoming data. But if the device disconnects, transferIn step 14 only throws a generic NetworkError. Plus, the disconnect event is fired after the error was thrown (at least on Windows and Chrome), it's impossible to detect the reason of such NetworkError.

Device disconnection is usually handled differently from other transfer errors (it's initiated by the user, not a logic error), "check if the device is configured" algorithm throws a NotFoundError if the device is not connected anymore, shows that there are at least some considerations for this situation.

Suggests:

  1. Also throws NotFoundError in transferIn step 14 if the failure reason is device disconnection.
  2. Precisely define the order of disconnect event, device.open property value change, and transferIn throwing, when a device disconencts.
reillyeon commented 2 years ago

The design of the WebUSB API reflects the platform APIs that it is based on. The connect and disconnect events come from what is essentially a completely different platform API than the one that is used to transfer data to and from the device. For example, in Chromium on Linux device connection events come from the udev daemon while device I/O goes through a device node provided by the kernel. Getting the ordering right here requires going through each of the platform APIs which could fail because the device disconnected (like transferIn()) and make sure that the error returned by the platform can be identified as a failure due to disconnection and surface that through the WebUSB API.

I recently did this for the Web Serial API so I can say that while it is not impossible it is definitely a good deal of effort to make sure it works correctly.