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(suite-desktop): bridge log for node-bridge in suite-desktop #12476

Merged
merged 3 commits into from
May 24, 2024
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
40 changes: 7 additions & 33 deletions packages/node-utils/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,14 @@ import * as net from 'net';
import * as url from 'url';

import type { RequiredKey } from '@trezor/type-utils';
import { LogMessage, TypedEmitter } from '@trezor/utils';
import { Log, TypedEmitter } from '@trezor/utils';
import { arrayPartition } from '@trezor/utils';

import { getFreePort } from './getFreePort';

type Request = RequiredKey<http.IncomingMessage, 'url'>;
type EventMap = { [event: string]: any };

type LogFn = (message: string | string[]) => void;
type Logger = {
info: LogFn;
warn: LogFn;
error: LogFn;
getLog: () => LogMessage[];
};

type OriginalLogFn = (topic: string, message: string | string[]) => void;
type OriginalLogger = {
info: OriginalLogFn;
warn: OriginalLogFn;
error: OriginalLogFn;
getLog?: () => LogMessage[];
};

type RequestWithParams = Request & {
params: Record<string, string>;
};
Expand All @@ -42,7 +26,7 @@ export type Handler<R extends Request = RequestWithParams> = (
request: R,
response: Response,
next: Next<R>,
{ logger }: { logger: Logger },
{ logger }: { logger: Log },
) => void;

type Route = {
Expand All @@ -66,28 +50,18 @@ type BaseEvents = {
*/
export class HttpServer<T extends EventMap> extends TypedEmitter<T & BaseEvents> {
public server: http.Server;
public logger: Logger;
public logger: Log;
private routes: Route[] = [];
private readonly emitter: TypedEmitter<BaseEvents> = this;
private port?: number;
private sockets: Record<number, net.Socket> = {};

constructor({ logger, port }: { logger: OriginalLogger; port?: number }) {
constructor({ logger, port }: { logger: Log; port?: number }) {
super();

this.port = port;

// this class accepts subset of suite-desktop-core "ILogger" interface.
// - in order to omit need for passing the first argument "topic" in each call, we wrap the logger and prepend "http: ${this.port}" to each call
// - here it implements also only a subset of ILogger functionality
// - todo: unify loggers across the codebase
this.logger = {
info: (message: string | string[]) => logger.info(`${this.logName}`, message),
warn: (message: string | string[]) => logger.warn(`${this.logName}`, message),
error: (message: string | string[]) => logger.error(`${this.logName}`, message),
getLog: () => (logger.getLog ? logger.getLog() : []),
};
// this.logger = logger;
this.logger = logger;
this.server = http.createServer(this.onRequest);
}

Expand Down Expand Up @@ -337,7 +311,7 @@ const checkOrigin = ({
request: Parameters<Handler>[0];
allowedOrigin: string[];
pathname: string;
logger: Logger;
logger: Log;
}) => {
const { origin } = request.headers;
const origins = allowedOrigin ?? [];
Expand Down Expand Up @@ -373,7 +347,7 @@ const checkReferer = ({
request: Parameters<Handler>[0];
allowedReferer: string[];
pathname: string;
logger: Logger;
logger: Log;
}) => {
const { referer } = request.headers;
const referers = allowedReferer ?? [];
Expand Down
7 changes: 3 additions & 4 deletions packages/node-utils/src/tests/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ describe('HttpServer', () => {
let server: HttpServer<Events>;
beforeEach(() => {
server = new HttpServer<Events>({
// @ts-expect-error
logger: muteLogger,
});
});
Expand Down Expand Up @@ -45,6 +46,7 @@ describe('HttpServer', () => {
});

test('a port can be passed to the constructor', async () => {
// @ts-expect-error
server = new HttpServer<Events>({ logger: muteLogger, port: 65526 });
await server.start();
expect(server.getServerAddress()).toMatchObject({
Expand Down Expand Up @@ -119,10 +121,7 @@ describe('HttpServer', () => {
await new Promise(resolve => setTimeout(resolve, 500));
controller.abort();
await new Promise(resolve => setTimeout(resolve, 500));
expect(muteLogger.info).toHaveBeenLastCalledWith(
expect.any(String),
'Request GET /foo aborted',
);
expect(muteLogger.info).toHaveBeenLastCalledWith('Request GET /foo aborted');
});

test('allowReferer middleware lets request with allowed referer through', async () => {
Expand Down
11 changes: 11 additions & 0 deletions packages/suite-desktop-core/src/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
// Include suite globals (as some dependencies from @suite can rely on them)
/// <reference path="../../suite/global.d.ts" />

type LogMessage = {
date: Date;
level: LogLevel;
topic: string;
text: string;
};

declare interface ILogger {
/**
* Exit the Logger (will correctly end the log file)
Expand Down Expand Up @@ -48,6 +55,10 @@ declare interface ILogger {
* @param options(Partial<Options>) - Log options
*/
config;
/**
* If logs are stored in memory, return array of logs
*/
getLog: () => LogMessage[];
}

// Globals
Expand Down
6 changes: 5 additions & 1 deletion packages/suite-desktop-core/src/libs/http-receiver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { xssFilters } from '@trezor/utils';
import { HttpServer, allowReferers } from '@trezor/node-utils';

import { HTTP_ORIGINS_DEFAULT } from './constants';
import { convertILoggerToLog } from '../utils/IloggerToLog';

type TemplateOptions = {
title?: string;
Expand Down Expand Up @@ -38,7 +39,10 @@ const applyTemplate = (content: string, options?: TemplateOptions) => {
};

export const createHttpReceiver = () => {
const httpReceiver = new HttpServer<Events>({ logger: global.logger, port: 21335 });
const httpReceiver = new HttpServer<Events>({
logger: convertILoggerToLog(global.logger, { serviceName: 'http-receiver' }),
port: 21335,
});

httpReceiver.use([
(request, response, next) => {
Expand Down
28 changes: 19 additions & 9 deletions packages/suite-desktop-core/src/libs/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,14 @@ export type Options = {
outputPath: string; // path for the output
logFormat: string; // Output format of the log
dedupeTimeout: number; // After how many ms are the same messages deduplicated
writeToMemory?: boolean; // Output is stored in memory
memoryCap: number; // Maximum number of messages stored in memory
};

const logLevelSwitchValue = app?.commandLine.getSwitchValue('log-level');
const logLevelByEnv = isDevEnv ? 'debug' : 'error';
const logLevelDefault = isLogLevel(logLevelSwitchValue) ? logLevelSwitchValue : logLevelByEnv;

type LogMessage = {
date: Date;
level: LogLevel;
topic: string;
text: string;
};

type RepeatedLogMessage = LogMessage & {
repetition?: number;
};
Expand All @@ -46,6 +41,7 @@ export class Logger implements ILogger {
private defaultOptions: Options;
private options: Options;
private logLevel = 0;
private memory: LogMessage[] = [];

constructor(level?: LogLevel, options?: Partial<Options>) {
const logLevel = level || logLevelDefault;
Expand All @@ -64,6 +60,8 @@ export class Logger implements ILogger {
(userDataDir ? `${userDataDir}/logs` : process.cwd()),
logFormat: '%dt - %lvl(%top): %rep%msg',
dedupeTimeout: 500,
writeToMemory: false,
memoryCap: 1000,
};

this.options = {
Expand Down Expand Up @@ -116,9 +114,9 @@ export class Logger implements ILogger {
}

private log(level: LogLevel, topic: string, message: string | string[]) {
const { writeToConsole, writeToDisk, logFormat } = this.options;
const { writeToConsole, writeToDisk, writeToMemory, logFormat } = this.options;

if ((!writeToConsole && !writeToDisk) || !logFormat) {
if ((!writeToConsole && !writeToDisk && !writeToMemory) || !logFormat) {
return;
}

Expand Down Expand Up @@ -175,6 +173,14 @@ export class Logger implements ILogger {
rep: (repetition ?? 0) > 1 ? `(${repetition}x) ` : '',
});

// write to memory
if (this.options.writeToMemory) {
this.memory.push({ date, level, topic, text });
if (this.memory.length > this.options.memoryCap) {
this.memory.shift();
}
}

if (this.options.writeToConsole) {
console.log(this.options.colors ? this.color(level, message) : message);
}
Expand Down Expand Up @@ -274,4 +280,8 @@ export class Logger implements ILogger {
this.logBasicInfo();
}
}

public getLog() {
return this.memory;
}
}
19 changes: 9 additions & 10 deletions packages/suite-desktop-core/src/modules/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { TrezordNode } from '@trezor/transport-bridge';
import { app, ipcMain } from '../typed-electron';
import { BridgeProcess } from '../libs/processes/BridgeProcess';
import { b2t } from '../libs/utils';
import { Logger } from '../libs/logger';
import { convertILoggerToLog } from '../utils/IloggerToLog';

import type { Module, Dependencies } from './index';

Expand Down Expand Up @@ -53,20 +55,17 @@ const getBridgeInstance = (store: Dependencies['store']) => {
return new BridgeProcess();
}

const bridgeLogger = new Logger('info', {
writeToDisk: false,
writeToMemory: true,
});

return new TrezordNode({
port: 21325,
api: bridgeDev || bridgeTest ? 'udp' : 'usb',
assetPrefix: '../build/node-bridge',
// passing down ILogger where Log is expected.
// @ts-expect-error
logger: {
...global.logger,
log: (...args) => logger.info('trezord-node', args.join(' ')),
info: (...args) => logger.info('trezord-node', args.join(' ')),
warn: (...args) => logger.warn('trezord-node', args.join(' ')),
debug: (...args) => logger.debug('trezord-node', args.join(' ')),
error: (...args) => logger.error('trezord-node', args.join(' ')),
},
logger: convertILoggerToLog(bridgeLogger, { serviceName: 'trezord-node' }),
});
};

Expand Down Expand Up @@ -138,7 +137,7 @@ const load = async ({ store, mainWindow }: Dependencies) => {
try {
logger.info(
SERVICE_NAME,
`Starting (Legacy dev: ${b2t(bridgeLegacyDev)}), Legacy test: ${b2t(bridgeLegacyTest)}), Legacy: ${b2t(bridgeLegacy)}, Test: ${b2t(bridgeTest)}`,
`Starting (Legacy dev: ${b2t(bridgeLegacyDev)}, Legacy test: ${b2t(bridgeLegacyTest)}, Legacy: ${b2t(bridgeLegacy)}, Test: ${b2t(bridgeTest)})`,
);
await start(bridge);
handleBridgeStatus(bridge, mainWindow);
Expand Down
32 changes: 32 additions & 0 deletions packages/suite-desktop-core/src/utils/IloggerToLog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Log, LogMessage as UtilsLogMessage } from '@trezor/utils';

/** take an instance of ILogger and return mimicked instance of Log while keeping more or less the same behavior */
export const convertILoggerToLog = (
iLogger: ILogger,
{ serviceName }: { serviceName: string },
): Log => {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: inline

return {
log: (msg: string) => iLogger.info(serviceName, msg),
info: (msg: string) => iLogger.info(serviceName, msg),
debug: (msg: string) => iLogger.debug(serviceName, msg),
warn: (msg: string) => iLogger.warn(serviceName, msg),
error: (msg: string) => iLogger.error(serviceName, msg),
prefix: '',
messages: [],
enabled: true,
css: '',
MAX_ENTRIES: 1000,
setColors: (_colors: any) => {},
setWriter: (_logWriter: any) => {},
addMessage: (_msg: UtilsLogMessage) => {},
logWriter: undefined,
getLog: (): UtilsLogMessage[] => {
return iLogger.getLog().map(log => ({
message: [log.text],
prefix: '',
level: log.level,
timestamp: log.date.getTime(),
}));
},
};
};
8 changes: 7 additions & 1 deletion packages/transport-bridge/src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { Log } from '@trezor/utils';

import { TrezordNode } from './http';

const trezordNode = new TrezordNode({ port: 21325, api: 'usb' });
const trezordNode = new TrezordNode({
port: 21325,
api: 'usb',
logger: new Log('@trezor/transport-bridge', true),
});

trezordNode.start();
7 changes: 3 additions & 4 deletions packages/transport-bridge/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,10 @@ export class TrezordNode {
port: number;
api: 'usb' | 'udp';
assetPrefix?: string;
logger?: Log;
logger: Log;
}) {
this.port = port || defaults.port;
this.logger = logger || new Log('@trezor/transport-bridge', true);

this.logger = logger;
this.descriptors = [];

this.listenSubscriptions = [];
Expand Down Expand Up @@ -271,7 +270,7 @@ export class TrezordNode {
intro: `To download full logs go to http://127.0.0.1:${this.port}/logs`,
version: this.version,
devices: enumerateResult.success ? enumerateResult.payload.descriptors : [],
logs: app.logger.getLog().slice(-20),
logs: this.logger.getLog().slice(-20),
};

res.end(str(props));
Expand Down
Loading