Skip to content

Commit

Permalink
feat: Stop the client gracefully. (#451)
Browse files Browse the repository at this point in the history
  • Loading branch information
vxern authored Oct 21, 2024
2 parents 45d35fe + 28b0d02 commit 574792a
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion source/library/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class Client {

readonly #channelDeletes: Collector<"channelDelete">;

#isStopping = false;
#stopSignal: string | undefined;

get localiseRaw(): LocalisationStore["localiseRaw"] {
return this.#localisations.localiseRaw.bind(this.#localisations);
}
Expand Down Expand Up @@ -240,6 +243,8 @@ class Client {
}

async start(): Promise<void> {
this.#stopOnSignal();

this.log.info("Starting client...");

await this.volatile?.setup();
Expand All @@ -254,9 +259,21 @@ class Client {
this.log.info("Client started.");
}

async stop(): Promise<void> {
async stop({ signal }: { signal?: string }): Promise<void> {
if (this.#isStopping) {
if (this.#stopSignal === signal) {
this.log.info("The client is already being stopped...");
return;
}

return;
}

this.log.info("Stopping client...");

this.#isStopping = true;
this.#stopSignal = signal;

this.volatile?.teardown();
await this.database.teardown();
await this.services.teardown();
Expand All @@ -266,8 +283,22 @@ class Client {
this.#teardownCollectors();
await this.#connection.close();

this.#isStopping = false;
this.#stopSignal = undefined;

this.log.info("Client stopped.");
}

#stopOnSignal(): void {
process.on("SIGINT", async () => {
await this.stop({ signal: "SIGINT" });
process.exit();
});
process.on("SIGTERM", async () => {
await this.stop({ signal: "SIGTERM" });
process.exit();
});
}
}

export { Client };

0 comments on commit 574792a

Please sign in to comment.