A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
perf(worker): wait for the actions stream before consuming
Hampusf88feb72ff6a
diff --git a/fluxer_api/src/api/worker/AccountActionConsumer.ts b/fluxer_api/src/api/worker/AccountActionConsumer.tsindex 22a288c88..07a86d65b 100644--- a/fluxer_api/src/api/worker/AccountActionConsumer.ts+++ b/fluxer_api/src/api/worker/AccountActionConsumer.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {setTimeout as sleep} from 'node:timers/promises';import {applyPauseGuildInvites, type GuildInvitePauseDeps} from '@app/api/guild/services/GuildInvitePauseApplier';import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';import {workerMeta} from '@app/api/infrastructure/activity/ActivityMeta';@@ -23,10 +24,17 @@ import {applyTempBanIp,outcomeOf,} from '@app/api/user/services/AccountStateApplier';-import {AckPolicy, type ConsumerMessages, type JetStreamClient, type JsMsg} from '@nats-io/jetstream';+import {+ AckPolicy,+ type ConsumerMessages,+ JetStreamApiCodes,+ JetStreamApiError,+ type JetStreamClient,+ type JsMsg,+} from '@nats-io/jetstream';export interface AccountActionDeps {- js: Pick<JetStreamClient, 'consumers'>;+ js: Pick<JetStreamClient, 'consumers' | 'streams'>;state: AccountStateDeps;guildInvites: GuildInvitePauseDeps;publishOutcome?: (key: string, outcome: ActionOutcome) => Promise<void>;@@ -35,12 +43,15 @@ export interface AccountActionDeps {}const RETRY_DELAY_MS = 5000;+const STREAM_RECHECK_MS = 300_000;const MAX_NAK_DELAY_MS = 30_000;interface ConsumerState {stopped: boolean;+ abort: AbortController;loops: Array<ConsumerMessages>;tasks: Array<Promise<void>>;+ streamReady: Promise<void> | null;}let running: ConsumerState | null = null;@@ -118,9 +129,44 @@ async function handleActionMessage(deps: AccountActionDeps, msg: JsMsg): Promiseawait msg.ackAck();}+async function pause(state: ConsumerState, ms: number): Promise<void> {+ await sleep(ms, undefined, {signal: state.abort.signal, ref: false}).catch(() => undefined);+}++async function waitForActionsStream(deps: AccountActionDeps, state: ConsumerState): Promise<void> {+ let missingLogged = false;+ while (!state.stopped) {+ try {+ await deps.js.streams.get(ACTIONS_STREAM);+ if (missingLogged) Logger.info({stream: ACTIONS_STREAM}, 'Account action stream found, consuming actions');+ return;+ } catch (error) {+ if (!(error instanceof JetStreamApiError && error.code === JetStreamApiCodes.StreamNotFound)) {+ Logger.debug({err: error}, 'Account action stream check failed, retrying');+ await pause(state, deps.retryDelayMs ?? RETRY_DELAY_MS);+ continue;+ }+ if (!missingLogged) {+ Logger.info({stream: ACTIONS_STREAM}, 'Account action stream does not exist, checking again later');+ missingLogged = true;+ }+ }+ await pause(state, STREAM_RECHECK_MS);+ }+}++function actionsStreamReady(deps: AccountActionDeps, state: ConsumerState): Promise<void> {+ state.streamReady ??= waitForActionsStream(deps, state).finally(() => {+ state.streamReady = null;+ });+ return state.streamReady;+}+async function runActionPartition(deps: AccountActionDeps, partition: number, state: ConsumerState): Promise<void> {const retryDelayMs = deps.retryDelayMs ?? RETRY_DELAY_MS;while (!state.stopped) {+ await actionsStreamReady(deps, state);+ if (state.stopped) return;try {const consumer = await deps.js.consumers.get(ACTIONS_STREAM, effectsConsumer(partition));const info = await consumer.info(true);@@ -145,13 +191,19 @@ async function runActionPartition(deps: AccountActionDeps, partition: number, stif (state.stopped) return;Logger.debug({err: error, partition}, 'Account action consumer unavailable, retrying');}- if (!state.stopped) await new Promise((resolve) => setTimeout(resolve, retryDelayMs).unref?.());+ if (!state.stopped) await pause(state, retryDelayMs);}}export function startAccountActionConsumer(deps: AccountActionDeps): void {if (running) return;- const state: ConsumerState = {stopped: false, loops: [], tasks: []};+ const state: ConsumerState = {+ stopped: false,+ abort: new AbortController(),+ loops: [],+ tasks: [],+ streamReady: null,+ };running = state;for (let p = 0; p < ACTION_PARTITIONS; p++) {state.tasks.push(runActionPartition(deps, p, state));@@ -163,6 +215,7 @@ export async function stopAccountActionConsumer(): Promise<void> {if (!state) return;running = null;state.stopped = true;+ state.abort.abort();await Promise.allSettled(state.loops.map((messages) => messages.close()));await Promise.allSettled(state.tasks);}