Skip to content

Commit

Permalink
chore(suite-desktop): create facade over ILogger to make it compatibl…
Browse files Browse the repository at this point in the history
…e with Log
  • Loading branch information
mroz22 committed May 22, 2024
1 parent ffa9605 commit 0fe541f
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 52 deletions.
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
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
17 changes: 8 additions & 9 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
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 => {
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

0 comments on commit 0fe541f

Please sign in to comment.