Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,20 @@ impl Drop for Emitter {
}
}

// A Linux machine without a USB bus (often a container) has no
// /sys/bus/usb/devices. That means there are no devices, not that listing failed.
fn is_missing_usb_bus(e: &nusb::Error) -> bool {
cfg!(target_os = "linux")
&& e.os_error().is_some_and(|code| {
std::io::Error::from_raw_os_error(code as i32).kind() == std::io::ErrorKind::NotFound
})
}
Comment on lines 165 to +173

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd probably just do list_devices().wait().map_or(Vec::new(), |devices| devices.collect()) instead of testing for the specific error, since if you don't want it to fail in that case, you probably don't want it to fail in other cases either.


async fn list_devices(error_prefix: &'static str) -> Result<Vec<nusb::DeviceInfo>> {
run_blocking(move || {
nusb::list_devices()
.wait()
.map(|devices| devices.collect::<Vec<_>>())
.map_err(|e| format!("{error_prefix} error: {e}"))
run_blocking(move || match nusb::list_devices().wait() {
Ok(devices) => Ok(devices.collect::<Vec<_>>()),
Err(e) if is_missing_usb_bus(&e) => Ok(Vec::new()),
Err(e) => Err(format!("{error_prefix} error: {e}")),
})
.await
}
Expand Down
8 changes: 6 additions & 2 deletions tsc/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,9 @@ class WebUSB extends EventTarget implements USB {
private queueNativeEmitterOperation(operation: () => Promise<void>): void {
const pending = this.nativeEmitterQueue.then(operation);
this.nativeEmitterQueue = pending.catch(() => {});
pending.catch(error => setTimeout(() => { throw error; }, 0));
// A hotplug watcher that can't start (e.g. no netlink in a container) must
// not crash the host process, so report it rather than rethrowing.
pending.catch(error => console.warn('usb: hotplug watcher error:', error));
}

private deviceConnectCallback = async (device: UsbDevice) => {
Expand Down Expand Up @@ -194,7 +196,9 @@ class WebUSB extends EventTarget implements USB {
await this.nativeEmitter.addAttach(this.deviceConnectCallback);
await this.nativeEmitter.addDetach(this.deviceDisconnectCallback);
});
nativeGetDevices().then(devices => devices.forEach(device => this.knownDevices.set(device.handle, device)));
nativeGetDevices()
.then(devices => devices.forEach(device => this.knownDevices.set(device.handle, device)))
.catch(error => console.warn('usb: failed to list devices for hotplug:', error));
}
}

Expand Down
Loading