Skip to content

Commit

Permalink
Force name functions (#2867)
Browse files Browse the repository at this point in the history
* Force functions to be named

* Change arrow functions to regular functions

* Make tests .test.ts

* name functions

* Review PR

* Revert test change
dapplion authored Jul 22, 2021

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 25ec250 commit 7e00bf4
Showing 21 changed files with 44 additions and 58 deletions.
3 changes: 3 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -117,6 +117,8 @@ module.exports = {
quotes: ["error", "double"],
semi: "off",
"no-restricted-imports": ["error", {patterns: ["../lib/*", "@chainsafe/*/lib/*"]}],
// Force to add names to all functions to ease CPU profiling
"func-names": ["error", "always"],

// Prevents accidentally pushing a commit with .only in Mocha tests
"no-only-tests/no-only-tests": "error",
@@ -127,6 +129,7 @@ module.exports = {
rules: {
"import/no-extraneous-dependencies": "off",
"@typescript-eslint/no-explicit-any": "off",
"func-names": "off",
},
},
{
2 changes: 1 addition & 1 deletion packages/api/src/client/events.ts
Original file line number Diff line number Diff line change
@@ -28,7 +28,7 @@ export function getClient(_config: IChainForkConfig, baseUrl: string): Api {
// EventSource will try to reconnect always on all errors
// `eventSource.onerror` events are informative but don't indicate the EventSource closed
// The only way to abort the connection from the client is via eventSource.close()
eventSource.onerror = function (err) {
eventSource.onerror = function onerror(err) {
const errEs = (err as unknown) as EventSourceError;
// Consider 400 and 500 status errors unrecoverable, close the eventsource
if (errEs.status === 400) {
2 changes: 1 addition & 1 deletion packages/api/src/utils/urlFormat.ts
Original file line number Diff line number Diff line change
@@ -65,7 +65,7 @@ export function compileRouteUrlFormater(path: string): (arg: Args) => string {
}
});

return function (args: Args) {
return function urlFormater(args: Args) {
// Don't use .map() or .join(), it's x3 slower
let s = "";
for (const fn of fns) s += fn(args);
Original file line number Diff line number Diff line change
@@ -34,6 +34,7 @@ import {
import {getNextSyncCommittee} from "../../altair/epoch/sync_committee";
import {ssz} from "@chainsafe/lodestar-types";
import {CachedInactivityScoreList, CachedInactivityScoreListProxyHandler} from "./cachedInactivityScoreList";
import {newFilledArray} from "../../util";

/**
* `BeaconState` with various caches
@@ -79,12 +80,8 @@ export function createCachedBeaconState<T extends allForks.BeaconState>(
};
currIndexedSyncCommittee = emptyIndexedSyncCommittee;
nextIndexedSyncCommittee = emptyIndexedSyncCommittee;
cachedPreviousParticipation = MutableVector.from(
Array.from({length: cachedValidators.length}, () => emptyParticipationStatus)
);
cachedCurrentParticipation = MutableVector.from(
Array.from({length: cachedValidators.length}, () => emptyParticipationStatus)
);
cachedPreviousParticipation = MutableVector.from(newFilledArray(cachedValidators.length, emptyParticipationStatus));
cachedCurrentParticipation = MutableVector.from(newFilledArray(cachedValidators.length, emptyParticipationStatus));
cachedInactivityScores = MutableVector.empty();
} else {
const {pubkey2index} = epochCtx;
2 changes: 1 addition & 1 deletion packages/cli/src/util/file.ts
Original file line number Diff line number Diff line change
@@ -11,7 +11,7 @@ export const yamlSchema = new Schema({
implicit: [
new Type("tag:yaml.org,2002:str", {
kind: "scalar",
construct: function (data) {
construct: function construct(data) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return data !== null ? data : "";
},
4 changes: 2 additions & 2 deletions packages/cli/src/util/process.ts
Original file line number Diff line number Diff line change
@@ -12,10 +12,10 @@ export function onGracefulShutdown(
logFn: (msg: string) => void = console.log
): void {
for (const signal of exitSignals) {
process.once(signal, async () => {
process.once(signal, async function onSignal() {
logFn("Stopping gracefully, use Ctrl+C again to force process exit");

process.on(signal, () => {
process.on(signal, function onSecondSignal() {
logFn("Forcing process exit");
process.exit(1);
});
2 changes: 1 addition & 1 deletion packages/lodestar/src/network/gossip/validation/index.ts
Original file line number Diff line number Diff line change
@@ -60,7 +60,7 @@ function getGossipValidatorFn<K extends GossipType>(
const {config, logger, metrics, uncompressCache, gossipTopicCache} = modules;
const getGossipObjectAcceptMetadata = getGossipAcceptMetadataByType[type] as GetGossipAcceptMetadataFn;

return async function (topicStr, gossipMsg) {
return async function gossipValidatorFn(topicStr, gossipMsg) {
try {
const topic = gossipTopicCache.getTopic(topicStr);
const encoding = topic.encoding ?? DEFAULT_ENCODING;
2 changes: 1 addition & 1 deletion packages/lodestar/src/network/gossip/validation/queue.ts
Original file line number Diff line number Diff line change
@@ -52,7 +52,7 @@ export function wrapWithQueue(
: undefined
);

return async function (topicStr, gossipMsg) {
return async function gossipValidatorFnWithQueue(topicStr, gossipMsg) {
await jobQueue.push(async () => gossipValidatorFn(topicStr, gossipMsg));
};
}
2 changes: 1 addition & 1 deletion packages/lodestar/src/network/network.ts
Original file line number Diff line number Diff line change
@@ -120,7 +120,7 @@ export class Network implements INetwork {
);

this.chain.emitter.on(ChainEvent.clockEpoch, this.onEpoch);
modules.signal.addEventListener("abort", () => this.close(), {once: true});
modules.signal.addEventListener("abort", this.close.bind(this), {once: true});
}

/** Destroy this instance. Can only be called once. */
4 changes: 2 additions & 2 deletions packages/lodestar/src/network/peers/peerManager.ts
Original file line number Diff line number Diff line change
@@ -119,8 +119,8 @@ export class PeerManager {
// On start-up will connected to existing peers in libp2p.peerStore, same as autoDial behaviour
this.heartbeat();
this.intervals = [
setInterval(() => this.pingAndStatusTimeouts(), CHECK_PING_STATUS_INTERVAL),
setInterval(() => this.heartbeat(), HEARTBEAT_INTERVAL_MS),
setInterval(this.pingAndStatusTimeouts.bind(this), CHECK_PING_STATUS_INTERVAL),
setInterval(this.heartbeat.bind(this), HEARTBEAT_INTERVAL_MS),
];
}

Original file line number Diff line number Diff line change
@@ -12,7 +12,7 @@ import {readEncodedPayload} from "../encodingStrategies";
export function requestDecode(
protocol: Pick<Protocol, "method" | "encoding">
): (source: AsyncIterable<Buffer | BufferList>) => Promise<RequestBody> {
return async function (source) {
return async function requestDecodeSink(source) {
const type = getRequestSzzTypeByMethod(protocol.method);
if (!type) {
// method has no body
Original file line number Diff line number Diff line change
@@ -33,7 +33,7 @@ export function responseDecode(
forkDigestContext: IForkDigestContext,
protocol: Protocol
): (source: AsyncIterable<Buffer>) => AsyncGenerator<ResponseBody> {
return async function* (source) {
return async function* responseDecodeSink(source) {
const deserializeToTree = deserializeToTreeByMethod[protocol.method];
const contextBytesType = contextBytesTypeByProtocol(protocol);
const bufferedSource = new BufferedSource(source as AsyncGenerator<Buffer>);
Original file line number Diff line number Diff line change
@@ -31,7 +31,7 @@ export function responseEncodeSuccess(
): (source: AsyncIterable<ResponseBody>) => AsyncIterable<Buffer> {
const contextBytesType = contextBytesTypeByProtocol(protocol);

return async function* (source) {
return async function* responseEncodeSuccessTransform(source) {
for await (const chunk of source) {
// <result>
yield Buffer.from([RespStatus.SUCCESS]);
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@ export function responseTimeoutsHandler<T>(
responseDecoder: (source: AsyncIterable<Buffer>) => AsyncGenerator<T>,
options?: Partial<typeof timeoutOptions>
): (source: AsyncIterable<Buffer>) => AsyncGenerator<T> {
return async function* (source) {
return async function* responseTimeoutsHandlerTransform(source) {
const {TTFB_TIMEOUT, RESP_TIMEOUT} = {...timeoutOptions, ...options};

const ttfbTimeoutController = new AbortController();
2 changes: 1 addition & 1 deletion packages/lodestar/src/network/reqresp/response/index.ts
Original file line number Diff line number Diff line change
@@ -56,7 +56,7 @@ export async function handleRequest(
// Yields success chunks and error chunks in the same generator
// This syntax allows to recycle stream.sink to send success and error chunks without returning
// in case request whose body is a List fails at chunk_i > 0, without breaking out of the for..await..of
(async function* () {
(async function* requestHandlerSource() {
try {
const requestBody = await withTimeout(
() => pipe(stream.source, requestDecode(protocol)),
2 changes: 1 addition & 1 deletion packages/lodestar/src/network/reqresp/utils/onChunk.ts
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@
* Useful for logging, or cancelling timeouts
*/
export function onChunk<T>(callback: (chunk: T) => void): (source: AsyncIterable<T>) => AsyncIterable<T> {
return async function* (source) {
return async function* onChunkTransform(source) {
for await (const chunk of source) {
callback(chunk);
yield chunk;
25 changes: 0 additions & 25 deletions packages/lodestar/src/util/io.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/lodestar/test/utils/network.ts
Original file line number Diff line number Diff line change
@@ -40,14 +40,14 @@ export async function disconnect(network: Network, peer: PeerId): Promise<void>
export function onPeerConnect(network: Network): Promise<void> {
return new Promise<void>((resolve) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
network["libp2p"].connectionManager.on(Libp2pEvent.peerConnect, () => resolve())
network["libp2p"].connectionManager.on(Libp2pEvent.peerConnect, resolve)
);
}

export function onPeerDisconnect(network: Network): Promise<void> {
return new Promise<void>((resolve) =>
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
network["libp2p"].connectionManager.on(Libp2pEvent.peerDisconnect, () => resolve())
network["libp2p"].connectionManager.on(Libp2pEvent.peerDisconnect, resolve)
);
}

13 changes: 9 additions & 4 deletions packages/spec-test-util/src/multi.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
/* eslint-disable @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any,@typescript-eslint/no-unused-vars */
import {writeFile} from "fs";
import {expect} from "chai";
import {loadYamlFile} from "./util";

/* eslint-disable
@typescript-eslint/no-unsafe-call,
@typescript-eslint/no-unsafe-member-access,
@typescript-eslint/no-unsafe-return,
@typescript-eslint/no-unsafe-assignment,
@typescript-eslint/no-explicit-any,
@typescript-eslint/no-unused-vars,
func-names */

export interface IBaseCase {
description: string;
}
@@ -23,8 +30,6 @@ interface TestSpec<TestCase extends IBaseCase> {
testCases: TestCase[];
}

const env = process.env;

/**
* Run yaml Eth2.0 bulk spec tests (m) for a certain function
* Compares actual vs expected for all test cases
8 changes: 7 additions & 1 deletion packages/spec-test-util/src/single.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any */
import {expect} from "chai";
import {readdirSync, readFileSync, existsSync} from "fs";
import {basename, join, parse} from "path";
import {Type, CompositeType} from "@chainsafe/ssz";
import {uncompress} from "snappyjs";
import {isDirectory, loadYamlFile} from "./util";

/* eslint-disable
@typescript-eslint/no-unsafe-assignment,
@typescript-eslint/no-unsafe-member-access,
@typescript-eslint/no-unsafe-return,
@typescript-eslint/no-explicit-any,
func-names */

export enum InputType {
SSZ = "ssz",
SSZ_SNAPPY = "ssz_snappy",
8 changes: 4 additions & 4 deletions packages/utils/src/yaml/int.ts
Original file line number Diff line number Diff line change
@@ -165,22 +165,22 @@ export const intType = new Type("tag:yaml.org,2002:int", {
represent: {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
binary: function (obj: number) {
binary: function binary(obj: number) {
return obj >= 0 ? "0b" + obj.toString(2) : "-0b" + obj.toString(2).slice(1);
},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
octal: function (obj: number) {
octal: function octal(obj: number) {
return obj >= 0 ? "0" + obj.toString(8) : "-0" + obj.toString(8).slice(1);
},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
decimal: function (obj: number) {
decimal: function decimal(obj: number) {
return obj.toString(10);
},
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
hexadecimal: function (obj: number) {
hexadecimal: function hexadecimal(obj: number) {
return obj >= 0 ? "0x" + obj.toString(16).toUpperCase() : "-0x" + obj.toString(16).toUpperCase().slice(1);
},
},

0 comments on commit 7e00bf4

Please sign in to comment.