A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): hand foreground sessions to the account engine
Hampus05170252b299
diff --git a/fluxer_app/src/features/account_engine/state/EngineForegroundHandoff.ts b/fluxer_app/src/features/account_engine/state/EngineForegroundHandoff.tsnew file mode 100644index 000000000..6b840e232--- /dev/null+++ b/fluxer_app/src/features/account_engine/state/EngineForegroundHandoff.ts@@ -0,0 +1,362 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {SNAPSHOT_SCHEMA_EPOCH} from '@app/features/gateway/snapshot/SnapshotEntities';+import type {StateSnapshotCapture} from '@app/features/gateway/snapshot/SnapshotTypes';+import type {GatewayHandoffSeed, GatewayResumeSeed} from '@app/features/gateway/transport/GatewaySocket';+import {Logger} from '@app/features/platform/utils/AppLogger';+import type {+ AccountEngineDemotion,+ AccountEnginePromotion,+ AccountEngineRequestMethod,+ AccountEngineRequests,+ AccountEngineResumeSession,+} from '@fluxer/desktop_ipc/src/AccountEngineContract';++const logger = new Logger('EngineForegroundHandoff');++const BOOT_ENGINE_WAIT_MS = 5_000;+const TIMED_OUT: unique symbol = Symbol('timed-out');++function within<T>(promise: Promise<T>, timeoutMs: number): Promise<T | typeof TIMED_OUT> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<typeof TIMED_OUT>((resolve) => {+ timer = setTimeout(() => resolve(TIMED_OUT), timeoutMs);+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++interface EngineHandoffEngine {+ readonly available: boolean;+ request<M extends AccountEngineRequestMethod>(+ method: M,+ params: AccountEngineRequests[M]['params'],+ ): Promise<AccountEngineRequests[M]['result']>;+}++interface EngineHandoffForeground {+ readonly foregroundAccountKey: string | null;+ beginForegroundDemotionHandover(accountKey: string): boolean;+ finishForegroundDemotionHandover(accountKey: string): Promise<GatewayHandoffSeed | null>;+ rollbackForegroundDemotionHandover(accountKey: string): Promise<void>;+ retireForAccountSwitch(): void;+ preparePromotedForegroundReplay(): void;+ startResumedSession(accountKey: string, seed: GatewayResumeSeed): Promise<boolean>;+}++interface EngineHandoffSnapshots {+ flush(accountKey: string): Promise<void>;+ captureDemotionSnapshot(accountKey: string): StateSnapshotCapture | null;+ adoptPromotedSnapshot(accountKey: string, selfUserId: string, capture: StateSnapshotCapture): boolean;+ evict(accountKey: string): void;+}++interface EngineHandoffAccount {+ readonly userId: string;+ readonly gatewayEndpoint: string | null;+}++export interface EngineHandoffHost {+ readonly engine: EngineHandoffEngine;+ readonly foreground: EngineHandoffForeground;+ readonly snapshots: EngineHandoffSnapshots;+ getAccount(accountKey: string): EngineHandoffAccount | null;+ isCurrentAccount(accountKey: string): boolean;+ captureMentionCounts(): ReadonlyMap<string, number>;+ hydrate(accountKey: string, mentionCounts: ReadonlyMap<string, number>): Promise<void>;+ whenForegroundLive(accountKey: string): Promise<boolean | null>;+ whenEngineConfigured(): Promise<void>;+}++type ForegroundDemotionRetirementReason = 'no_foreground' | 'handover_unavailable' | 'engine_unavailable';++export type ForegroundDemotionOutcome =+ | {+ readonly mode: 'handed_off';+ readonly accountKey: string;+ readonly session: AccountEngineResumeSession | null;+ readonly captured: boolean;+ }+ | {+ readonly mode: 'retired';+ readonly accountKey: string | null;+ readonly reason: ForegroundDemotionRetirementReason;+ };++export type ForegroundPromotionMode = 'resume' | 'hydrated' | 'cold';++interface ActivePromotion {+ readonly accountKey: string;+ readonly requested: boolean;+ readonly request: Promise<AccountEnginePromotion | null>;+ readonly demotionAccountKey: string | null;+}++export class EngineForegroundHandoff {+ private active: ActivePromotion | null = null;+ private readonly awaitingLive = new Set<string>();++ constructor(private readonly host: EngineHandoffHost) {}++ beginPromotion(accountKey: string): void {+ if (this.active !== null) {+ throw new Error(`Foreground promotion is already active for ${this.active.accountKey}`);+ }+ const previousAccountKey = this.host.foreground.foregroundAccountKey;+ const demotionAccountKey =+ previousAccountKey !== null &&+ previousAccountKey !== accountKey &&+ this.host.foreground.beginForegroundDemotionHandover(previousAccountKey)+ ? previousAccountKey+ : null;+ const requested = this.host.engine.available;+ this.active = {+ accountKey,+ requested,+ request: requested ? this.requestPromotion(accountKey) : Promise.resolve(null),+ demotionAccountKey,+ };+ }++ async completePromotion(accountKey: string): Promise<ForegroundPromotionMode> {+ const active = this.requireActive(accountKey);+ try {+ const promotion = await active.request;+ return await this.adoptAndSettle(accountKey, promotion, active.requested);+ } finally {+ if (this.active === active) {+ this.active = null;+ }+ if (active.demotionAccountKey !== null) {+ await this.host.foreground.rollbackForegroundDemotionHandover(active.demotionAccountKey);+ }+ }+ }++ async rollbackPromotion(accountKey: string): Promise<void> {+ const active = this.active;+ if (active === null || active.accountKey !== accountKey) {+ return;+ }+ this.active = null;+ try {+ await active.request;+ if (active.requested) {+ this.send('abortPromotion', {accountKey});+ }+ } finally {+ if (active.demotionAccountKey !== null) {+ await this.host.foreground.rollbackForegroundDemotionHandover(active.demotionAccountKey);+ }+ }+ }++ async demoteForeground(): Promise<ForegroundDemotionOutcome> {+ const foreground = this.host.foreground;+ const accountKey = foreground.foregroundAccountKey;+ if (accountKey === null) {+ foreground.retireForAccountSwitch();+ return {mode: 'retired', accountKey: null, reason: 'no_foreground'};+ }+ if (!this.host.engine.available) {+ this.host.snapshots.evict(accountKey);+ foreground.retireForAccountSwitch();+ return {mode: 'retired', accountKey, reason: 'engine_unavailable'};+ }+ const handoverActive =+ this.active?.demotionAccountKey === accountKey || foreground.beginForegroundDemotionHandover(accountKey);+ try {+ const seed = handoverActive ? await foreground.finishForegroundDemotionHandover(accountKey) : null;+ const capture = await this.captureDemotion(accountKey);+ const account = this.host.getAccount(accountKey);+ const session =+ seed !== null &&+ capture !== null &&+ capture.cursor.sessionId === seed.sessionId &&+ account?.gatewayEndpoint != null+ ? {sessionId: seed.sessionId, sequence: seed.sequence, gatewayUrl: account.gatewayEndpoint}+ : null;+ const demotion: AccountEngineDemotion = {+ accountKey,+ session,+ release: session !== null && seed !== null ? seed.release : null,+ capture,+ mentionCounts: capture === null ? null : Object.fromEntries(this.host.captureMentionCounts()),+ };+ this.host.snapshots.evict(accountKey);+ foreground.retireForAccountSwitch();+ if (account !== null) {+ this.settleLive(accountKey);+ this.send('demote', demotion);+ }+ if (!handoverActive) {+ return {mode: 'retired', accountKey, reason: 'handover_unavailable'};+ }+ return {mode: 'handed_off', accountKey, session, captured: capture !== null};+ } catch (error) {+ this.host.snapshots.evict(accountKey);+ foreground.retireForAccountSwitch();+ throw error;+ }+ }++ async bootForeground(accountKey: string): Promise<ForegroundPromotionMode> {+ if (!this.host.engine.available) {+ return 'cold';+ }+ const configured = await within(this.host.whenEngineConfigured(), BOOT_ENGINE_WAIT_MS);+ if (configured === TIMED_OUT) {+ logger.warn('The account engine did not answer in time, starting the foreground session cold', {accountKey});+ if (this.host.isCurrentAccount(accountKey)) {+ this.send('claimForeground', {accountKey});+ }+ return 'cold';+ }+ if (!this.canBoot(accountKey)) {+ return 'cold';+ }+ const request = this.requestPromotion(accountKey);+ const promotion = await within(request, BOOT_ENGINE_WAIT_MS);+ if (promotion === TIMED_OUT) {+ logger.warn('The account engine did not hand over in time, starting the foreground session cold', {accountKey});+ void request.then((late) => this.settleAbandonedBoot(accountKey, late));+ return 'cold';+ }+ if (!this.canBoot(accountKey)) {+ this.settleAbandonedBoot(accountKey, promotion);+ return 'cold';+ }+ return await this.adoptAndSettle(accountKey, promotion, true);+ }++ private settleAbandonedBoot(accountKey: string, promotion: AccountEnginePromotion | null): void {+ if (this.host.isCurrentAccount(accountKey)) {+ this.settleCold(accountKey, promotion);+ return;+ }+ if (promotion !== null) {+ this.send('abortPromotion', {accountKey});+ }+ }++ private canBoot(accountKey: string): boolean {+ return (+ this.active === null &&+ this.host.isCurrentAccount(accountKey) &&+ this.host.foreground.foregroundAccountKey === null+ );+ }++ private async adoptAndSettle(+ accountKey: string,+ promotion: AccountEnginePromotion | null,+ requested: boolean,+ ): Promise<ForegroundPromotionMode> {+ let mode: ForegroundPromotionMode = 'cold';+ try {+ mode = await this.adoptPromotion(accountKey, promotion);+ return mode;+ } finally {+ if (mode !== 'resume' && requested) {+ this.settleCold(accountKey, promotion);+ }+ }+ }++ private async adoptPromotion(+ accountKey: string,+ promotion: AccountEnginePromotion | null,+ ): Promise<ForegroundPromotionMode> {+ const capture = promotion?.capture ?? null;+ const account = this.host.getAccount(accountKey);+ if (+ promotion === null ||+ capture === null ||+ account === null ||+ !this.host.engine.available ||+ capture.cursor.schemaEpoch !== SNAPSHOT_SCHEMA_EPOCH+ ) {+ return 'cold';+ }+ try {+ this.host.foreground.preparePromotedForegroundReplay();+ if (!this.host.snapshots.adoptPromotedSnapshot(accountKey, account.userId, capture)) {+ return 'cold';+ }+ await this.host.hydrate(accountKey, new Map(Object.entries(promotion.mentionCounts)));+ } catch (error) {+ logger.warn('Falling back to a cold foreground session after promotion hydration failed', {+ accountKey,+ error,+ });+ this.host.snapshots.evict(accountKey);+ return 'cold';+ }+ const session = promotion.session;+ if (session === null || session.sessionId !== capture.cursor.sessionId) {+ return 'hydrated';+ }+ const started = await this.host.foreground.startResumedSession(accountKey, {+ sessionId: session.sessionId,+ sequence: session.sequence,+ });+ if (!started) {+ return 'hydrated';+ }+ this.awaitingLive.add(accountKey);+ const settle = () => this.settleLive(accountKey);+ void this.host.whenForegroundLive(accountKey).then(settle, settle);+ return 'resume';+ }++ private async captureDemotion(accountKey: string): Promise<StateSnapshotCapture | null> {+ try {+ await this.host.snapshots.flush(accountKey);+ } catch (error) {+ logger.warn('Dropping an invalid snapshot on demotion', {accountKey, error});+ return null;+ }+ const capture = this.host.snapshots.captureDemotionSnapshot(accountKey);+ return capture !== null && capture.cursor.schemaEpoch === SNAPSHOT_SCHEMA_EPOCH ? capture : null;+ }++ private settleLive(accountKey: string): void {+ if (!this.awaitingLive.delete(accountKey)) {+ return;+ }+ this.send('completePromotion', {accountKey});+ }++ private settleCold(accountKey: string, promotion: AccountEnginePromotion | null): void {+ if (promotion === null) {+ this.send('claimForeground', {accountKey});+ return;+ }+ this.send('completePromotion', {accountKey});+ }++ private requestPromotion(accountKey: string): Promise<AccountEnginePromotion | null> {+ return this.host.engine.request('beginPromotion', {accountKey}).catch((error: unknown) => {+ logger.warn('The account engine could not hand over the account, switching cold', {accountKey, error});+ return null;+ });+ }++ private send<M extends AccountEngineRequestMethod>(method: M, params: AccountEngineRequests[M]['params']): void {+ if (!this.host.engine.available) {+ return;+ }+ void this.host.engine.request(method, params).catch((error: unknown) => {+ logger.warn(`Account engine ${method} failed`, {error});+ });+ }++ private requireActive(accountKey: string): ActivePromotion {+ const active = this.active;+ if (active === null || active.accountKey !== accountKey) {+ throw new Error(+ `Foreground promotion for ${accountKey} is not active (${active?.accountKey ?? 'none'} is active)`,+ );+ }+ return active;+ }+}diff --git a/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.ts b/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.tsindex 3c44e1f5f..92df5d1a1 100644--- a/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.ts+++ b/fluxer_app/src/features/gateway/transport/ForegroundDemotionHandover.ts@@ -3,6 +3,7 @@import {exceedsDispatchBufferCapacity} from '@app/features/gateway/transport/GatewayDispatchBufferBounds';import {type GatewayDispatchDelivery,+ type GatewayHandoffSeed,type GatewaySocket,MAX_GATEWAY_AUTH_TOKEN_LENGTH,} from '@app/features/gateway/transport/GatewaySocket';@@ -10,6 +11,8 @@ import {Logger} from '@app/features/platform/utils/AppLogger';const logger = new Logger('ForegroundDemotionHandover');+export const GATEWAY_HANDOFF_CLOSE_CODE = 4901;+interface ActiveForegroundDemotion {readonly accountKey: string;readonly expectedUserId: string;@@ -36,7 +39,7 @@ export interface ForegroundDemotionRestore {readonly canRestore: boolean;}-export interface ForegroundDemotionRetire {+interface ForegroundDemotionRetire {readonly outcome: 'retire';}@@ -107,22 +110,22 @@ export class ForegroundDemotionHandover {});}- async consume(accountKey: string): Promise<boolean> {+ async finish(accountKey: string): Promise<GatewayHandoffSeed | null> {const active = this.activeForAccount(accountKey);if (active === null) {- return false;+ return null;}+ const seed = active.socket.closeForHandoff(GATEWAY_HANDOFF_CLOSE_CODE, 'handoff');try {await this.persistLatestRetiringToken(active);} catch (error) {- active.socket.reset(true);this.release(active);logger.error('Failed to persist a foreground gateway token rotation during demotion', error);- return false;+ return null;}- if (!this.canContinue(active)) {+ if (active.overflowed) {this.release(active);- return false;+ return null;}for (const delivery of active.deliveries) {if (!active.socket.isDispatchActive(delivery.receipt)) {@@ -131,14 +134,14 @@ export class ForegroundDemotionHandover {try {this.host.applySnapshotDispatch(active.accountKey, active.expectedUserId, delivery);} catch (error) {- active.socket.failDispatchProcessing(delivery.receipt, error);+ logger.warn('Failed to apply a buffered dispatch to the demoted snapshot', error);this.release(active);- return false;+ return null;}active.socket.completeDispatchProcessing(delivery.receipt);}this.release(active);- return this.canContinue(active);+ return seed;}async rollback(accountKey: string): Promise<ForegroundDemotionRollback | null> {diff --git a/fluxer_app/src/features/gateway/transport/GatewaySessionPool.ts b/fluxer_app/src/features/gateway/transport/GatewaySessionPool.tsindex ef1acfc3f..510dc9804 100644--- a/fluxer_app/src/features/gateway/transport/GatewaySessionPool.ts+++ b/fluxer_app/src/features/gateway/transport/GatewaySessionPool.ts@@ -1,17 +1,23 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import AccountEngine from '@app/features/account_engine/state/AccountEngine';+import {+ EngineForegroundHandoff,+ type ForegroundDemotionOutcome,+} from '@app/features/account_engine/state/EngineForegroundHandoff';import Initialization from '@app/features/app/state/Initialization';-import {BackgroundGatewaySessionManager} from '@app/features/gateway/transport/BackgroundGatewaySessionManager';+import {+ captureForegroundMentionCounts,+ hydrateStoresFromSnapshotScope,+} from '@app/features/gateway/snapshot/SnapshotHydration';+import SnapshotSync from '@app/features/gateway/snapshot/SnapshotSync';import {installDeferredReaction} from '@app/features/gateway/transport/DeferredReaction';import {ForegroundGatewayConnectionRecoverableError,ForegroundGatewayRecoveryExhaustedError,} from '@app/features/gateway/transport/ForegroundGatewayConnectionFailure';import {- type ForegroundDemotionOutcome,- ForegroundGatewayHandoff,-} from '@app/features/gateway/transport/ForegroundGatewayHandoff';-import {+ GatewaySessionStartStatus,PooledGatewayConnection,selectForegroundActivationGuildId,} from '@app/features/gateway/transport/PooledGatewayConnection';@@ -33,8 +39,7 @@ type ForegroundRecoveryState =class GatewaySessionPool {readonly foregroundConnection = new PooledGatewayConnection();- private readonly backgroundSessions = new BackgroundGatewaySessionManager();- private readonly handoff = new ForegroundGatewayHandoff(this.foregroundConnection, this.backgroundSessions);+ private readonly handoff: EngineForegroundHandoff;private started = false;private disposers: Array<() => void> = [];private foregroundRecoveryRevision = 0;@@ -42,6 +47,42 @@ class GatewaySessionPool {private foregroundRecovery: ForegroundRecoveryState = {kind: 'idle'};private failedRecoveryDisposer: (() => void) | null = null;+ constructor() {+ const connection = this.foregroundConnection;+ this.handoff = new EngineForegroundHandoff({+ engine: AccountEngine,+ foreground: {+ get foregroundAccountKey() {+ return connection.foregroundAccountKey;+ },+ beginForegroundDemotionHandover: (accountKey) =>+ this.foregroundConnection.beginForegroundDemotionHandover(accountKey),+ finishForegroundDemotionHandover: (accountKey) =>+ this.foregroundConnection.finishForegroundDemotionHandover(accountKey),+ rollbackForegroundDemotionHandover: (accountKey) =>+ this.foregroundConnection.rollbackForegroundDemotionHandover(accountKey),+ retireForAccountSwitch: () => this.foregroundConnection.retireForAccountSwitch(),+ preparePromotedForegroundReplay: () => this.foregroundConnection.preparePromotedForegroundReplay(),+ startResumedSession: async (accountKey, seed) => {+ const result = await this.foregroundConnection.startSession(accountKey, {resume: seed});+ return result.status === GatewaySessionStartStatus.STARTED;+ },+ },+ snapshots: SnapshotSync,+ getAccount: (accountKey) => {+ const account = SessionManager.getAccount(accountKey);+ return account === null+ ? null+ : {userId: account.userId, gatewayEndpoint: account.instance?.gatewayEndpoint ?? null};+ },+ isCurrentAccount: (accountKey) => SessionManager.currentAccountKey === accountKey,+ captureMentionCounts: () => captureForegroundMentionCounts(),+ hydrate: (accountKey, mentionCounts) => hydrateStoresFromSnapshotScope(accountKey, mentionCounts),+ whenForegroundLive: (accountKey) => this.whenForegroundLive(accountKey),+ whenEngineConfigured: () => AccountEngine.whenConfigured(),+ });+ }+async retireForAccountTransition(reason: AccountScopedWorkTransitionReason): Promise<void> {if (reason === AccountScopedWorkTransitionReason.ACCOUNT_SWITCH) {await this.demoteForegroundForAccountSwitch();@@ -82,7 +123,6 @@ class GatewaySessionPool {),),);- this.backgroundSessions.start();}startRestoredSession(): void {@@ -90,7 +130,21 @@ class GatewaySessionPool {if (accountKey === null) {return;}- this.startForegroundRecovery(accountKey);+ if (!AccountEngine.available) {+ this.startForegroundRecovery(accountKey);+ return;+ }+ this.start();+ void this.handoff+ .bootForeground(accountKey)+ .catch((error: unknown) => {+ logger.warn('Failed to restore the foreground account from the account engine', {accountKey, error});+ })+ .finally(() => {+ if (this.started && SessionManager.currentAccountKey === accountKey) {+ this.startForegroundRecovery(accountKey);+ }+ });}recoverForegroundSession(accountKey: string): void {@@ -110,7 +164,6 @@ class GatewaySessionPool {for (const dispose of disposers) {dispose();}- this.backgroundSessions.shutdown();}private startForegroundRecovery(accountKey: string): void {@@ -257,29 +310,44 @@ class GatewaySessionPool {await this.foregroundConnection.startSessionAndWaitForReady(targetAccountKey);}- beginPromote(accountKey: string): Promise<void> {+ async beginPromote(accountKey: string): Promise<void> {this.stopForegroundRecovery();- return this.handoff.beginPromotion(accountKey);+ this.handoff.beginPromotion(accountKey);}- completePromote(accountKey: string): Promise<void> {- return this.handoff.completePromotion(accountKey);+ async completePromote(accountKey: string): Promise<void> {+ const startedAtMs = Date.now();+ const mode = await this.handoff.completePromotion(accountKey);+ logger.info('Foreground promotion completed', {accountKey, mode, elapsedMs: Date.now() - startedAtMs});}rollbackPromote(accountKey: string): Promise<void> {return this.handoff.rollbackPromotion(accountKey);}- demoteForegroundForAccountSwitch(): Promise<ForegroundDemotionOutcome> {- return this.handoff.demoteForegroundForAccountSwitch();- }-- get isBackgroundBootstrapped(): boolean {- return this.backgroundSessions.isBootstrapped;+ async demoteForegroundForAccountSwitch(): Promise<ForegroundDemotionOutcome> {+ const startedAtMs = Date.now();+ const outcome = await this.handoff.demoteForeground();+ logger.info('Foreground demotion completed', {...outcome, elapsedMs: Date.now() - startedAtMs});+ return outcome;}- get backgroundConnectionCount(): number {- return this.backgroundSessions.connectionCount;+ private whenForegroundLive(accountKey: string): Promise<boolean | null> {+ const socket = this.foregroundConnection.foregroundSocketForAccount(accountKey);+ if (socket === null) {+ return Promise.resolve(null);+ }+ return new Promise((resolve) => {+ const settle = (resumed: boolean): void => {+ socket.off('resumed', onResumed);+ socket.off('ready', onReady);+ resolve(resumed);+ };+ const onResumed = (): void => settle(true);+ const onReady = (): void => settle(false);+ socket.on('resumed', onResumed);+ socket.on('ready', onReady);+ });}private syncForegroundPresence(): void {