Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(engine): give the init deadline a home outside the wwjs adapter
Yudhi Armyndharise4802d601d43
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9e2b4d441..5a134f078 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -56,6 +56,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the same captured `(id, engine)` the closure did, so the stale-generation identity guards areunchanged.+- **The session lifecycle no longer imports the whatsapp-web.js adapter to size a timeout.** The+ deadline `SessionService` races `engine.initialize()` against is engine-agnostic — it applies to+ Baileys sessions too — but it was derived inline from `resolveAuthTimeoutMs()`, which the adapter+ owned, so the lifecycle owner depended on one specific engine's module for a value it applies to+ all of them. Both the env parse and the derivation now live in `engine/engine-init-timeout.ts`, and+ the adapter re-exports `resolveAuthTimeoutMs` for the callers that legitimately reach it through+ the engine they are configuring.++ Pure code motion — the derived deadline is identical, and both+ `whatsapp-web-js.adapter.spec.ts` and `session.service.spec.ts` pass with no edits. The wwjs-named+ `WWEBJS_AUTH_TIMEOUT_MS` still feeds the shared floor, which is documented rather than changed: it+ can only ever raise the deadline above 60s, never lower it, so a Baileys session gets a more+ generous window and never a shorter one. Splitting the two engines' windows needs its own env var+ and is a behaviour change, not a move.+### Fixed- **A missing dashboard asset returns 404 instead of the SPA shell.** `ServeStaticModule`'s built-indiff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 4f71f1f50..b23958060 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -50,6 +50,7 @@ import {IncomingCallEvent,} from '../interfaces/whatsapp-engine.interface';import { resolveWebVersionPin } from '../wa-web-version';+import { resolveAuthTimeoutMs } from '../engine-init-timeout';import { chatKind, isChannelJid, userPart } from '../identity/wa-id';import { LidMappingStore } from '../identity/lid-mapping-store.service';import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';@@ -390,23 +391,11 @@ export function probeOnboardingModal(options?: { labels?: string[]; headingOptio// status can import it without loading whatsapp-web.js (engine lazy-loading). The adapter imports// resolveWebVersionPin above for use in initialize().-/**- * Optional override for whatsapp-web.js's initial boot/inject wait (#353). On slow first boots- * (e.g. WSL2 or low-resource containers) the default 30s `authTimeoutMs` can expire before WhatsApp- * Web finishes loading, aborting QR generation. Set WWEBJS_AUTH_TIMEOUT_MS to a larger value in- * milliseconds (e.g. 120000) to extend it. Unset, or a value that is not a positive safe integer,- * keeps the whatsapp-web.js default (30000ms).- */-export function resolveAuthTimeoutMs(): number | undefined {- const raw = process.env.WWEBJS_AUTH_TIMEOUT_MS?.trim();- if (!raw || !/^\d+$/.test(raw)) {- return undefined;- }- const ms = Number(raw);- // Number.isSafeInteger rejects Infinity (from huge digit strings) and >2^53 unsafe integers — both- // pass the /^\d+$/ shape check but would make whatsapp-web.js's inject loop wait effectively forever.- return Number.isSafeInteger(ms) && ms > 0 ? ms : undefined;-}+// resolveAuthTimeoutMs now lives in ../engine-init-timeout, next to the outer init deadline derived+// from it: that deadline is engine-agnostic, so deriving it here made the session lifecycle import+// this adapter just to size a timeout. Re-exported because callers still reach it through the engine+// they are configuring.+export { resolveAuthTimeoutMs };/*** Extracts the JID of the parent community a group is linked to, if any.diff --git a/src/engine/engine-init-timeout.ts b/src/engine/engine-init-timeout.tsnew file mode 100644index 000000000..6d84c5aeb--- /dev/null+++ b/src/engine/engine-init-timeout.ts@@ -0,0 +1,45 @@+/**+ * The deadline the session lifecycle races `engine.initialize()` against, and the whatsapp-web.js+ * auth window it is derived from.+ *+ * These live outside the adapters because the OUTER deadline is engine-agnostic — SessionService+ * applies it to every engine — while the value it must clear is set by whatsapp-web.js. Deriving it+ * inside `session.service.ts` meant the lifecycle owner imported the wwjs adapter just to size a+ * timeout, which is why this pair now has one home instead of a cross-layer import.+ */++/**+ * Optional override for whatsapp-web.js's initial boot/inject wait (#353). On slow first boots+ * (e.g. WSL2 or low-resource containers) the default 30s `authTimeoutMs` can expire before WhatsApp+ * Web finishes loading, aborting QR generation. Set WWEBJS_AUTH_TIMEOUT_MS to a larger value in+ * milliseconds (e.g. 120000) to extend it. Unset, or a value that is not a positive safe integer,+ * keeps the whatsapp-web.js default (30000ms).+ */+export function resolveAuthTimeoutMs(): number | undefined {+ const raw = process.env.WWEBJS_AUTH_TIMEOUT_MS?.trim();+ if (!raw || !/^\d+$/.test(raw)) {+ return undefined;+ }+ const ms = Number(raw);+ // Number.isSafeInteger rejects Infinity (from huge digit strings) and >2^53 unsafe integers — both+ // pass the /^\d+$/ shape check but would make whatsapp-web.js's inject loop wait effectively forever.+ return Number.isSafeInteger(ms) && ms > 0 ? ms : undefined;+}++/**+ * How long a session waits for `engine.initialize()` before treating it as wedged.+ *+ * The deadline MUST exceed the auth wait whatsapp-web.js runs INSIDE engine.initialize()+ * (authTimeoutMs — the inject() poll for WA Web's JS to bootstrap, raisable via+ * WWEBJS_AUTH_TIMEOUT_MS for slow first boots). A shorter outer deadline would SIGKILL a legitimate+ * slow init mid-auth. Floor 60s for the hang case; otherwise the configured auth window plus 30s for+ * launch/navigation/post-inject overhead.+ *+ * WWEBJS_AUTH_TIMEOUT_MS can only ever RAISE this above the 60s floor, never lower it, so a+ * Baileys session whose operator set it for whatsapp-web.js gets a more generous deadline — never a+ * shorter one. Giving the two engines separate windows would need its own env var and is a+ * behaviour change, not part of moving this out of the adapter.+ */+export function resolveEngineInitTimeoutMs(): number {+ return Math.max(60_000, (resolveAuthTimeoutMs() ?? 30_000) + 30_000);+}diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex f77a33ad2..128dd4296 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -27,7 +27,7 @@ import { decideReconnect, type ReconnectAttemptState } from './reconnect-policy'import { SessionLidResolver } from './session-lid-resolver.service';import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';-import { resolveAuthTimeoutMs } from '../../engine/adapters/whatsapp-web-js.adapter';+import { resolveEngineInitTimeoutMs } from '../../engine/engine-init-timeout';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';import { resolveFeatureFlags } from '../../config/feature-flags';@@ -1181,12 +1181,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// propagate untouched so start()'s catch keeps owning FAILED+reason (the diagnosability #600/#631// added) — pre-deleting the engine and writing DISCONNECTED here would make start()'s// `engines.get(id)` return undefined, skip its FAILED write, and hide the failure reason.- // The deadline MUST exceed the auth wait whatsapp-web.js runs INSIDE engine.initialize()- // (authTimeoutMs — the inject() poll for WA Web's JS to bootstrap, raisable via- // WWEBJS_AUTH_TIMEOUT_MS for slow first boots, e.g. WSL2/low-resource containers). A shorter- // outer deadline would SIGKILL a legitimate slow init mid-auth. Floor 60s for the hang case;- // otherwise give the configured auth window + 30s for launch/navigation/post-inject overhead.- const engineInitTimeoutMs = Math.max(60_000, (resolveAuthTimeoutMs() ?? 30_000) + 30_000);+ // The deadline must clear the auth wait an engine runs INSIDE initialize(), or it would SIGKILL a+ // legitimately slow init mid-auth — see resolveEngineInitTimeoutMs for the derivation.+ const engineInitTimeoutMs = resolveEngineInitTimeoutMs();// Promise.race can't cancel the losing promise, so swallow a late rejection from initPromise.initPromise.catch(() => undefined);