Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

πŸ‘” (webhid) [NO-ISSUE]: Update reconnection error sending #631

Merged
merged 2 commits into from
Jan 27, 2025
Merged
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
5 changes: 5 additions & 0 deletions .changeset/fuzzy-spies-divide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ledgerhq/device-transport-kit-web-hid": patch
---

Update reconnection event to trigger error only after a specific time
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ describe("WebHidDeviceConnection", () => {
});

describe("anticipating loss of connection after sending an APDU", () => {
test("sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success", async () => {
it("sendApdu(whatever, true) should wait for reconnection before resolving if the response is a success", async () => {
// given
device.sendReport = jest.fn(() =>
Promise.resolve(
Expand All @@ -130,12 +130,14 @@ describe("WebHidDeviceConnection", () => {
} as HIDInputReportEvent),
),
);

const connection = new WebHidDeviceConnection(
{ device, apduSender, apduReceiver, onConnectionTerminated, deviceId },
logger,
);

let hasResolved = false;

const responsePromise = connection
.sendApdu(Uint8Array.from([]), true)
.then((response) => {
Expand Down Expand Up @@ -164,7 +166,7 @@ describe("WebHidDeviceConnection", () => {
);
});

test("sendApdu(whatever, true) should not wait for reconnection if the response is not a success", async () => {
it("sendApdu(whatever, true) should not wait for reconnection if the response is not a success", async () => {
// given
device.sendReport = jest.fn(() =>
Promise.resolve(
Expand All @@ -191,7 +193,7 @@ describe("WebHidDeviceConnection", () => {
);
});

test("sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection", async () => {
it("sendApdu(whatever, true) should return an error if the device gets disconnected while waiting for reconnection", async () => {
// given
device.sendReport = jest.fn(() =>
Promise.resolve(
Expand Down Expand Up @@ -220,7 +222,7 @@ describe("WebHidDeviceConnection", () => {
});

describe("connection lost before sending an APDU", () => {
test("sendApdu(whatever, false) should return an error if the device connection has been lost and times out", async () => {
it("sendApdu(whatever, false) should return an error if the device connection has been lost and times out", async () => {
// given
device.sendReport = jest.fn(() =>
Promise.resolve(
Expand All @@ -246,7 +248,7 @@ describe("WebHidDeviceConnection", () => {
expect(response).toEqual(Left(new ReconnectionFailedError()));
});

test("sendApdu(whatever, false) should wait for reconnection to resolve", async () => {
it("sendApdu(whatever, false) should wait for reconnection to resolve", async () => {
// given
device.sendReport = jest.fn(() =>
Promise.resolve(
Expand Down Expand Up @@ -283,7 +285,13 @@ describe("WebHidDeviceConnection", () => {

const response = await responsePromise;

expect(response).toEqual(Left(new WebHidSendReportError()));
expect(response).toEqual(
Left(
new WebHidSendReportError(
new Error("Device disconnected while waiting for device response"),
),
),
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
ReconnectionFailedError,
} from "@ledgerhq/device-management-kit";
import { type Either, Left, Maybe, Nothing, Right } from "purify-ts";
import { Subject } from "rxjs";
import { firstValueFrom, from, retry, Subject } from "rxjs";

import { RECONNECT_DEVICE_TIMEOUT } from "@api/data/WebHidConfig";
import { WebHidSendReportError } from "@api/model/Errors";
Expand All @@ -23,6 +23,8 @@ type WebHidDeviceConnectionConstructorArgs = {
onConnectionTerminated: () => void;
};

type Timer = ReturnType<typeof setTimeout>;

/**
* Class to manage the connection with a USB HID device.
* It sends APDU commands to the device and receives the responses.
Expand All @@ -44,7 +46,7 @@ export class WebHidDeviceConnection implements DeviceConnection {
/** Flag to indicate if the connection is waiting for a reconnection */
private waitingForReconnection = false;
/** Timeout to wait for the device to reconnect */
private lostConnectionTimeout: NodeJS.Timeout | null = null;
private lostConnectionTimeout: Timer | null = null;
/** Flag to indicate if the connection is terminated */
private terminated = false;

Expand Down Expand Up @@ -114,11 +116,9 @@ export class WebHidDeviceConnection implements DeviceConnection {
if (this.waitingForReconnection || !this.device.opened) {
const waitingForDeviceResponse =
this.device.opened && this._pendingApdu.isJust();

const reconnectionRes = await this.waitForReconnection(
waitingForDeviceResponse,
);

if (reconnectionRes.isLeft()) {
return reconnectionRes;
}
Expand All @@ -129,8 +129,16 @@ export class WebHidDeviceConnection implements DeviceConnection {
this._logger.debug("Sending Frame", {
data: { frame: frame.getRawData() },
});

try {
await this._device.sendReport(0, frame.getRawData());
await firstValueFrom(
from(this._device.sendReport(0, frame.getRawData())).pipe(
retry({
count: 3,
delay: 500,
}),
),
);
} catch (error) {
this._logger.error("Error sending frame", { data: { error } });
return Promise.resolve(Left(new WebHidSendReportError(error)));
Expand Down Expand Up @@ -174,14 +182,21 @@ export class WebHidDeviceConnection implements DeviceConnection {
const sub = this.reconnectionSubject.subscribe({
next: (res) => {
if (waitingForDeviceResponse) {
this._sendApduSubject.error(new WebHidSendReportError());
this._sendApduSubject.error(
new WebHidSendReportError(
new Error(
"Device disconnected while waiting for device response",
),
),
);
}

if (res === "success") {
resolve(Right(undefined));
} else {
resolve(Left(res));
}

sub.unsubscribe();
},
});
Expand All @@ -207,16 +222,11 @@ export class WebHidDeviceConnection implements DeviceConnection {
this._device.oninputreport = (event) => this.receiveHidInputReport(event);

if (this.lostConnectionTimeout) {
this._logger.info("β±οΈπŸ”Œ Device reconnected");
clearTimeout(this.lostConnectionTimeout);
}

await device.open();

if (this._pendingApdu.isJust()) {
this._sendApduSubject.error(new WebHidSendReportError());
}

this._logger.info("β±οΈπŸ”Œ Device reconnected");
this.waitingForReconnection = false;
this.reconnectionSubject.next("success");
}
Expand Down