Skip to content

Commit

Permalink
chore: add logs for network/update/electron (#5012)
Browse files Browse the repository at this point in the history
  • Loading branch information
huhuanming authored Jul 1, 2024
1 parent 1a181c3 commit 2e224ae
Show file tree
Hide file tree
Showing 17 changed files with 106 additions and 34 deletions.
12 changes: 6 additions & 6 deletions apps/desktop/src-electron/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ function createMainWindow() {
}

browserWindow.webContents.on('did-finish-load', () => {
console.log('browserWindow >>>> did-finish-load');
logger.info('browserWindow >>>> did-finish-load');
browserWindow.webContents.send(ipcMessageKeys.SET_ONEKEY_DESKTOP_GLOBALS, {
resourcesPath: (global as any).resourcesPath,
staticPath: `file://${staticPath}`,
Expand All @@ -283,7 +283,7 @@ function createMainWindow() {
browserWindow.on('closed', () => {
mainWindow = null;
isAppReady = false;
console.log('set isAppReady on browserWindow closed', isAppReady);
logger.info('set isAppReady on browserWindow closed', isAppReady);
});

browserWindow.webContents.on('devtools-opened', () => {
Expand All @@ -296,7 +296,7 @@ function createMainWindow() {
// dom-ready is fired after ipcMain:app/ready
browserWindow.webContents.on('dom-ready', () => {
isAppReady = true;
console.log('set isAppReady on browserWindow dom-ready', isAppReady);
logger.info('set isAppReady on browserWindow dom-ready', isAppReady);
});

browserWindow.webContents.setWindowOpenHandler(({ url }) => {
Expand All @@ -306,7 +306,7 @@ function createMainWindow() {

ipcMain.on(ipcMessageKeys.APP_READY, () => {
isAppReady = true;
console.log('set isAppReady on ipcMain app/ready', isAppReady);
logger.info('set isAppReady on ipcMain app/ready', isAppReady);
emitter.emit('ready');
});
ipcMain.on(ipcMessageKeys.APP_READY, () => {
Expand Down Expand Up @@ -730,7 +730,7 @@ app.on('will-finish-launching', () => {
app.on('open-url', handleDeepLinkUrl);
});

console.log(' ========= Desktop main app start!!!!!!!!!!!!! ========== ');
logger.info(' ========= Desktop main app start!!!!!!!!!!!!! ========== ');
const userDataPath = app.getPath('userData');
console.log(JSON.stringify({ userDataPath }, null, 2));
console.log(' ===================');
logger.info(' =================== ');
4 changes: 2 additions & 2 deletions apps/desktop/src-electron/libs/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export const getSecureItem = (key: string) => {
const result = safeStorage.decryptString(Buffer.from(value, 'hex'));
return result;
} catch (e) {
logger.error(`failed to decrypt ${key}`, e);
logger.error(`failed to decrypt ${key}`);
return undefined;
}
}
Expand All @@ -85,7 +85,7 @@ export const setSecureItem = (key: string, value: string): void => {
items[key] = safeStorage.encryptString(value).toString('hex');
store.set(configKeys.EncryptedData, items);
} catch (e) {
logger.error(`failed to encrypt ${key} ${value}`, e);
logger.error(`failed to encrypt ${key}`);
}
};

Expand Down
2 changes: 1 addition & 1 deletion apps/desktop/src-electron/process/AutoUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ const init = ({ mainWindow, store }: IDependencies) => {
})
.then((selection) => {
if (selection.response === 0) {
// User clicked 'Install and Restart'
logger.info('auto-update', "User clicked 'Install and Restart'");
app.removeAllListeners('window-all-closed');
mainWindow.removeAllListeners('close');
for (const window of BrowserWindow.getAllWindows()) {
Expand Down
3 changes: 1 addition & 2 deletions apps/desktop/src-electron/process/TouchRes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ const init = ({ mainWindow }: { mainWindow: BrowserWindow }) => {

wmic.stdout.on('data', (buffer: Buffer) => {
let data = buffer.toString('utf8');
logger.info('wmic stdout =====> ', data);
// logger.info('wmic stdout =====> ', data);
data = data.replace(/DeviceID/g, '');
data = data.replace(/VolumeName/g, '');
const array = [...data].filter(
Expand Down Expand Up @@ -227,7 +227,6 @@ const init = ({ mainWindow }: { mainWindow: BrowserWindow }) => {
const SourceFolder = path.join(resourcePath, 'res/res');

const downloadFile = (fileUrl: string) => {
logger.info('process: ', process.env);
logger.info('resource path: ', resourcePath);
if (!fs.existsSync(resourcePath)) {
logger.info('create resource path start');
Expand Down
5 changes: 1 addition & 4 deletions packages/kit-bg/src/services/ServiceAppUpdate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
} from '@onekeyhq/shared/src/background/backgroundDecorators';
import { ETranslations } from '@onekeyhq/shared/src/locale';
import platformEnv from '@onekeyhq/shared/src/platformEnv';
import { getRequestHeaders } from '@onekeyhq/shared/src/request/Interceptor';
import timerUtils from '@onekeyhq/shared/src/utils/timerUtils';
import { EServiceEndpointEnum } from '@onekeyhq/shared/types/endpoint';

Expand All @@ -35,9 +34,7 @@ class ServiceAppUpdate extends ServiceBase {
const response = await client.get<{
code: number;
data: IResponseAppUpdateInfo;
}>('/utility/v1/app-update', {
headers: await getRequestHeaders(),
});
}>('/utility/v1/app-update');
const { code, data } = response.data;
if (code === 0) {
this.updateAt = Date.now();
Expand Down
2 changes: 0 additions & 2 deletions packages/kit/src/components/RenameDialog/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ function V4AccountNameSelector({
indexedAccountId: indexedAccount.id,
},
);
console.log(accounts);
return accounts
.map((account) => {
const networkId = v4CoinTypeToNetworkId[account.coinType];
Expand Down Expand Up @@ -85,7 +84,6 @@ function V4AccountNameSelector({
title={intl.formatMessage({
id: ETranslations.v4_select_account_name_label,
})}
onOpenChange={console.log}
/>
</Stack>
);
Expand Down
3 changes: 3 additions & 0 deletions packages/shared/src/logger/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { AppScope } from './scopes/app';
import { DemoScope } from './scopes/demo';
import { SettingScope } from './scopes/setting';
import { SignatureRecordScope } from './scopes/signatureRecord';
import { UpdateScope } from './scopes/update';

class Logger {
app = new AppScope();
Expand All @@ -14,6 +15,8 @@ class Logger {
addressInput = new AddressInputScope();

signatureRecord = new SignatureRecordScope();

update = new UpdateScope();
}

export const defaultLogger = new Logger();
3 changes: 3 additions & 0 deletions packages/shared/src/logger/scopes/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { EScopeName } from '../../types';
import { BackgroundScene } from './scenes/background';
import { BootstrapScene } from './scenes/bootstrap';
import { InstallScene } from './scenes/install';
import { NetworkScene } from './scenes/network';

export class AppScope extends BaseScope {
protected override scopeName = EScopeName.app;
Expand All @@ -13,4 +14,6 @@ export class AppScope extends BaseScope {
background = this.createScene('background', BackgroundScene);

install = this.createScene('install', InstallScene);

network = this.createScene('network', NetworkScene);
}
14 changes: 14 additions & 0 deletions packages/shared/src/logger/scopes/app/scenes/network.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { BaseScene } from '../../../base/baseScene';
import { LogToLocal } from '../../../decorators';

export class NetworkScene extends BaseScene {
@LogToLocal({ level: 'debug' })
public call(
requestType: string,
method = 'GET',
path = '/',
requestId?: string,
) {
return `${requestType}:${method}:${path}, requestId: ${requestId || ''}`;
}
}
10 changes: 10 additions & 0 deletions packages/shared/src/logger/scopes/update/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { BaseScope } from '../../base/baseScope';
import { EScopeName } from '../../types';

import { AppScene } from './scenes/app';

export class UpdateScope extends BaseScope {
protected override scopeName = EScopeName.app;

app = this.createScene('app', AppScene);
}
9 changes: 9 additions & 0 deletions packages/shared/src/logger/scopes/update/scenes/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { BaseScene } from '../../../base/baseScene';
import { LogToLocal } from '../../../decorators';

export class AppScene extends BaseScene {
@LogToLocal({ level: 'info' })
public log(eventName: string, version: number | string = '') {
return `${eventName} ${version}`;
}
}
26 changes: 21 additions & 5 deletions packages/shared/src/modules3rdParty/auto-update/index.android.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useEffect, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';

import { NativeEventEmitter, NativeModules } from 'react-native';
import { useThrottledCallback } from 'use-debounce';

import { defaultLogger } from '../../logger/logger';
import RNFS from '../react-native-fs';

import type {
Expand Down Expand Up @@ -51,6 +52,7 @@ export const downloadPackage: IDownloadPackage = async ({
};

export const installPackage: IInstallPackage = ({ latestVersion, sha256 }) => {
defaultLogger.update.app.log('install', latestVersion);
if (!latestVersion) {
return Promise.resolve();
}
Expand All @@ -70,16 +72,30 @@ export const useDownloadProgress: IUseDownloadProgress = (
const updatePercent = useThrottledCallback(
({ progress }: { progress: number }) => {
console.log('update/downloading', progress);
defaultLogger.update.app.log('downloading', progress);
setPercent(progress);
},
10,
);

const handleSuccess = useCallback(() => {
defaultLogger.update.app.log('downloaded');
onSuccess();
}, [onSuccess]);

const handleFailed = useCallback(
(params: { message: string }) => {
defaultLogger.update.app.log('error', params.message);
onFailed(params);
},
[onFailed],
);

useEffect(() => {
const onStartEventListener = eventEmitter.addListener(
'update/start',
() => {
console.log('update/start');
defaultLogger.update.app.log('start');
setPercent(0);
},
);
Expand All @@ -89,18 +105,18 @@ export const useDownloadProgress: IUseDownloadProgress = (
);
const onDownloadedEventListener = eventEmitter.addListener(
'update/downloaded',
onSuccess,
handleSuccess,
);
const onErrorEventListener = eventEmitter.addListener(
'update/error',
onFailed,
handleFailed,
);
return () => {
onStartEventListener.remove();
onDownloadingEventListener.remove();
onDownloadedEventListener.remove();
onErrorEventListener.remove();
};
}, [onFailed, onSuccess, updatePercent]);
}, [handleFailed, handleSuccess, onFailed, onSuccess, updatePercent]);
return percent;
};
15 changes: 11 additions & 4 deletions packages/shared/src/modules3rdParty/auto-update/index.desktop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { useEffect, useState } from 'react';

import { useThrottledCallback } from 'use-debounce';

import { defaultLogger } from '../../logger/logger';

import type {
IDownloadPackage,
IInstallPackage,
Expand All @@ -10,26 +12,27 @@ import type {

const updateCheckingTasks: (() => void)[] = [];
window.desktopApi?.on?.('update/checking', () => {
console.log('update/checking');
defaultLogger.update.app.log('checking');
while (updateCheckingTasks.length) {
updateCheckingTasks.pop()?.();
}
});

const updateAvailableTasks: (() => void)[] = [];
window.desktopApi?.on?.('update/available', ({ version }) => {
console.log('update/available, version: ', version);
defaultLogger.update.app.log('available', version);
while (updateAvailableTasks.length) {
updateAvailableTasks.pop()?.();
}
});

window.desktopApi?.on?.('update/not-available', (params) => {
console.log('update/not-available', params);
defaultLogger.update.app.log('not-available');
});

window.desktopApi?.on?.('update/download', ({ version }) => {
console.log('update/download, version: ', version);
defaultLogger.update.app.log('download', version);
});

let updateDownloadingTasks: ((params: {
Expand All @@ -49,12 +52,14 @@ window.desktopApi?.on?.(
transferred: number;
}) => {
console.log('update/downloading', params);
defaultLogger.update.app.log('downloading', params.percent);
updateDownloadingTasks.forEach((t) => t(params));
},
);

const updateDownloadedTasks: (() => void)[] = [];
window.desktopApi.on('update/downloaded', () => {
defaultLogger.update.app.log('download');
while (updateDownloadedTasks.length) {
updateDownloadedTasks.pop()?.();
}
Expand All @@ -75,6 +80,7 @@ window.desktopApi?.on?.(
const message =
err.message ||
'Network exception, please check your internet connection.';
defaultLogger.update.app.log('error', message);
while (updateErrorTasks.length) {
updateErrorTasks.pop()?.({ message });
}
Expand All @@ -92,6 +98,7 @@ export const downloadPackage: IDownloadPackage = () =>
});

export const installPackage: IInstallPackage = async () => {
defaultLogger.update.app.log('install');
window.desktopApi.installUpdate();
};

Expand All @@ -111,7 +118,7 @@ export const useDownloadProgress: IUseDownloadProgress = (
percent: number;
bytesPerSecond: number;
}) => {
console.log('update/downloading', progress);
defaultLogger.update.app.log('downloading', progress);
setPercent((prev) => Math.max(Number(Number(progress).toFixed()), prev));
},
10,
Expand Down
4 changes: 3 additions & 1 deletion packages/shared/src/request/Interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export async function checkRequestIsOneKeyDomain({
return isOneKeyDomain;
}

export const HEADER_REQUEST_ID_KEY = normalizeHeaderKey('X-Onekey-Request-ID');

export async function getRequestHeaders() {
const settings = await settingsPersistAtom.get();

Expand All @@ -69,7 +71,7 @@ export async function getRequestHeaders() {

const requestId = generateUUID();
return {
[normalizeHeaderKey('X-Onekey-Request-ID')]: requestId,
[HEADER_REQUEST_ID_KEY]: requestId,
[normalizeHeaderKey('X-Amzn-Trace-Id')]: requestId,
[normalizeHeaderKey('X-Onekey-Request-Currency')]: settings.currencyInfo.id,
[normalizeHeaderKey('X-Onekey-Request-Locale')]: locale.toLowerCase(),
Expand Down
Loading

0 comments on commit 2e224ae

Please sign in to comment.