From f5eaffdf95eb61b6d09f7694ac822441769cf14e Mon Sep 17 00:00:00 2001 From: Spencer T Brody Date: Mon, 29 Jul 2024 14:16:09 -0400 Subject: [PATCH] make background job shutdown cleanly --- packages/core/src/ceramic.ts | 9 +++------ packages/core/src/shutdown-signal.ts | 6 ++++++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/core/src/ceramic.ts b/packages/core/src/ceramic.ts index 5e2f18cd36..79f3a69009 100644 --- a/packages/core/src/ceramic.ts +++ b/packages/core/src/ceramic.ts @@ -24,6 +24,7 @@ import { CeramicSigner, StreamStateLoader, StreamReaderWriter, + delayOrAbort, } from '@ceramicnetwork/common' import { DEFAULT_TRACE_SAMPLE_RATIO, @@ -683,12 +684,8 @@ export class Ceramic implements StreamReaderWriter, StreamStateLoader { let attemptNum = 0 let backoffMs = 100 const maxBackoffMs = 1000 * 60 // Caps off at checking once per minute - const delay = async function (ms) { - return new Promise((resolve) => setTimeout(() => resolve(), ms)) - } - // eslint-disable-next-line no-constant-condition - while (true) { + while (!this._shutdownSignal.isShuttingDown()) { try { await this.dispatcher.getFromIpfs(model.cid) if (attemptNum > 0) { @@ -704,7 +701,7 @@ export class Ceramic implements StreamReaderWriter, StreamStateLoader { this._logger.err(`Error loading Model ${model} used to publish Node Metrics: ${err}`) } - await delay(backoffMs) + await this._shutdownSignal.abortable((signal) => delayOrAbort(backoffMs, signal)) attemptNum++ if (backoffMs <= maxBackoffMs) { backoffMs *= 2 diff --git a/packages/core/src/shutdown-signal.ts b/packages/core/src/shutdown-signal.ts index aa9ee1ab72..f061b88b0f 100644 --- a/packages/core/src/shutdown-signal.ts +++ b/packages/core/src/shutdown-signal.ts @@ -7,6 +7,7 @@ import { Observer, Subject } from 'rxjs' */ export class ShutdownSignal { private subject: Subject = new Subject() + private shuttingDown = false /** * Subscribers to the signal. @@ -20,6 +21,11 @@ export class ShutdownSignal { */ abort(): void { this.subject.complete() + this.shuttingDown = true + } + + isShuttingDown(): boolean { + return this.shuttingDown } /**