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

chore: optimize cancel #340

Draft
wants to merge 1 commit into
base: onekey
Choose a base branch
from
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
21 changes: 21 additions & 0 deletions packages/core/src/api/BaseMethod.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ERRORS, HardwareErrorCode } from '@onekeyfe/hd-shared';
import { supportInputPinOnSoftware, supportModifyHomescreen } from '../utils/deviceFeaturesUtils';
import { createDeviceMessage } from '../events/device';
import { UI_REQUEST } from '../constants/ui-request';
Expand Down Expand Up @@ -81,6 +82,11 @@ export abstract class BaseMethod<Params = undefined> {
*/
skipForceUpdateCheck = false;

/**
* 取消标志,比如还没有搜索到设备,用户取消了操作
*/
private canceled = false;

// @ts-expect-error: strictPropertyInitialization
postMessage: (message: CoreMessage) => void;

Expand Down Expand Up @@ -164,6 +170,21 @@ export abstract class BaseMethod<Params = undefined> {

dispose() {}

hasCanceled() {
return this.canceled;
}

inspectHasCanceled() {
if (this.hasCanceled()) {
throw ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser);
}
}

cancel() {
this.canceled = true;
this.dispose();
}

// Reusable events
postPreviousAddressMessage = (data: { address?: string; path?: string }) => {
this.postMessage(
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/constants/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ export const safeThrowError = (error: any) => {
} else if (error.code === 'ECONNABORTED') {
throw ERRORS.TypedError(HardwareErrorCode.BridgeTimeoutError);
} else {
throw ERRORS.TypedError(error);
throw ERRORS.TypedError(HardwareErrorCode.UnknownError, error.message);
}
};
48 changes: 38 additions & 10 deletions packages/core/src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ let preConnectCache: {
passphraseState: undefined,
};

const removeMethodFromQueue = (methodId: number | undefined) => {
const index = methodId ? callApiQueue.findIndex(m => m.responseID === methodId) : -1;
if (index > -1) {
callApiQueue.splice(index, 1);
console.log('Removed method from queue:', methodId);
}
};

export const callAPI = async (message: CoreMessage) => {
if (!message.id || !message.payload || message.type !== IFRAME.CALL) {
return Promise.reject(ERRORS.TypedError('on call: message.id or message.payload is missing'));
Expand Down Expand Up @@ -131,6 +139,13 @@ export const callAPI = async (message: CoreMessage) => {
return createResponseMessage(method.responseID, false, { error: e });
}

if (method.hasCanceled()) {
removeMethodFromQueue(method.responseID);
return createResponseMessage(method.responseID, false, {
error: ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser),
});
}

Log.debug('Call API - setDevice: ', device.mainId);
method.setDevice?.(device);

Expand All @@ -145,6 +160,8 @@ export const callAPI = async (message: CoreMessage) => {

try {
const inner = async (): Promise<void> => {
method.inspectHasCanceled();

// check firmware version
const versionRange = getMethodVersionRange(
device.features,
Expand Down Expand Up @@ -235,6 +252,8 @@ export const callAPI = async (message: CoreMessage) => {
await TransportManager.reconfigure(device.features);
}

method.inspectHasCanceled();

// Check to see if it is safe to use Passphrase
checkPassphraseEnableState(method, device.features);

Expand Down Expand Up @@ -282,6 +301,8 @@ export const callAPI = async (message: CoreMessage) => {
return;
}

method.inspectHasCanceled();

try {
const response: object = await method.run();
Log.debug('Call API - Inner Method Run: ');
Expand Down Expand Up @@ -322,16 +343,7 @@ export const callAPI = async (message: CoreMessage) => {
}

// remove method from queue
const index = method.responseID
? callApiQueue.findIndex(m => m.responseID === method.responseID)
: -1;
if (index > -1) {
callApiQueue.splice(index, 1);
Log.debug(
'Remove the finished method from the queue: ',
callApiQueue.map(m => m.name)
);
}
removeMethodFromQueue(method.responseID);

closePopup();

Expand Down Expand Up @@ -534,6 +546,11 @@ const ensureConnected = async (method: BaseMethod, pollingId: number) => {
}
}

if (method.hasCanceled()) {
reject(ERRORS.TypedError(HardwareErrorCode.DeviceInterruptedFromUser));
return;
}

if (tryCount > MAX_RETRY_COUNT) {
if (timer) {
clearTimeout(timer);
Expand Down Expand Up @@ -565,6 +582,17 @@ export const cancel = (connectId?: string) => {
// Empty
Log.error('Cancel API Error: ', e);
}
try {
if (connectId) {
for (const method of callApiQueue) {
if (method.payload.connectId === connectId) {
method.cancel();
}
}
}
} catch (e) {
Log.error('Cancel method error: ', e);
}
cleanup();
closePopup();
};
Expand Down
File renamed without changes.
18 changes: 17 additions & 1 deletion scripts/monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ const chokidar = require('chokidar');
const fs = require('fs-extra');
const path = require('path');

const config = require('./moniter-config.json');
// @ts-ignore
const config = require('./monitor-config.json');

const targetDir = process.env[config.targetEnvVar];

Expand Down Expand Up @@ -68,6 +69,21 @@ async function handleFileEvent(filePath, eventType) {
} else {
copyFile(filePath, destPath, eventType === 'add');
}

// 特殊处理 web-sdk/build 文件夹
if (projectName === 'hd-web-sdk' && watchDir === 'build') {
const additionalDestPath = path.join(
targetDir,
'apps/desktop/public/static/js-sdk',
...restPath
);
if (eventType === 'delete') {
await fs.remove(additionalDestPath);
console.log(`Removed ${additionalDestPath}`);
} else {
copyFile(filePath, additionalDestPath, eventType === 'add');
}
}
} catch (err) {
console.error(`Error ${eventType === 'delete' ? 'removing' : 'copying'} ${filePath}:`, err);
}
Expand Down
Loading