Skip to content
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
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default [
"@typescript-eslint/no-empty-object": "off",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "warn",
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/no-non-null-asserted-optional-chain": "off",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-redundant-type-constituents": "warn",
Expand Down
3 changes: 2 additions & 1 deletion packages/api-sync/source/listeners/abstract-listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Identifiers } from "@mainsail/constants";
import { inject, injectable, tagged } from "@mainsail/container";
import type { Contracts } from "@mainsail/contracts";
import { NotImplemented } from "@mainsail/exceptions";
import { setTimeoutAsync } from "@mainsail/utils";

import { EventListener } from "../contracts.js";

Expand Down Expand Up @@ -60,7 +61,7 @@ export abstract class AbstractListener<TEventData, TEntity extends object> imple
} catch (ex) {
this.logger.error(`#syncToDatabaseTransaction failed: ${ex}`);
} finally {
this.#syncTimeout = setTimeout(run, syncInterval);
this.#syncTimeout = setTimeoutAsync(run, syncInterval);
}
};

Expand Down
38 changes: 16 additions & 22 deletions packages/api-sync/source/tokens/whitelist.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,38 +31,32 @@ export class TokenWhitelist {
@inject(Identifiers.Cryptography.Identity.Address.Factory)
private readonly addressFactory!: Contracts.Crypto.AddressFactory;

#syncInterval?: NodeJS.Timeout;
#syncTimeout?: NodeJS.Timeout;

public async bootstrap(): Promise<void> {
const syncInterval = this.#getTokenWhitelistRefreshIntervalMs();

let running = false;

this.logger.info(`Starting TokenWhitelist using remote: ${this.#getTokenWhitelistRemoteUrl()}`);

this.#syncWhitelist()
.catch((error) => this.logger.error(`#syncWhitelist failed: ${error}`))
.finally(() => {
this.#syncInterval = setInterval(async () => {
if (running) {
return;
}

running = true;

try {
await this.#syncWhitelist();
} catch (ex) {
this.logger.error(`#syncWhitelist failed: ${ex}`);
} finally {
running = false;
}
const run = async () => {
try {
await this.#syncWhitelist();
} catch (ex) {
this.logger.error(`#syncWhitelist failed: ${ex}`);
} finally {
this.#syncTimeout = setTimeout(() => {
void run();
}, syncInterval);
});
}
};

void run();
}

public async dispose(): Promise<void> {
clearInterval(this.#syncInterval);
if (this.#syncTimeout) {
clearTimeout(this.#syncTimeout);
}
}

async #syncWhitelist(): Promise<void> {
Expand Down
9 changes: 5 additions & 4 deletions packages/consensus/source/scheduler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Identifiers } from "@mainsail/constants";
import { inject, injectable } from "@mainsail/container";
import type { Contracts } from "@mainsail/contracts";
import { setTimeoutAsync } from "@mainsail/utils";
import dayjs from "dayjs";

@injectable()
Expand Down Expand Up @@ -33,7 +34,7 @@ export class Scheduler implements Contracts.Consensus.Scheduler {

const timeout = Math.max(0, timestamp - dayjs().valueOf());

this.#timeoutStartRound = setTimeout(async () => {
this.#timeoutStartRound = setTimeoutAsync(async () => {
await this.#getConsensus().onTimeoutStartRound();
this.#timeoutStartRound = undefined;
}, timeout);
Expand All @@ -46,7 +47,7 @@ export class Scheduler implements Contracts.Consensus.Scheduler {
return false;
}

this.#timeoutPropose = setTimeout(async () => {
this.#timeoutPropose = setTimeoutAsync(async () => {
await this.#getConsensus().onTimeoutPropose(height, round);
this.#timeoutPropose = undefined;
}, this.#getTimeout(round));
Expand All @@ -59,7 +60,7 @@ export class Scheduler implements Contracts.Consensus.Scheduler {
return false;
}

this.#timeoutPrevote = setTimeout(async () => {
this.#timeoutPrevote = setTimeoutAsync(async () => {
await this.#getConsensus().onTimeoutPrevote(height, round);
this.#timeoutPrevote = undefined;
}, this.#getTimeout(round));
Expand All @@ -72,7 +73,7 @@ export class Scheduler implements Contracts.Consensus.Scheduler {
return false;
}

this.#timeoutPrecommit = setTimeout(async () => {
this.#timeoutPrecommit = setTimeoutAsync(async () => {
await this.#getConsensus().onTimeoutPrecommit(height, round);
this.#timeoutPrecommit = undefined;
}, this.#getTimeout(round));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ export class ListenToShutdownSignals implements Contracts.Kernel.Bootstrapper {

public async bootstrap(): Promise<void> {
for (const signal in Enums.Kernel.ShutdownSignal) {
process.on(signal, async (code) => {
await this.app.terminate(signal);
process.on(signal, (_) => {
void this.#onSignal(signal);
});
}
}

async #onSignal(signal: string) {
await this.app.terminate(signal);
}
}
26 changes: 15 additions & 11 deletions packages/kernel/source/ipc/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,21 @@ export class Handler<T extends object> implements Contracts.Kernel.IPC.Handler<T
}

public handleRequest(): void {
parentPort?.on("message", async (message) => {
if (this.handler[message.method] === undefined) {
throw new Error(`Method ${message.method} is not defined on the handler`);
}

try {
const result = await this.handler[message.method](...message.args);
parentPort?.postMessage({ id: message.id, result });
} catch (error) {
parentPort?.postMessage({ error: error.message, id: message.id });
}
parentPort?.on("message", (message) => {
void this.#onMessage(message);
});
}

async #onMessage(message: { method: string; id: string; args: [] }) {
if (this.handler[message.method] === undefined) {
throw new Error(`Method ${message.method} is not defined on the handler`);
}

try {
const result = await this.handler[message.method](...message.args);
parentPort?.postMessage({ id: message.id, result });
} catch (error) {
parentPort?.postMessage({ error: error.message, id: message.id });
}
}
}
21 changes: 12 additions & 9 deletions packages/kernel/source/services/config/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,25 @@ export class Watcher {
private readonly app!: Contracts.Kernel.Application;

#watcher!: nsfw.NSFW;
#configFiles = new Set([".env", "validators.json", "peers.json", "plugins.js", "plugins.json"]);

public async boot(): Promise<void> {
const configFiles = new Set([".env", "validators.json", "peers.json", "plugins.js", "plugins.json"]);

this.#watcher = await nsfw(this.app.configPath(), async (events) => {
for (const event of events) {
if (event.action === nsfw.ActionType.MODIFIED && configFiles.has(event.file)) {
await this.app.reboot();
break;
}
}
this.#watcher = await nsfw(this.app.configPath(), (events) => {
void this.#handleEvents(events);
});

await this.#watcher.start();
}

async #handleEvents(events: nsfw.FileChangeEvent[]) {
for (const event of events) {
if (event.action === nsfw.ActionType.MODIFIED && this.#configFiles.has(event.file)) {
await this.app.reboot();
break;
}
}
}

public async dispose(): Promise<void> {
return this.#watcher.stop();
}
Expand Down
4 changes: 2 additions & 2 deletions packages/kernel/source/services/filesystem/drivers/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export class LocalFilesystem implements Contracts.Kernel.Filesystem {
return this.fs
.readdirSync(directory)
.map((item: string) => `${directory}/${item}`)
.filter(async (item: string) => this.fs.lstatSync(item).isFile());
.filter((item: string) => this.fs.lstatSync(item).isFile());
}

public async directories(directory: string): Promise<string[]> {
Expand All @@ -89,7 +89,7 @@ export class LocalFilesystem implements Contracts.Kernel.Filesystem {
return this.fs
.readdirSync(directory)
.map((item: string) => `${directory}/${item}`)
.filter(async (item: string) => this.fs.lstatSync(item).isDirectory());
.filter((item: string) => this.fs.lstatSync(item).isDirectory());
}

public async makeDirectory(path: string): Promise<boolean> {
Expand Down
2 changes: 1 addition & 1 deletion packages/kernel/source/services/queue/drivers/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class MemoryQueue extends EventEmitter implements Contracts.Kernel.Queue
}

public async later(delay: number, job: Contracts.Kernel.QueueJob): Promise<void> {
setTimeout(() => this.push(job), delay);
setTimeout(() => void this.push(job), delay);
}

public async bulk(jobs: Contracts.Kernel.QueueJob[]): Promise<void> {
Expand Down
11 changes: 9 additions & 2 deletions packages/p2p/source/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ export class Service implements Contracts.P2P.Service {
await this.#checkReceivedMessages();

if (!this.#disposed) {
this.#mainLoopTimeout = setTimeout(() => this.mainLoop(), 2000);
this.#mainLoopTimeout = setTimeout(() => {
void this.mainLoop();
}, 2000);
}
}

Expand Down Expand Up @@ -108,7 +110,9 @@ export class Service implements Contracts.P2P.Service {

if (!this.#disposed) {
const nextTimeout = randomNumber(10, 20) * 60 * 1000;
this.#apiNodeCheckLoopTimeout = setTimeout(() => this.#checkApiNodes(), nextTimeout);
this.#apiNodeCheckLoopTimeout = setTimeout(() => {
void this.#checkApiNodes();
}, nextTimeout);
}
}

Expand All @@ -127,6 +131,8 @@ export class Service implements Contracts.P2P.Service {

// we use Promise.race to cut loose in case some communicator.ping() does not resolve within the delay
// in that case we want to keep on with our program execution while ping promises can finish in the background
// TODO: revisit
/* eslint-disable @typescript-eslint/no-misused-promises */
await new Promise<void>(async (resolve) => {
let isResolved = false;

Expand All @@ -150,6 +156,7 @@ export class Service implements Contracts.P2P.Service {

await delay(pingDelay).finally(resolvesFirst);
});
/* eslint-enable */

if (unresponsivePeers > 0) {
this.logger.debug(`Removed ${pluralize("peer", unresponsivePeers, true)}`, "p2p");
Expand Down
8 changes: 4 additions & 4 deletions packages/test-runner/source/describe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ type ContextFunction<T> = () => T;
type ContextCallback<T> = (context: T) => Promise<void> | void;

interface CallbackArguments<T> {
afterAll: (callback_: ContextCallback<T>) => void;
afterEach: (callback_: ContextCallback<T>) => void;
afterAll: (callback_: ContextCallback<T>) => Promise<void>;
afterEach: (callback_: ContextCallback<T>) => Promise<void>;
assert: typeof assert;
beforeAll: (callback_: ContextCallback<T>) => void;
beforeEach: (callback_: ContextCallback<T>) => void;
beforeAll: (callback_: ContextCallback<T>) => Promise<void>;
beforeEach: (callback_: ContextCallback<T>) => Promise<void>;
clock: (config?: number | Date | { now?: number | Date | undefined }) => sinon.SinonFakeTimers;

dataset: unknown;
Expand Down
1 change: 1 addition & 0 deletions packages/utils/source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ export * from "./reverse.js";
export * from "./sample.js";
export * from "./semver.js";
export * from "./set.js";
export * from "./set-timeout-async.js";
export * from "./shuffle.js";
export * from "./sleep.js";
export * from "./snake-case.js";
Expand Down
22 changes: 22 additions & 0 deletions packages/utils/source/set-timeout-async.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe } from "@mainsail/test-runner";
import { setTimeoutAsync } from "./set-timeout-async";

describe("setTimeoutAsync", async ({ assert, it }) => {
it("should be ok", async () => {
const events: string[] = [];

const done = new Promise<void>((resolve) => {
const timeout = setTimeoutAsync(async () => {
events.push("callback");
await Promise.resolve();
resolve();
}, 100);
});

events.push("after-call");

await done;

assert.equal(events, ["after-call", "callback"]);
});
});
6 changes: 6 additions & 0 deletions packages/utils/source/set-timeout-async.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const setTimeoutAsync = (callback: () => Promise<void>, delay: number): NodeJS.Timeout =>
setTimeout(() => {
void (async () => {
await callback();
})();
}, delay);
Loading