Merge pull request #926 from status-im/console-log

refactor: remove console.log usage
This commit is contained in:
fryorcraken.eth 2022-09-08 15:00:43 +10:00 committed by GitHub
commit bcb9082ea1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 86 additions and 81 deletions

View File

@ -32,13 +32,15 @@
"sort-imports": [
"error",
{ "ignoreDeclarationSort": true, "ignoreCase": true }
]
],
"no-console": "warn"
},
"overrides": [
{
"files": ["*.spec.ts", "**/test_utils/*.ts"],
"rules": {
"@typescript-eslint/no-non-null-assertion": "off"
"@typescript-eslint/no-non-null-assertion": "off",
"no-console": "off"
}
}
]

View File

@ -26,7 +26,7 @@ import { ENRKey, ENRValue, NodeId, SequenceNumber } from "./types";
import * as v4 from "./v4";
import { decodeWaku2, encodeWaku2, Waku2 } from "./waku2_codec";
const dbg = debug("waku:enr");
const log = debug("waku:enr");
export class ENR extends Map<ENRKey, ENRValue> {
public static readonly RECORD_PREFIX = "enr:";
@ -57,7 +57,7 @@ export class ENR extends Map<ENRKey, ENRValue> {
enr.peerId = await createPeerIdFromKeypair(keypair);
}
} catch (e) {
dbg("Could not calculate peer id for ENR", e);
log("Could not calculate peer id for ENR", e);
}
return enr;
@ -112,7 +112,7 @@ export class ENR extends Map<ENRKey, ENRValue> {
try {
obj[bytesToUtf8(kvs[i])] = kvs[i + 1];
} catch (e) {
dbg("Failed to decode ENR key to UTF-8, skipping it", kvs[i], e);
log("Failed to decode ENR key to UTF-8, skipping it", kvs[i], e);
}
}
// If seq is an empty array, translate as value 0

View File

@ -9,7 +9,7 @@ import {
yieldNodesUntilCapabilitiesFulfilled,
} from "./fetch_nodes";
const dbg = debug("waku:discovery:dns");
const log = debug("waku:discovery:dns");
export type SearchContext = {
domain: string;
@ -64,7 +64,7 @@ export class DnsNodeDiscovery {
this._errorTolerance,
() => this._search(domain, context)
);
dbg(
log(
"retrieved peers: ",
peers.map((peer) => {
return {
@ -136,13 +136,13 @@ export class DnsNodeDiscovery {
return null;
}
} catch (error) {
dbg(
log(
`Failed to search DNS tree ${entryType} at subdomain ${subdomain}: ${error}`
);
return null;
}
} catch (error) {
dbg(`Failed to retrieve TXT record at subdomain ${subdomain}: ${error}`);
log(`Failed to retrieve TXT record at subdomain ${subdomain}: ${error}`);
return null;
}
}

View File

@ -4,7 +4,7 @@ import { ENR, Waku2 } from "../enr";
import { NodeCapabilityCount } from "./dns";
const dbg = debug("waku:discovery:fetch_nodes");
const log = debug("waku:discovery:fetch_nodes");
/**
* Fetch nodes using passed [[getNode]] until all wanted capabilities are
@ -49,7 +49,7 @@ export async function fetchNodesUntilCapabilitiesFulfilled(
peers.push(peer);
}
}
dbg(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);
log(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);
}
totalSearches++;
@ -101,7 +101,7 @@ export async function* yieldNodesUntilCapabilitiesFulfilled(
yield peer;
}
}
dbg(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);
log(`got new peer candidate from DNS address=${peer.nodeId}@${peer.ip}`);
}
totalSearches++;
}

View File

@ -8,7 +8,7 @@ import { waitForRemotePeer } from "../wait_for_remote_peer";
import { Protocols, Waku } from "../waku";
import { WakuMessage } from "../waku_message";
const dbg = debug("waku:test:lightpush");
const log = debug("waku:test:lightpush");
const TestContentTopic = "/test/1/waku-light-push/utf8";
@ -79,17 +79,17 @@ describe("Waku Light Push [node only]", () => {
TestContentTopic
);
dbg("Send message via lightpush");
log("Send message via lightpush");
const pushResponse = await waku.lightPush.push(message, {
peerId: nimPeerId,
pubSubTopic: customPubSubTopic,
});
dbg("Ack received", pushResponse);
log("Ack received", pushResponse);
expect(pushResponse?.isSuccess).to.be.true;
let msgs: WakuMessage[] = [];
dbg("Waiting for message to show in nwaku");
log("Waiting for message to show in nwaku");
while (msgs.length === 0) {
await delay(200);
msgs = await nwaku.messages(customPubSubTopic);

View File

@ -1,5 +1,6 @@
import type { PeerId } from "@libp2p/interface-peer-id";
import type { Peer } from "@libp2p/interface-peer-store";
import debug from "debug";
import all from "it-all";
import * as lp from "it-length-prefixed";
import { pipe } from "it-pipe";
@ -14,6 +15,8 @@ import { WakuMessage } from "../waku_message";
import { PushRPC } from "./push_rpc";
const log = debug("waku:light-push");
export const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
export { PushResponse };
@ -86,16 +89,16 @@ export class WakuLightPush {
const response = PushRPC.decode(bytes).response;
if (!response) {
console.log("No response in PushRPC");
log("No response in PushRPC");
return null;
}
return response;
} catch (err) {
console.log("Failed to decode push reply", err);
log("Failed to decode push reply", err);
}
} catch (err) {
console.log("Failed to send waku light push request", err);
log("Failed to send waku light push request", err);
}
return null;
}

View File

@ -20,7 +20,7 @@ import { Protocols, Waku } from "../waku";
import { DecryptionMethod, WakuMessage } from "./index";
const dbg = debug("waku:test:message");
const log = debug("waku:test:message");
const TestContentTopic = "/test/1/waku-message/utf8";
@ -37,14 +37,14 @@ describe("Waku Message [node only]", function () {
await waku.start();
nwaku = new Nwaku(makeLogFileName(this));
dbg("Starting nwaku node");
log("Starting nwaku node");
await nwaku.start({ rpcPrivate: true });
dbg("Dialing to nwaku node");
log("Dialing to nwaku node");
await waku.dial(await nwaku.getMultiaddrWithId());
dbg("Wait for remote peer");
log("Wait for remote peer");
await waitForRemotePeer(waku, [Protocols.Relay]);
dbg("Remote peer ready");
log("Remote peer ready");
// As this test uses the nwaku RPC API, we somehow often face
// Race conditions where the nwaku node does not have the js-waku
// Node in its relay mesh just yet.
@ -78,7 +78,7 @@ describe("Waku Message [node only]", function () {
);
const publicKey = getPublicKey(privateKey);
dbg("Post message");
log("Post message");
const res = await nwaku.postAsymmetricMessage(message, publicKey);
expect(res).to.be.true;
@ -92,13 +92,13 @@ describe("Waku Message [node only]", function () {
it("Encrypts message for nwaku [asymmetric, no signature]", async function () {
this.timeout(5000);
dbg("Ask nwaku to generate asymmetric key pair");
log("Ask nwaku to generate asymmetric key pair");
const keyPair = await nwaku.getAsymmetricKeyPair();
const privateKey = hexToBytes(keyPair.privateKey);
const publicKey = hexToBytes(keyPair.publicKey);
const messageText = "This is a message I am going to encrypt";
dbg("Encrypt message");
log("Encrypt message");
const message = await WakuMessage.fromUtf8String(
messageText,
TestContentTopic,
@ -107,18 +107,18 @@ describe("Waku Message [node only]", function () {
}
);
dbg("Send message over relay");
log("Send message over relay");
await waku.relay.send(message);
let msgs: WakuRelayMessage[] = [];
while (msgs.length === 0) {
dbg("Wait for message to be seen by nwaku");
log("Wait for message to be seen by nwaku");
await delay(200);
msgs = await nwaku.getAsymmetricMessages(privateKey);
}
dbg("Check message content");
log("Check message content");
expect(msgs[0].contentTopic).to.equal(message.contentTopic);
expect(bytesToUtf8(hexToBytes(msgs[0].payload))).to.equal(messageText);
});
@ -132,7 +132,7 @@ describe("Waku Message [node only]", function () {
payload: bytesToHex(utf8ToBytes(messageText)),
};
dbg("Generate symmetric key");
log("Generate symmetric key");
const symKey = generateSymmetricKey();
waku.relay.addDecryptionKey(symKey, {
@ -145,11 +145,11 @@ describe("Waku Message [node only]", function () {
}
);
dbg("Post message using nwaku");
log("Post message using nwaku");
await nwaku.postSymmetricMessage(message, symKey);
dbg("Wait for message to be received by js-waku");
log("Wait for message to be received by js-waku");
const receivedMsg = await receivedMsgPromise;
dbg("Message received by js-waku");
log("Message received by js-waku");
expect(receivedMsg.contentTopic).to.eq(message.contentTopic);
expect(receivedMsg.version).to.eq(1);
@ -159,9 +159,9 @@ describe("Waku Message [node only]", function () {
it("Encrypts message for nwaku [symmetric, no signature]", async function () {
this.timeout(5000);
dbg("Getting symmetric key from nwaku");
log("Getting symmetric key from nwaku");
const symKey = await nwaku.getSymmetricKey();
dbg("Encrypting message with js-waku");
log("Encrypting message with js-waku");
const messageText =
"This is a message I am going to encrypt with a symmetric key";
const message = await WakuMessage.fromUtf8String(
@ -171,14 +171,14 @@ describe("Waku Message [node only]", function () {
symKey: symKey,
}
);
dbg("Sending message over relay");
log("Sending message over relay");
await waku.relay.send(message);
let msgs: WakuRelayMessage[] = [];
while (msgs.length === 0) {
await delay(200);
dbg("Getting messages from nwaku");
log("Getting messages from nwaku");
msgs = await nwaku.getSymmetricMessages(symKey);
}

View File

@ -6,7 +6,7 @@ import { bytesToUtf8, utf8ToBytes } from "../utils";
import * as version_1 from "./version_1";
const DefaultVersion = 0;
const dbg = debug("waku:message");
const log = debug("waku:message");
const OneMillion = BigInt(1_000_000);
export enum DecryptionMethod {
@ -156,7 +156,7 @@ export class WakuMessage {
let signature;
if (protoBuf.version === 1 && payload) {
if (decryptionParams === undefined) {
dbg("Payload is encrypted but no private keys have been provided.");
log("Payload is encrypted but no private keys have been provided.");
return;
}
@ -173,7 +173,7 @@ export class WakuMessage {
try {
return await version_1.decryptAsymmetric(payload, key);
} catch (e) {
dbg(
log(
"Failed to decrypt message using asymmetric encryption despite decryption method being specified",
e
);
@ -183,7 +183,7 @@ export class WakuMessage {
try {
return await version_1.decryptSymmetric(payload, key);
} catch (e) {
dbg(
log(
"Failed to decrypt message using asymmetric encryption despite decryption method being specified",
e
);
@ -193,14 +193,14 @@ export class WakuMessage {
try {
return await version_1.decryptSymmetric(payload, key);
} catch (e) {
dbg(
log(
"Failed to decrypt message using symmetric encryption",
e
);
try {
return await version_1.decryptAsymmetric(payload, key);
} catch (e) {
dbg(
log(
"Failed to decrypt message using asymmetric encryption",
e
);
@ -222,14 +222,14 @@ export class WakuMessage {
const decodedResults = allResults.filter(isDefined);
if (decodedResults.length === 0) {
dbg("Failed to decrypt payload.");
log("Failed to decrypt payload.");
return;
}
const dec = decodedResults[0];
const res = await version_1.clearDecode(dec);
if (!res) {
dbg("Failed to decode payload.");
log("Failed to decode payload.");
return;
}
Object.assign(protoBuf, { payload: res.payload });
@ -252,7 +252,7 @@ export class WakuMessage {
try {
return bytesToUtf8(this.payload);
} catch (e) {
dbg("Could not decode byte as UTF-8", e);
log("Could not decode byte as UTF-8", e);
return "";
}
}

View File

@ -16,7 +16,7 @@ import { DecryptionMethod, WakuMessage } from "../waku_message";
import * as constants from "./constants";
const dbg = debug("waku:relay");
const log = debug("waku:relay");
export interface CreateOptions {
/**
@ -194,11 +194,11 @@ export class WakuRelay extends GossipSub {
}
);
dbg(`Message received on ${pubSubTopic}`);
log(`Message received on ${pubSubTopic}`);
WakuMessage.decode(event.detail.msg.data, decryptionParams)
.then((wakuMsg) => {
if (!wakuMsg) {
dbg("Failed to decode Waku Message");
log("Failed to decode Waku Message");
return;
}
@ -216,7 +216,7 @@ export class WakuRelay extends GossipSub {
}
})
.catch((e) => {
dbg("Failed to decode Waku Message", e);
log("Failed to decode Waku Message", e);
});
}
}

View File

@ -19,7 +19,7 @@ import { DecryptionMethod, WakuMessage } from "../waku_message";
import { PageDirection } from "./history_rpc";
const dbg = debug("waku:test:store");
const log = debug("waku:test:store");
const TestContentTopic = "/test/1/waku-store/utf8";
@ -265,7 +265,7 @@ describe("Waku Store", () => {
}),
]);
dbg("Messages have been encrypted");
log("Messages have been encrypted");
const [waku1, waku2, nimWakuMultiaddr] = await Promise.all([
createWaku({
@ -277,18 +277,18 @@ describe("Waku Store", () => {
nwaku.getMultiaddrWithId(),
]);
dbg("Waku nodes created");
log("Waku nodes created");
await Promise.all([
waku1.dial(nimWakuMultiaddr),
waku2.dial(nimWakuMultiaddr),
]);
dbg("Waku nodes connected to nwaku");
log("Waku nodes connected to nwaku");
await waitForRemotePeer(waku1, [Protocols.LightPush]);
dbg("Sending messages using light push");
log("Sending messages using light push");
await Promise.all([
waku1.lightPush.push(encryptedAsymmetricMessage),
waku1.lightPush.push(encryptedSymmetricMessage),
@ -300,7 +300,7 @@ describe("Waku Store", () => {
waku2.store.addDecryptionKey(symKey);
dbg("Retrieve messages from store");
log("Retrieve messages from store");
const messages = await waku2.store.queryHistory([], {
decryptionParams: [{ key: privateKey }],
});
@ -367,7 +367,7 @@ describe("Waku Store", () => {
),
]);
dbg("Messages have been encrypted");
log("Messages have been encrypted");
const [waku1, waku2, nimWakuMultiaddr] = await Promise.all([
createWaku({
@ -379,18 +379,18 @@ describe("Waku Store", () => {
nwaku.getMultiaddrWithId(),
]);
dbg("Waku nodes created");
log("Waku nodes created");
await Promise.all([
waku1.dial(nimWakuMultiaddr),
waku2.dial(nimWakuMultiaddr),
]);
dbg("Waku nodes connected to nwaku");
log("Waku nodes connected to nwaku");
await waitForRemotePeer(waku1, [Protocols.LightPush]);
dbg("Sending messages using light push");
log("Sending messages using light push");
await Promise.all([
waku1.lightPush.push(encryptedAsymmetricMessage),
waku1.lightPush.push(encryptedSymmetricMessage),
@ -405,7 +405,7 @@ describe("Waku Store", () => {
method: DecryptionMethod.Symmetric,
});
dbg("Retrieve messages from store");
log("Retrieve messages from store");
const messages = await waku2.store.queryHistory([], {
decryptionParams: [{ key: privateKey }],
});

View File

@ -23,7 +23,7 @@ import { HistoryRPC, PageDirection } from "./history_rpc";
import Error = HistoryResponse.HistoryError;
const dbg = debug("waku:store");
const log = debug("waku:store");
export const DefaultPageSize = 10;
@ -147,7 +147,7 @@ export class WakuStore {
{ contentTopics, startTime, endTime }
);
dbg("Querying history with the following options", {
log("Querying history with the following options", {
peerId: options?.peerId?.toString(),
...options,
});
@ -170,7 +170,7 @@ export class WakuStore {
// Do not break as we want to keep the last value
}
}
dbg(`Use store codec ${storeCodec}`);
log(`Use store codec ${storeCodec}`);
if (!storeCodec)
throw `Peer does not register waku store protocol: ${peer.id.toString()}`;
@ -202,7 +202,7 @@ export class WakuStore {
const stream = await connection.newStream(storeCodec);
const queryOpts = Object.assign(opts, { cursor });
const historyRpcQuery = HistoryRPC.createQuery(queryOpts);
dbg("Querying store peer", connections[0].remoteAddr.toString());
log("Querying store peer", connections[0].remoteAddr.toString());
const res = await pipe(
[historyRpcQuery.encode()],
@ -219,7 +219,7 @@ export class WakuStore {
const reply = historyRpcQuery.decode(bytes);
if (!reply.response) {
dbg("No message returned from store: `response` field missing");
log("No message returned from store: `response` field missing");
return messages;
}
@ -231,11 +231,11 @@ export class WakuStore {
if (!response.messages || !response.messages.length) {
// No messages left (or stored)
dbg("No message returned from store: `messages` array empty");
log("No message returned from store: `messages` array empty");
return messages;
}
dbg(
log(
`${response.messages.length} messages retrieved for (${opts.pubSubTopic})`,
contentTopics
);
@ -271,7 +271,7 @@ export class WakuStore {
if (cursor === undefined) {
// If the server does not return cursor then there is an issue,
// Need to abort, or we end up in an infinite loop
dbg("Store response does not contain a cursor, stopping pagination");
log("Store response does not contain a cursor, stopping pagination");
return messages;
}
}

View File

@ -21,7 +21,7 @@ import { existsAsync, mkdirAsync, openAsync } from "./async_fs";
import { delay } from "./delay";
import waitForLine from "./log_file";
const dbg = debug("waku:nwaku");
const log = debug("waku:nwaku");
const WAKU_SERVICE_NODE_DIR =
process.env.WAKU_SERVICE_NODE_DIR ?? appRoot + "/nwaku";
@ -150,7 +150,7 @@ export class Nwaku {
if (WAKU_SERVICE_NODE_PARAMS) {
argsArray.push(WAKU_SERVICE_NODE_PARAMS);
}
dbg(`nwaku args: ${argsArray.join(" ")}`);
log(`nwaku args: ${argsArray.join(" ")}`);
this.process = spawn(WAKU_SERVICE_NODE_BIN, argsArray, {
cwd: WAKU_SERVICE_NODE_DIR,
stdio: [
@ -160,12 +160,12 @@ export class Nwaku {
],
});
this.pid = this.process.pid;
dbg(
log(
`nwaku ${this.process.pid} started at ${new Date().toLocaleTimeString()}`
);
this.process.on("exit", (signal) => {
dbg(
log(
`nwaku ${
this.process ? this.process.pid : this.pid
} process exited with ${signal} at ${new Date().toLocaleTimeString()}`
@ -173,25 +173,25 @@ export class Nwaku {
});
this.process.on("error", (err) => {
console.log(
log(
`nwaku ${
this.process ? this.process.pid : this.pid
} process encountered an error: ${err} at ${new Date().toLocaleTimeString()}`
);
});
dbg(`Waiting to see '${NODE_READY_LOG_LINE}' in nwaku logs`);
log(`Waiting to see '${NODE_READY_LOG_LINE}' in nwaku logs`);
await this.waitForLog(NODE_READY_LOG_LINE, 15000);
if (process.env.CI) await delay(100);
dbg("nwaku node has been started");
log("nwaku node has been started");
}
public stop(): void {
const pid = this.process ? this.process.pid : this.pid;
dbg(`nwaku ${pid} getting SIGINT at ${new Date().toLocaleTimeString()}`);
log(`nwaku ${pid} getting SIGINT at ${new Date().toLocaleTimeString()}`);
if (!this.process) throw "nwaku process not set";
const res = this.process.kill("SIGINT");
dbg(`nwaku ${pid} interrupted:`, res);
log(`nwaku ${pid} interrupted:`, res);
this.process = undefined;
}
@ -375,7 +375,7 @@ export class Nwaku {
method: string,
params: Array<string | number | unknown>
): Promise<T> {
dbg("RPC Query: ", method, params);
log("RPC Query: ", method, params);
const res = await fetch(this.rpcUrl, {
method: "POST",
body: JSON.stringify({
@ -387,7 +387,7 @@ export class Nwaku {
headers: new Headers({ "Content-Type": "application/json" }),
});
const json = await res.json();
dbg(`RPC Response: `, res, json);
log(`RPC Response: `, res, json);
return json.result;
}