/** * The bearer resolver every provider's chat turn uses on the shared core: * load the leased connection's credential under the exact accepted turn, * refresh it proactively when stale, and share one in-flight refresh per * connection and refresh generation within the process (the database's * per-connection advisory lock serializes other replicas). * * The caller supplies the provider's view of a loaded credential, how a * snapshot is built from it, and the errors it raises; this module decides * when to refresh and which outcomes may be shared between turns. */ import { subscriptionCoreCredentialRefresher, type SubscriptionCoreAdapter, } from "@opengeni/subscriptions"; /** * When a credential is refreshed: this long before expiry, or `fallbackMs` * after the last refresh when the expiry is unknown. `null` for a * credential that never renews (no refresher, or a credential format whose * `autoRenews` is false): it is refreshed only once its known expiry passed * (or on a forced refresh after the provider refused it), and that refresh * marks it needs-relogin. */ export type SubscriptionCoreRefreshPolicy = { windowMs: number; fallbackMs: number } | null; /** The refresh policy the provider's adapter declares for one decoded credential. */ export function subscriptionCoreRefreshPolicy( adapter: Pick, "capabilitiesFor" | "credential" | "refresh">, credential: Credential, ): SubscriptionCoreRefreshPolicy { const refresher = subscriptionCoreCredentialRefresher(adapter, credential); return refresher === null ? null : { windowMs: refresher.windowMs, fallbackMs: refresher.fallbackMs }; } /** What every loaded credential view exposes to the resolver. */ export type SubscriptionCoreLoadedCredentialBase = { refreshGeneration: number; planType: string | null; expiresAt: Date | null; lastRefreshAt: Date | null; }; export type SubscriptionCoreRefreshedBase = { kind: "refreshed"; refreshGeneration: number; /** The plan the rotated credential reported; absent when the caller does not track it. */ planType?: string | null; }; /** A refresh outcome whose `refreshed` member carries a provider-specific payload. */ export type SubscriptionCoreRefreshOutcomeOf = | Refreshed /** Another refresh or credential writer already advanced the generation. */ | { kind: "superseded" } | { kind: "relogin"; message: string; marked: boolean } | { kind: "lease_lost" } | { kind: "not_visible" } | { kind: "refused" } | { kind: "error"; error: unknown }; export type SubscriptionCoreCredentialLoadOf = | { kind: "loaded"; credential: Loaded } | { kind: "lease_lost" } | { kind: "not_visible" } | { kind: "needs_relogin" } | { kind: "unavailable" }; export type SubscriptionCoreResolverInput< Loaded extends SubscriptionCoreLoadedCredentialBase, Refreshed extends SubscriptionCoreRefreshedBase, Snapshot, > = { /** * Separates flights of different callers (chat turns, connection-level * operations): only flights in the same namespace share an outcome. */ flightNamespace: string; connectionId: string; /** The exact turn lease (turn, holder, generation) this resolver serves. */ holderKey: string; /** * The refresh policy of a loaded credential * (`subscriptionCoreRefreshPolicy(adapter, credential)`): it depends on the * credential's format. */ policy(loaded: Loaded): SubscriptionCoreRefreshPolicy; load(): Promise>; /** The expiry embedded in the credential, used when the store records none. */ embeddedExpiry(loaded: Loaded): Date | null; refresh(loaded: Loaded): Promise>; snapshot(loaded: Loaded): Snapshot; refreshedSnapshot(outcome: Refreshed, loaded: Loaded): Snapshot; /** A persisted refresh reported a plan different from the recorded one. */ onPlanChanged?: (() => void) | undefined; errors: { /** The sign-in was revoked; only a new sign-in recovers. */ relogin(message: string | null): Error; /** The turn no longer holds its lease; dispatch must stop. */ leaseLost(): Error; /** The connection, or the turn's authority over it, is no longer usable. */ accessLost(): Error; }; }; type RefreshFlight = { /** The exact turn lease that started this provider refresh. */ holderKey: string; promise: Promise>; }; const inflight = new Map(); /** * Outcomes about the connection itself, which every turn waiting on the same * connection and generation may share. A lost lease, a refused authorization * or an invisible connection belongs to the turn that hit it only. */ function connectionLevelRefreshOutcome(outcome: { kind: string }): boolean { return ( outcome.kind === "refreshed" || outcome.kind === "superseded" || outcome.kind === "relogin" || outcome.kind === "error" ); } export function buildSubscriptionCoreCredentialResolver< Loaded extends SubscriptionCoreLoadedCredentialBase, Refreshed extends SubscriptionCoreRefreshedBase, Snapshot, >( input: SubscriptionCoreResolverInput, ): { getToken: () => Promise; /** Scoped read only: null when normal use would require credential renewal. */ getFreshToken: () => Promise; refresh: () => Promise; } { const { errors, holderKey } = input; /** * The newest credential generation this resolver handed out. A forced * refresh means "the credential I hold was refused"; one that loads a * generation newer than any its caller could hold (another caller's * rotation committed while it read) uses that credential instead of * rotating it again. */ let issuedGeneration: number | null = null; const issued = (generation: number) => { if (issuedGeneration === null || generation > issuedGeneration) issuedGeneration = generation; }; const load = async (): Promise => { const loaded = await input.load(); switch (loaded.kind) { case "loaded": return loaded.credential; case "lease_lost": throw errors.leaseLost(); case "needs_relogin": throw errors.relogin(null); default: throw errors.accessLost(); } }; const runOwnRefresh = (loaded: Loaded) => input.refresh(loaded); const sharedRefresh = async ( loaded: Loaded, ): Promise> => { const key = `${input.flightNamespace}:${input.connectionId}:${loaded.refreshGeneration}`; const existing = inflight.get(key); if (existing) { const outcome = (await existing.promise) as SubscriptionCoreRefreshOutcomeOf; // Another turn's lease or authorization outcome is not this turn's: // refresh under this turn's own lease instead. return existing.holderKey === holderKey || connectionLevelRefreshOutcome(outcome) ? outcome : await runOwnRefresh(loaded); } const flight: RefreshFlight = { holderKey, promise: Promise.resolve() as unknown as RefreshFlight["promise"], }; flight.promise = runOwnRefresh(loaded).finally(() => { if (inflight.get(key) === flight) inflight.delete(key); }); inflight.set(key, flight); return (await flight.promise) as SubscriptionCoreRefreshOutcomeOf; }; const doRefresh = async (loaded: Loaded): Promise => { const outcome = await sharedRefresh(loaded); switch (outcome.kind) { case "refreshed": if ( outcome.planType !== undefined && outcome.planType !== null && loaded.planType !== null && outcome.planType !== loaded.planType ) { try { input.onPlanChanged?.(); } catch { // A wake hint must never fail the request it rode on. } } issued(outcome.refreshGeneration); return input.refreshedSnapshot(outcome as Refreshed, loaded); case "superseded": { const current = await load(); issued(current.refreshGeneration); return input.snapshot(current); } case "relogin": throw errors.relogin(outcome.message); case "lease_lost": throw errors.leaseLost(); case "error": throw outcome.error; default: throw errors.accessLost(); } }; const stale = (loaded: Loaded): boolean => { const expiry = loaded.expiresAt ?? input.embeddedExpiry(loaded); const policy = input.policy(loaded); return policy === null ? // A credential that never renews is used until its known expiry. expiry !== null && expiry.getTime() <= Date.now() : expiry ? expiry.getTime() <= Date.now() + policy.windowMs : loaded.lastRefreshAt ? loaded.lastRefreshAt.getTime() < Date.now() - policy.fallbackMs : true; }; const resolve = async (force: boolean): Promise => { // Captured before the read: what the caller could hold when it asked. const held = issuedGeneration; const loaded = await load(); const rotatedSinceHeld = held !== null && loaded.refreshGeneration > held; if ((force && !rotatedSinceHeld) || stale(loaded)) return await doRefresh(loaded); issued(loaded.refreshGeneration); return input.snapshot(loaded); }; return { getToken: () => resolve(false), getFreshToken: async () => { const loaded = await load(); if (stale(loaded)) return null; issued(loaded.refreshGeneration); return input.snapshot(loaded); }, refresh: () => resolve(true), }; }