import { isMaintenanceError, OpenGeniApiError } from "@opengeni/sdk"; import { type OpenGeniText } from "../messages/runtime"; /* * A deploy, failover or database restart makes the API answer 502/503/504 (or a * retryable 500) for a few seconds, or drops the connection outright. Reads * behind the new-chat composer retry those quietly before anything is shown; * the person keeps typing and never sees a raw "service unavailable" line. */ /** Backoff between attempts: about ten seconds in all before anything is shown. */ export const TRANSIENT_RETRY_DELAYS_MS: readonly number[] = [1_000, 2_000, 3_000, 4_000]; /** After the quiet retries give up, try once at this pace until Opengeni answers. */ export const TRANSIENT_RECONNECT_INTERVAL_MS = 3_000; /** The one line shown while Opengeni is briefly unreachable. */ export const OPENGENI_UPDATING_NOTICE = (t: OpenGeniText) => t("lib.transientRetry.opengeniIsUpdatingWeLl"); /** * An explicit action (Stop, Resume, Steer, a direct send) that failed only * because Opengeni is updating. It is not retried automatically, so it never * reads as "we'll reconnect": the person is told calmly to try again. */ export const OPENGENI_UPDATING_ACTION_NOTICE = (t: OpenGeniText) => t("lib.transientRetry.actionMayNotHaveGoneThrough"); const actionFailures = new WeakSet(); /** Record that `error` is the failure of an explicit action, not a background read or save. */ export function markActionFailure(error: T): T { if (typeof error === "object" && error !== null) actionFailures.add(error); return error; } /** True for a failure recorded with {@link markActionFailure}. */ export function isActionFailure(error: unknown): boolean { return typeof error === "object" && error !== null && actionFailures.has(error); } const NETWORK_FAILURE = /failed to fetch|fetch failed|networkerror|load failed|network request failed/iu; /** * True for a failure that says the service is briefly unreachable, not that * the request was wrong: a gateway or availability status, a 500 the API marks * retryable, or a request that never got a response. */ export function isTransientServiceFailure(error: unknown): boolean { if (isAbort(error)) return false; if (isMaintenanceError(error)) return true; if (error instanceof OpenGeniApiError) { // The API said this exact failure is not worth retrying. if (error.retryable === false) return false; if (error.status === 502 || error.status === 503 || error.status === 504) return true; if (error.status === 500) return error.retryable; // The SDK reports a mutation whose response never arrived as status 0. return error.status === 0 && error.code === "network_error"; } return error instanceof TypeError && NETWORK_FAILURE.test(error.message); } /** * How long an ordinary transient failure stays calm (shown as "updating" * rather than as an error). A normal deploy or failover ends well inside it; * a failure that outlasts it is reported as the error it is. The maintenance * marker is a planned update and stays calm for as long as it lasts. */ export const SERVICE_UPDATING_CALM_WINDOW_MS = 120_000; /** * True when `error` should read as "updating, reconnecting" rather than as a * failure: the maintenance marker, or a transient failure first seen at * `since` and not yet past the calm window at `now`. */ export function isCalmServiceFailure( error: unknown, since: number, now: number = Date.now(), ): boolean { if (isMaintenanceError(error)) return true; return isTransientServiceFailure(error) && now - since < SERVICE_UPDATING_CALM_WINDOW_MS; } export type RetryTransientOptions = { /** Stop waiting (and rethrow the last failure) once this returns false. */ shouldContinue?: () => boolean; signal?: AbortSignal; delaysMs?: readonly number[]; sleep?: (ms: number, signal?: AbortSignal) => Promise; }; /** * Run a read, retrying only transient service failures with backoff. Never use * this for a request whose repeat could apply twice: it is for reads and for * writes that are idempotent by construction. */ export async function retryTransient( operation: () => Promise, options: RetryTransientOptions = {}, ): Promise { const delays = options.delaysMs ?? TRANSIENT_RETRY_DELAYS_MS; const sleep = options.sleep ?? abortableSleep; for (let attempt = 0; ; attempt += 1) { try { return await operation(); } catch (error) { const delay = delays[attempt]; if ( delay === undefined || !isTransientServiceFailure(error) || options.signal?.aborted || options.shouldContinue?.() === false ) { throw error; } await sleep(delay, options.signal); if (options.signal?.aborted || options.shouldContinue?.() === false) throw error; } } } function abortableSleep(ms: number, signal?: AbortSignal): Promise { return new Promise((resolve) => { if (signal?.aborted) { resolve(); return; } const done = () => { clearTimeout(timer); signal?.removeEventListener("abort", done); resolve(); }; const timer = setTimeout(done, ms); signal?.addEventListener("abort", done, { once: true }); }); } function isAbort(error: unknown): boolean { return ( (typeof DOMException !== "undefined" && error instanceof DOMException && error.name === "AbortError") || (error instanceof Error && error.name === "AbortError") ); }