A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(app): remove the renderer foreground promotion handoff
Hampus4adf3a39e1f5
diff --git a/fluxer_app/src/features/gateway/transport/ForegroundGatewayHandoff.test.ts b/fluxer_app/src/features/gateway/transport/ForegroundGatewayHandoff.test.tsdeleted file mode 100644index 70d7b344e..000000000--- a/fluxer_app/src/features/gateway/transport/ForegroundGatewayHandoff.test.ts+++ /dev/null@@ -1,398 +0,0 @@-// @vitest-environment happy-dom-// 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 {BackgroundGatewaySessionManager} from '@app/features/gateway/transport/BackgroundGatewaySessionManager';-import {- type ForegroundDemotionRetirementReason,- ForegroundGatewayHandoff,-} from '@app/features/gateway/transport/ForegroundGatewayHandoff';-import type {WarmForegroundCandidate} from '@app/features/gateway/transport/ForegroundPromoteCoordinator';-import type {GatewaySocket, GatewaySocketProperties} from '@app/features/gateway/transport/GatewaySocket';-import type {PooledGatewayConnection} from '@app/features/gateway/transport/PooledGatewayConnection';-import type {Account} from '@app/features/platform/state/AuthSession';-import {beforeEach, describe, expect, test, vi} from 'vitest';--const mocks = vi.hoisted(() => ({- accounts: new Map<string, unknown>(),- events: [] as Array<string>,- adoptSocketError: null as Error | null,- snapshotAvailable: true,-}));--vi.mock('@lingui/core/macro', () => {- const descriptor = (value: unknown): unknown => (typeof value === 'string' ? {message: value} : value);- return {msg: descriptor, t: descriptor, plural: () => '', select: () => '', selectOrdinal: () => ''};-});--vi.mock('@lingui/react/macro', () => ({- Trans: () => null,- useLingui: () => ({i18n: {_: (descriptor: {message?: string}) => descriptor.message ?? '', locale: 'en'}}),-}));--vi.mock('@app/features/channel/state/Channels', () => ({default: {getChannel: () => undefined}}));--vi.mock('@app/features/navigation/state/Navigation', () => ({default: {channelId: null}}));--vi.mock('@app/features/messaging/state/AttachmentUrlRefresher', () => ({default: {reset: vi.fn()}}));--vi.mock('@app/features/platform/state/AuthSession', () => ({- default: {getAccount: (accountKey: string) => mocks.accounts.get(accountKey) ?? null},-}));--vi.mock('@app/features/gateway/snapshot/SnapshotHydration', () => ({- captureForegroundMentionCounts: () => new Map(),- hydrateStoresFromSnapshotScope: () => Promise.resolve(),-}));--vi.mock('@app/features/gateway/snapshot/SnapshotSync', () => ({- default: {- flush: (storageKey: string) => {- mocks.events.push(`snapshot:flush:${storageKey}`);- return Promise.resolve();- },- demoteForeground: (storageKey: string) => {- mocks.events.push(`snapshot:demote:${storageKey}`);- return mocks.snapshotAvailable ? demotionCapture() : null;- },- captureDemotionSnapshot: () => null,- prepareForegroundPromotion: () => false,- commitForegroundPromotion: () => false,- abortForegroundPromotion: (storageKey: string) => {- mocks.events.push(`snapshot:abort:${storageKey}`);- },- finalizeForegroundPromotion: () => undefined,- },-}));--vi.mock('@app/features/gateway/transport/BackgroundGatewaySession', () => ({- BackgroundGatewaySession: class BackgroundGatewaySession {- constructor(config: {account: Account}) {- mocks.events.push(`session:new:${config.account.storageKey}`);- }-- adoptSocket(): void {- mocks.events.push('session:adopt');- if (mocks.adoptSocketError !== null) {- throw mocks.adoptSocketError;- }- }-- stop(): void {- mocks.events.push('session:stop');- }- },-}));--const ACCOUNT_KEY = 'secondary.test::200';-const TARGET_KEY = 'primary.test::100';-const SESSION_ID = 'session-200';--const PROPERTIES: GatewaySocketProperties = {- os: 'macos',- browser: 'Fluxer Client',- device: 'desktop',- locale: 'en-US',- user_agent: 'test',- browser_version: '1',- os_version: '1',- build_version: '1',-};--function retainedAccount(): Account {- return {- storageKey: ACCOUNT_KEY,- userId: '200',- token: 'token-200',- lastActive: 10,- isValid: true,- instance: {- gatewayEndpoint: 'wss://gateway.secondary.test',- features: {max_background_gateway_connections: 4},- } as Account['instance'],- };-}--function demotionCapture(): StateSnapshotCapture {- return {entries: {}, cursor: {sessionId: SESSION_ID, schemaEpoch: SNAPSHOT_SCHEMA_EPOCH, updatedAt: 0}};-}--class FakeGatewaySocket {- sessionId: string | null = SESSION_ID;- connected = true;- readonly resets: Array<boolean> = [];-- getSessionId(): string | null {- return this.sessionId;- }-- isConnected(): boolean {- return this.connected;- }-- reset(shouldReconnect: boolean): void {- this.resets.push(shouldReconnect);- }-}--class FakeForegroundConnection {- foregroundAccountKey: string | null = ACCOUNT_KEY;- handoverAvailable = true;- consumeResult = true;- socket: FakeGatewaySocket | null = new FakeGatewaySocket();-- beginForegroundDemotionHandover(accountKey: string): boolean {- mocks.events.push(`foreground:begin-handover:${accountKey}`);- return this.handoverAvailable;- }-- consumeForegroundDemotionHandover(accountKey: string): Promise<boolean> {- mocks.events.push(`foreground:consume-handover:${accountKey}`);- return Promise.resolve(this.consumeResult);- }-- rollbackForegroundDemotionHandover(accountKey: string): Promise<void> {- mocks.events.push(`foreground:rollback-handover:${accountKey}`);- return Promise.resolve();- }-- foregroundSocketForAccount(): GatewaySocket | null {- return this.socket as unknown as GatewaySocket | null;- }-- detachForegroundSocket(): GatewaySocket | null {- mocks.events.push('foreground:detach');- return this.socket as unknown as GatewaySocket | null;- }-- retireForAccountSwitch(): void {- mocks.events.push('foreground:retire');- this.foregroundAccountKey = null;- }-}--class FakeBackgroundSessionManager {- transportAvailable = true;- cachedProperties: GatewaySocketProperties | null = PROPERTIES;- readonly protectedAccountKeys: Array<string> = [];- readonly adoptedAccountKeys: Array<string> = [];- readonly candidates = new Map<string, WarmForegroundCandidate>();-- isTransportAvailable(): boolean {- return this.transportAvailable;- }-- preloadProperties(): Promise<GatewaySocketProperties | null> {- return Promise.resolve(this.cachedProperties);- }-- protect(accountKey: string): void {- mocks.events.push(`background:protect:${accountKey}`);- this.protectedAccountKeys.push(accountKey);- }-- unprotect(accountKey: string): void {- mocks.events.push(`background:unprotect:${accountKey}`);- const index = this.protectedAccountKeys.indexOf(accountKey);- if (index >= 0) {- this.protectedAccountKeys.splice(index, 1);- }- }-- sync(): void {}-- invalidateSync(): void {}-- find(accountKey: string): WarmForegroundCandidate | null {- return this.candidates.get(accountKey) ?? null;- }-- adopt(accountKey: string): void {- mocks.events.push(`background:adopt:${accountKey}`);- this.adoptedAccountKeys.push(accountKey);- }-- stop(accountKey: string): void {- mocks.events.push(`background:stop:${accountKey}`);- }-}--interface Harness {- foreground: FakeForegroundConnection;- background: FakeBackgroundSessionManager;- handoff: ForegroundGatewayHandoff;-}--function createHarness(): Harness {- const foreground = new FakeForegroundConnection();- const background = new FakeBackgroundSessionManager();- const handoff = new ForegroundGatewayHandoff(- foreground as unknown as PooledGatewayConnection,- background as unknown as BackgroundGatewaySessionManager,- );- return {foreground, background, handoff};-}--beforeEach(() => {- mocks.events.length = 0;- mocks.adoptSocketError = null;- mocks.snapshotAvailable = true;- mocks.accounts.clear();- mocks.accounts.set(ACCOUNT_KEY, retainedAccount());-});--describe('foreground gateway demotion retirement', () => {- const cases: Array<{reason: ForegroundDemotionRetirementReason; arrange: (harness: Harness) => void}> = [- {- reason: 'no_foreground',- arrange: ({foreground}) => {- foreground.foregroundAccountKey = null;- },- },- {- reason: 'handover_unavailable',- arrange: ({foreground}) => {- foreground.handoverAvailable = false;- },- },- {- reason: 'socket_lost',- arrange: ({foreground}) => {- foreground.consumeResult = false;- },- },- {- reason: 'account_unavailable',- arrange: () => {- mocks.accounts.delete(ACCOUNT_KEY);- },- },- {- reason: 'transport_disabled',- arrange: ({background}) => {- background.transportAvailable = false;- },- },- {- reason: 'capacity_disabled',- arrange: () => {- const account = retainedAccount();- mocks.accounts.set(ACCOUNT_KEY, {- ...account,- instance: {- ...account.instance,- features: {max_background_gateway_connections: 0},- },- });- },- },- {- reason: 'endpoint_unavailable',- arrange: () => {- const account = retainedAccount();- mocks.accounts.set(ACCOUNT_KEY, {...account, instance: {...account.instance, gatewayEndpoint: ''}});- },- },- {- reason: 'metadata_unavailable',- arrange: ({background}) => {- background.cachedProperties = null;- },- },- {- reason: 'snapshot_unavailable',- arrange: () => {- mocks.snapshotAvailable = false;- },- },- ];-- for (const {reason, arrange} of cases) {- test(`a demotion retires the foreground gateway with ${reason}`, async () => {- const harness = createHarness();- arrange(harness);-- const outcome = await harness.handoff.demoteForegroundForAccountSwitch();-- expect(outcome).toEqual({- mode: 'retired',- accountKey: reason === 'no_foreground' ? null : ACCOUNT_KEY,- reason,- });- expect(mocks.events).toContain('foreground:retire');- expect(harness.background.adoptedAccountKeys).toEqual([]);- expect(mocks.events).not.toContain('session:adopt');- });- }-- test('a live foreground socket that lost its session id is retired rather than retained', async () => {- const harness = createHarness();- (harness.foreground.socket as FakeGatewaySocket).sessionId = null;-- const outcome = await harness.handoff.demoteForegroundForAccountSwitch();-- expect(outcome).toEqual({mode: 'retired', accountKey: ACCOUNT_KEY, reason: 'socket_lost'});- expect(harness.background.adoptedAccountKeys).toEqual([]);- });-- test('a demotion that clears every gate retains the socket as a background session', async () => {- const harness = createHarness();-- const outcome = await harness.handoff.demoteForegroundForAccountSwitch();-- expect(outcome).toEqual({mode: 'retained', accountKey: ACCOUNT_KEY, sessionId: SESSION_ID});- expect(harness.background.adoptedAccountKeys).toEqual([ACCOUNT_KEY]);- expect(mocks.events).toContain('foreground:retire');- });-});--describe('foreground gateway demotion adoption failure', () => {- test('a background session that refuses the socket is stopped and the socket discarded once', async () => {- const harness = createHarness();- mocks.adoptSocketError = new Error('adoption rejected');-- await expect(harness.handoff.demoteForegroundForAccountSwitch()).rejects.toThrow(- `Failed to retain foreground gateway ${ACCOUNT_KEY}`,- );-- expect(mocks.events.filter((event) => event === 'session:stop')).toEqual(['session:stop']);- expect((harness.foreground.socket as FakeGatewaySocket).resets).toEqual([false]);- expect(harness.background.adoptedAccountKeys).toEqual([]);- expect(mocks.events).toContain('foreground:retire');- });-});--describe('foreground gateway promotion rollback', () => {- function throwingCandidate(): WarmForegroundCandidate {- return {- isBackgroundConnectionReady: true,- beginBackgroundDispatchHandover: () => {- throw new Error('handover refused');- },- endBackgroundDispatchHandover: () => undefined,- detachBackgroundSocket: () => null,- waitForBackgroundConnectionReady: () => Promise.resolve(true),- waitForBackgroundDispatchIdle: () => Promise.resolve(),- };- }-- test('a promotion that fails to begin rolls the demotion back and releases both accounts', async () => {- const harness = createHarness();- harness.background.candidates.set(TARGET_KEY, throwingCandidate());-- await expect(harness.handoff.beginPromotion(TARGET_KEY)).rejects.toThrow('handover refused');-- expect(mocks.events).toContain(`foreground:rollback-handover:${ACCOUNT_KEY}`);- expect(harness.background.protectedAccountKeys).toEqual([]);- });-- test('a failed promotion leaves the coordinator free for the next account', async () => {- const harness = createHarness();- harness.background.candidates.set(TARGET_KEY, throwingCandidate());-- await expect(harness.handoff.beginPromotion(TARGET_KEY)).rejects.toThrow('handover refused');-- await expect(harness.handoff.beginPromotion('other.test::300')).resolves.toBeUndefined();- });-});diff --git a/fluxer_app/src/features/gateway/transport/ForegroundGatewayHandoff.ts b/fluxer_app/src/features/gateway/transport/ForegroundGatewayHandoff.tsdeleted file mode 100644index ea1cfffb8..000000000--- a/fluxer_app/src/features/gateway/transport/ForegroundGatewayHandoff.ts+++ /dev/null@@ -1,339 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {SNAPSHOT_SCHEMA_EPOCH} from '@app/features/gateway/snapshot/SnapshotEntities';-import {- captureForegroundMentionCounts,- hydrateStoresFromSnapshotScope,-} from '@app/features/gateway/snapshot/SnapshotHydration';-import SnapshotSync from '@app/features/gateway/snapshot/SnapshotSync';-import type {StateSnapshotCapture} from '@app/features/gateway/snapshot/SnapshotTypes';-import {gatewayEndpointForAccount} from '@app/features/gateway/transport/BackgroundGatewayAccounts';-import {BackgroundGatewaySession} from '@app/features/gateway/transport/BackgroundGatewaySession';-import {- type BackgroundGatewaySessionManager,- readMaxBackgroundGatewayConnections,-} from '@app/features/gateway/transport/BackgroundGatewaySessionManager';-import {- ForegroundPromoteCoordinator,- type ForegroundPromoteHost,- type ForegroundPromotionOutcome,-} from '@app/features/gateway/transport/ForegroundPromoteCoordinator';-import type {GatewaySocket, GatewaySocketProperties} from '@app/features/gateway/transport/GatewaySocket';-import type {PooledGatewayConnection} from '@app/features/gateway/transport/PooledGatewayConnection';-import SessionManager, {type Account} from '@app/features/platform/state/AuthSession';-import {Logger} from '@app/features/platform/utils/AppLogger';--const logger = new Logger('ForegroundGatewayHandoff');--export type ForegroundDemotionRetirementReason =- | 'no_foreground'- | 'handover_unavailable'- | 'socket_lost'- | 'account_unavailable'- | 'transport_disabled'- | 'capacity_disabled'- | 'endpoint_unavailable'- | 'metadata_unavailable'- | 'snapshot_unavailable';--export type ForegroundDemotionOutcome =- | {readonly mode: 'retained'; readonly accountKey: string; readonly sessionId: string}- | {- readonly mode: 'retired';- readonly accountKey: string | null;- readonly reason: ForegroundDemotionRetirementReason;- };--export class ForegroundGatewayHandoff {- private readonly promotion: ForegroundPromoteCoordinator;- private promotionTargetAccountKey: string | null = null;- private promotionStartedAtMs: number | null = null;- private demotionAccountKey: string | null = null;-- constructor(- private readonly foreground: PooledGatewayConnection,- private readonly background: BackgroundGatewaySessionManager,- ) {- this.promotion = new ForegroundPromoteCoordinator(this.createPromotionHost());- }-- async beginPromotion(accountKey: string): Promise<void> {- if (this.promotionTargetAccountKey !== null) {- throw new Error(`Foreground gateway promotion is already active for ${this.promotionTargetAccountKey}`);- }- this.promotionTargetAccountKey = accountKey;- this.promotionStartedAtMs = Date.now();- this.background.protect(accountKey);- const previousAccountKey = this.foreground.foregroundAccountKey;- try {- if (- previousAccountKey !== null &&- previousAccountKey !== accountKey &&- this.foreground.beginForegroundDemotionHandover(previousAccountKey)- ) {- this.demotionAccountKey = previousAccountKey;- this.background.protect(previousAccountKey);- }- if (this.background.isTransportAvailable()) {- try {- await this.background.preloadProperties();- } catch (error) {- logger.warn('Failed to pre-resolve client metadata for gateway handover', error);- }- }- await this.promotion.begin(accountKey);- } catch (error) {- const demotionAccountKey = this.demotionAccountKey ?? previousAccountKey;- try {- if (demotionAccountKey !== null) {- await this.foreground.rollbackForegroundDemotionHandover(demotionAccountKey);- }- } finally {- this.releaseHandoffAccounts();- }- throw error;- }- }-- async completePromotion(accountKey: string): Promise<void> {- if (this.promotionTargetAccountKey !== accountKey) {- throw new Error(`Foreground gateway promotion target mismatch for ${accountKey}`);- }- try {- const outcome = await this.promotion.complete(accountKey);- this.logPromotionOutcome(accountKey, outcome);- } finally {- await this.unwindHandoff(accountKey);- }- }-- private logPromotionOutcome(accountKey: string, outcome: ForegroundPromotionOutcome): void {- const startedAtMs = this.promotionStartedAtMs;- if (startedAtMs === null) {- throw new Error(`Foreground gateway promotion for ${accountKey} has no start time`);- }- logger.info('Foreground gateway promotion completed', {- accountKey,- mode: outcome.mode,- reason: outcome.mode === 'cold' ? outcome.reason : null,- elapsedMs: Date.now() - startedAtMs,- });- }-- async rollbackPromotion(accountKey: string): Promise<void> {- if (this.promotionTargetAccountKey !== accountKey) {- return;- }- await this.unwindHandoff(accountKey);- }-- private async unwindHandoff(accountKey: string): Promise<void> {- try {- await this.promotion.rollback(accountKey);- } finally {- try {- if (this.demotionAccountKey !== null) {- await this.foreground.rollbackForegroundDemotionHandover(this.demotionAccountKey);- }- } finally {- this.releaseHandoffAccounts();- }- }- }-- async demoteForegroundForAccountSwitch(): Promise<ForegroundDemotionOutcome> {- const startedAtMs = Date.now();- const previousAccountKey = this.foreground.foregroundAccountKey;- try {- const outcome = await this.executeForegroundDemotion(previousAccountKey);- logger.info('Foreground gateway demotion completed', {- accountKey: outcome.accountKey,- mode: outcome.mode,- reason: outcome.mode === 'retired' ? outcome.reason : null,- sessionId: outcome.mode === 'retained' ? outcome.sessionId : null,- elapsedMs: Date.now() - startedAtMs,- });- return outcome;- } catch (error) {- this.foreground.retireForAccountSwitch();- logger.error('Foreground gateway demotion failed', {- accountKey: previousAccountKey,- elapsedMs: Date.now() - startedAtMs,- error,- });- throw error;- } finally {- if (previousAccountKey !== null && this.demotionAccountKey === previousAccountKey) {- this.demotionAccountKey = null;- this.background.unprotect(previousAccountKey);- }- this.background.sync();- }- }-- private async executeForegroundDemotion(previousAccountKey: string | null): Promise<ForegroundDemotionOutcome> {- if (previousAccountKey === null) {- return this.retireForeground(null, 'no_foreground');- }- if (this.demotionAccountKey === null) {- if (!this.foreground.beginForegroundDemotionHandover(previousAccountKey)) {- return this.retireForeground(previousAccountKey, 'handover_unavailable');- }- this.demotionAccountKey = previousAccountKey;- this.background.protect(previousAccountKey);- } else if (this.demotionAccountKey !== previousAccountKey) {- throw new Error(`Foreground gateway demotion belongs to ${this.demotionAccountKey}, not ${previousAccountKey}`);- }- this.background.invalidateSync();- if (!(await this.foreground.consumeForegroundDemotionHandover(previousAccountKey))) {- return this.retireForeground(previousAccountKey, 'socket_lost');- }- const retainedAccount = SessionManager.getAccount(previousAccountKey);- if (retainedAccount === null || !retainedAccount.isValid || retainedAccount.instance === undefined) {- return this.retireForeground(previousAccountKey, 'account_unavailable');- }- if (!this.background.isTransportAvailable()) {- return this.retireForeground(previousAccountKey, 'transport_disabled');- }- const maxBackgroundConnections = readMaxBackgroundGatewayConnections(- retainedAccount.instance.features.max_background_gateway_connections,- );- if (maxBackgroundConnections <= 0) {- return this.retireForeground(previousAccountKey, 'capacity_disabled');- }- const gatewayEndpoint = gatewayEndpointForAccount(retainedAccount);- if (gatewayEndpoint === null) {- return this.retireForeground(previousAccountKey, 'endpoint_unavailable');- }- const properties = this.background.cachedProperties;- if (properties === null) {- return this.retireForeground(previousAccountKey, 'metadata_unavailable');- }- await SnapshotSync.flush(previousAccountKey);- const foregroundSocket = this.foreground.foregroundSocketForAccount(previousAccountKey);- const sessionId = foregroundSocket?.getSessionId() ?? null;- if (foregroundSocket === null || sessionId === null || !foregroundSocket.isConnected()) {- return this.retireForeground(previousAccountKey, 'socket_lost');- }- const snapshot = SnapshotSync.demoteForeground(previousAccountKey);- if (snapshot === null) {- return this.retireForeground(previousAccountKey, 'snapshot_unavailable');- }- if (snapshot.cursor.sessionId !== sessionId || snapshot.cursor.schemaEpoch !== SNAPSHOT_SCHEMA_EPOCH) {- throw new Error(- `Foreground gateway snapshot invariant failed for ${previousAccountKey}: live=${sessionId}, snapshot=${snapshot.cursor.sessionId}, schema=${snapshot.cursor.schemaEpoch}`,- );- }- const socket = this.foreground.detachForegroundSocket();- if (socket === null || socket !== foregroundSocket) {- throw new Error(`Foreground gateway socket detach invariant failed for ${previousAccountKey}`);- }- this.adoptDemotedSocket(previousAccountKey, retainedAccount, gatewayEndpoint, properties, socket, snapshot);- this.foreground.retireForAccountSwitch();- return {mode: 'retained', accountKey: previousAccountKey, sessionId};- }-- private retireForeground(- accountKey: string | null,- reason: ForegroundDemotionRetirementReason,- ): ForegroundDemotionOutcome {- this.foreground.retireForAccountSwitch();- return {mode: 'retired', accountKey, reason};- }-- private adoptDemotedSocket(- accountKey: string,- account: Account,- gatewayEndpoint: string,- properties: GatewaySocketProperties,- socket: GatewaySocket,- snapshot: StateSnapshotCapture,- ): void {- const session = new BackgroundGatewaySession({- account,- gatewayEndpoint,- properties,- onStopRequested: () => this.background.stop(accountKey),- });- try {- session.adoptSocket(socket, snapshot, captureForegroundMentionCounts());- this.background.adopt(accountKey, session);- } catch (error) {- session.stop();- if (socket.isConnected()) {- this.discardDetachedSocket(socket);- }- throw new Error(`Failed to retain foreground gateway ${accountKey} as a background session`, {cause: error});- }- }-- private createPromotionHost(): ForegroundPromoteHost {- return {- findWarmCandidate: (accountKey) => this.background.find(accountKey),- prepareForegroundSnapshot: async (accountKey) => {- await SnapshotSync.flush(accountKey);- const candidate = this.background.find(accountKey);- const capture = SnapshotSync.captureDemotionSnapshot(accountKey);- if (- candidate === null ||- capture === null ||- capture.cursor.sessionId !== candidate.backgroundSessionId ||- capture.cursor.schemaEpoch !== SNAPSHOT_SCHEMA_EPOCH- ) {- return false;- }- return SnapshotSync.prepareForegroundPromotion(accountKey, capture.entries);- },- hydrateForegroundSnapshot: (accountKey) =>- hydrateStoresFromSnapshotScope(accountKey, this.background.find(accountKey)?.captureMentionCounts() ?? null),- commitForegroundSnapshot: (accountKey) => SnapshotSync.commitForegroundPromotion(accountKey),- abortForegroundSnapshot: (accountKey) => SnapshotSync.abortForegroundPromotion(accountKey),- finalizeForegroundSnapshot: (accountKey) => SnapshotSync.finalizeForegroundPromotion(accountKey),- stopBackgroundConnection: (accountKey) => this.background.stop(accountKey),- prepareForegroundReplay: () => this.foreground.preparePromotedForegroundReplay(),- adoptForegroundSocket: (accountKey, socket) => {- const sessionId = socket.getSessionId();- if (sessionId === null) {- throw new Error('Cannot promote a background gateway without its live session id');- }- this.foreground.adoptForegroundSocket(socket, {accountKey, sessionId});- },- replayForegroundDispatch: (accountKey, delivery) =>- this.foreground.replayForegroundDispatch(accountKey, delivery),- finalizeForeground: (accountKey) => this.foreground.finalizePromotedForegroundSession(accountKey),- removeBackgroundConnection: (accountKey) => {- if (!this.background.detachRegistration(accountKey)) {- throw new Error(`Promoted background gateway ${accountKey} was not registered`);- }- },- discardDetachedSocket: (socket) => this.discardDetachedSocket(socket),- discardForegroundConnection: (accountKey) => {- if (this.foreground.foregroundAccountKey !== accountKey) {- throw new Error(`Cannot discard a foreground gateway not owned by ${accountKey}`);- }- this.foreground.retireForAccountSwitch();- },- };- }-- private discardDetachedSocket(socket: GatewaySocket): void {- try {- socket.reset(false);- } catch (error) {- logger.warn('Failed to reset a detached gateway promotion socket', error);- }- }-- private releaseHandoffAccounts(): void {- if (this.promotionTargetAccountKey !== null) {- this.background.unprotect(this.promotionTargetAccountKey);- }- if (this.demotionAccountKey !== null) {- this.background.unprotect(this.demotionAccountKey);- }- this.promotionTargetAccountKey = null;- this.promotionStartedAtMs = null;- this.demotionAccountKey = null;- this.background.sync();- }-}diff --git a/fluxer_app/src/features/gateway/transport/ForegroundPromoteCoordinator.test.ts b/fluxer_app/src/features/gateway/transport/ForegroundPromoteCoordinator.test.tsdeleted file mode 100644index b67f93231..000000000--- a/fluxer_app/src/features/gateway/transport/ForegroundPromoteCoordinator.test.ts+++ /dev/null@@ -1,458 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type BackgroundDispatchHandoverEnd,- BackgroundDispatchHandoverOutcome,-} from '@app/features/gateway/transport/BackgroundGatewayDispatchQueue';-import {- ForegroundPromoteCoordinator,- type ForegroundPromoteHost,- type WarmForegroundCandidate,-} from '@app/features/gateway/transport/ForegroundPromoteCoordinator';-import type {GatewayDispatchDelivery, GatewaySocket} from '@app/features/gateway/transport/GatewaySocket';-import {describe, expect, test} from 'vitest';--const ACCOUNT_KEY = 'secondary.test::200';-const WARM_PROMOTE_BUFFER_MAX_BYTES = 16 * 1024 * 1024;-const WARM_PROMOTE_BUFFER_MAX_ENTRIES = 1024;--function delivery(type: string, retainedByteSize = 8): GatewayDispatchDelivery {- return {- type,- data: {},- retainedByteSize,- receipt: {sequence: 1, generation: 0},- } as unknown as GatewayDispatchDelivery;-}--class FakeCandidate implements WarmForegroundCandidate {- isBackgroundConnectionReady = true;- readyResult = true;- socket: GatewaySocket | null = {} as GatewaySocket;- idleHook: (() => void) | null = null;- lastHandoverEnd: BackgroundDispatchHandoverEnd | null = null;- private listener: ((item: GatewayDispatchDelivery) => void) | null = null;-- constructor(private readonly calls: Array<string>) {}-- beginBackgroundDispatchHandover(listener: (item: GatewayDispatchDelivery) => void): void {- this.calls.push('beginHandover');- this.listener = listener;- }-- endBackgroundDispatchHandover(request: BackgroundDispatchHandoverEnd): void {- this.calls.push(`endHandover:${request.outcome}`);- this.lastHandoverEnd =- request.outcome === BackgroundDispatchHandoverOutcome.RESTORED- ? {outcome: request.outcome, deliveries: [...request.deliveries]}- : request;- this.listener = null;- }-- detachBackgroundSocket(): GatewaySocket | null {- this.calls.push('detach');- const socket = this.socket;- this.socket = null;- return socket;- }-- waitForBackgroundConnectionReady(): Promise<boolean> {- this.calls.push('waitReady');- return Promise.resolve(this.readyResult);- }-- waitForBackgroundDispatchIdle(): Promise<void> {- this.calls.push('idle');- this.idleHook?.();- return Promise.resolve();- }-- deliver(item: GatewayDispatchDelivery): void {- this.listener?.(item);- }-}--class FakeHost implements ForegroundPromoteHost {- snapshotPrepared = true;- commitAccepted = true;- replayError: Error | null = null;- hydrateError: Error | null = null;- adoptedSockets: Array<GatewaySocket> = [];- hydrateHook: (() => void) | null = null;-- constructor(- readonly calls: Array<string>,- public candidate: WarmForegroundCandidate | null,- ) {}-- findWarmCandidate(): WarmForegroundCandidate | null {- return this.candidate;- }-- prepareForegroundSnapshot(): Promise<boolean> {- this.calls.push('prepareSnapshot');- return Promise.resolve(this.snapshotPrepared);- }-- hydrateForegroundSnapshot(): Promise<void> {- this.calls.push('hydrate');- this.hydrateHook?.();- return this.hydrateError === null ? Promise.resolve() : Promise.reject(this.hydrateError);- }-- commitForegroundSnapshot(): boolean {- this.calls.push('commit');- return this.commitAccepted;- }-- abortForegroundSnapshot(): void {- this.calls.push('abortSnapshot');- }-- finalizeForegroundSnapshot(): void {- this.calls.push('finalizeSnapshot');- }-- stopBackgroundConnection(): void {- this.calls.push('stopBackground');- }-- prepareForegroundReplay(): void {- this.calls.push('prepareReplay');- }-- adoptForegroundSocket(_accountKey: string, socket: GatewaySocket): void {- this.calls.push('adopt');- this.adoptedSockets.push(socket);- }-- replayForegroundDispatch(_accountKey: string, item: GatewayDispatchDelivery): void {- this.calls.push(`replay:${item.type}`);- if (this.replayError !== null) {- throw this.replayError;- }- }-- finalizeForeground(): void {- this.calls.push('finalizeForeground');- }-- removeBackgroundConnection(): void {- this.calls.push('removeBackground');- }-- discardDetachedSocket(): void {- this.calls.push('discardSocket');- }-- discardForegroundConnection(): void {- this.calls.push('discardForeground');- }-}--function createHarness(): {calls: Array<string>; candidate: FakeCandidate; host: FakeHost} {- const calls: Array<string> = [];- const candidate = new FakeCandidate(calls);- return {calls, candidate, host: new FakeHost(calls, candidate)};-}--describe('foreground promote coordinator', () => {- test('a warm promotion hands the background socket over in one fixed order', async () => {- const {calls, candidate, host} = createHarness();- const promoted = candidate.socket;- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- candidate.deliver(delivery('MESSAGE_CREATE'));- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'warm'});- expect(calls).toEqual([- 'beginHandover',- 'idle',- 'prepareSnapshot',- 'idle',- 'idle',- 'prepareReplay',- 'hydrate',- 'idle',- 'commit',- `endHandover:${BackgroundDispatchHandoverOutcome.CONSUMED}`,- 'detach',- 'removeBackground',- 'adopt',- 'replay:MESSAGE_CREATE',- 'finalizeForeground',- 'finalizeSnapshot',- ]);- expect(host.adoptedSockets).toEqual([promoted]);- });-- test('a missing candidate goes cold without touching any handover', async () => {- const {calls, host} = createHarness();- host.candidate = null;- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'no_candidate'});- expect(calls).toEqual(['stopBackground']);- });-- test('a candidate that never becomes ready goes cold without touching any handover', async () => {- const {calls, candidate, host} = createHarness();- candidate.isBackgroundConnectionReady = false;- candidate.readyResult = false;- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'candidate_not_ready_timeout'});- expect(calls).toEqual(['waitReady', 'stopBackground']);- });-- test('a candidate lost during the handover restores its buffered dispatches and aborts the snapshot once', async () => {- const {calls, candidate, host} = createHarness();- const buffered = delivery('MESSAGE_CREATE');- const coordinator = new ForegroundPromoteCoordinator(host);- candidate.idleHook = () => {- candidate.deliver(buffered);- candidate.isBackgroundConnectionReady = false;- };-- await coordinator.begin(ACCOUNT_KEY);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'candidate_lost'});- expect(candidate.lastHandoverEnd).toEqual({- outcome: BackgroundDispatchHandoverOutcome.RESTORED,- deliveries: [buffered],- });- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls.filter((call) => call.startsWith('endHandover'))).toEqual([- `endHandover:${BackgroundDispatchHandoverOutcome.RESTORED}`,- ]);- expect(calls).not.toContain('adopt');- });-- test('an unavailable snapshot goes cold and restores the handover once', async () => {- const {calls, candidate, host} = createHarness();- host.snapshotPrepared = false;- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'snapshot_unavailable'});- expect(candidate.lastHandoverEnd).toEqual({- outcome: BackgroundDispatchHandoverOutcome.RESTORED,- deliveries: [],- });- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls).not.toContain('detach');- });-- test('a buffer overflow goes cold and loses the handover instead of restoring it', async () => {- const {calls, candidate, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- candidate.deliver(delivery('MESSAGE_CREATE', WARM_PROMOTE_BUFFER_MAX_BYTES));- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'buffer_capacity'});- expect(candidate.lastHandoverEnd).toEqual({outcome: BackgroundDispatchHandoverOutcome.LOST});- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls).not.toContain('adopt');- });-- test('exceeding the retained entry bound goes cold and loses the handover instead of restoring it', async () => {- const {calls, candidate, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- for (let index = 0; index <= WARM_PROMOTE_BUFFER_MAX_ENTRIES; index += 1) {- candidate.deliver(delivery('MESSAGE_CREATE'));- }- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'buffer_capacity'});- expect(candidate.lastHandoverEnd).toEqual({outcome: BackgroundDispatchHandoverOutcome.LOST});- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls).not.toContain('adopt');- });-- test('staying one delivery under the retained entry bound still promotes warm', async () => {- const {calls, candidate, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- for (let index = 0; index < WARM_PROMOTE_BUFFER_MAX_ENTRIES; index += 1) {- candidate.deliver(delivery('MESSAGE_CREATE'));- }- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'warm'});- expect(candidate.lastHandoverEnd).toEqual({outcome: BackgroundDispatchHandoverOutcome.CONSUMED});- expect(calls.filter((call) => call === 'replay:MESSAGE_CREATE')).toHaveLength(WARM_PROMOTE_BUFFER_MAX_ENTRIES);- });-- test('a failure after the foreground socket is adopted discards the foreground connection', async () => {- const {calls, candidate, host} = createHarness();- const replayError = new Error('replay exploded');- host.replayError = replayError;- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- candidate.deliver(delivery('MESSAGE_CREATE'));-- await expect(coordinator.complete(ACCOUNT_KEY)).rejects.toBe(replayError);- expect(calls).toContain('discardForeground');- expect(calls).not.toContain('discardSocket');- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls).toContain('stopBackground');-- host.candidate = null;- await expect(coordinator.begin(ACCOUNT_KEY)).resolves.toBeUndefined();- });-- test('a rollback restores the buffered dispatches and clears the promotion', async () => {- const {calls, candidate, host} = createHarness();- const buffered = delivery('MESSAGE_CREATE');- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- candidate.deliver(buffered);- await coordinator.rollback(ACCOUNT_KEY);-- expect(candidate.lastHandoverEnd).toEqual({- outcome: BackgroundDispatchHandoverOutcome.RESTORED,- deliveries: [buffered],- });- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls).not.toContain('detach');-- host.candidate = null;- await expect(coordinator.begin(ACCOUNT_KEY)).resolves.toBeUndefined();- });-- test('buffered dispatches replay into the promoted foreground in arrival order', async () => {- const {calls, candidate, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- candidate.deliver(delivery('MESSAGE_CREATE'));- candidate.deliver(delivery('MESSAGE_UPDATE'));- candidate.deliver(delivery('MESSAGE_DELETE'));- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'warm'});- expect(calls.filter((call) => call.startsWith('replay:'))).toEqual([- 'replay:MESSAGE_CREATE',- 'replay:MESSAGE_UPDATE',- 'replay:MESSAGE_DELETE',- ]);- });-- test('a candidate replaced in the registry mid-handover goes cold instead of promoting the stale one', async () => {- const {calls, candidate, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- host.candidate = new FakeCandidate(calls);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'candidate_lost'});- expect(candidate.socket).not.toBeNull();- expect(host.adoptedSockets).toEqual([]);- expect(calls).not.toContain('adopt');- });-- test('a buffer overflow during snapshot hydration goes cold instead of promoting without its dispatches', async () => {- const {calls, candidate, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);- host.hydrateHook = () => {- candidate.deliver(delivery('MESSAGE_CREATE', WARM_PROMOTE_BUFFER_MAX_BYTES));- };-- await coordinator.begin(ACCOUNT_KEY);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'buffer_capacity'});- expect(candidate.lastHandoverEnd).toEqual({outcome: BackgroundDispatchHandoverOutcome.LOST});- expect(calls).not.toContain('adopt');- });-- test('a snapshot that fails to hydrate goes cold instead of failing the whole promotion', async () => {- const {calls, candidate, host} = createHarness();- host.hydrateError = new Error('snapshot hydration rejected');- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- const outcome = await coordinator.complete(ACCOUNT_KEY);-- expect(outcome).toEqual({mode: 'cold', reason: 'snapshot_unavailable'});- expect(candidate.lastHandoverEnd).toEqual({- outcome: BackgroundDispatchHandoverOutcome.RESTORED,- deliveries: [],- });- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- expect(calls).toContain('stopBackground');- expect(calls).not.toContain('adopt');-- host.candidate = null;- await expect(coordinator.begin(ACCOUNT_KEY)).resolves.toBeUndefined();- });-- test('a rejected snapshot commit aborts instead of adopting the background socket', async () => {- const {calls, candidate, host} = createHarness();- host.commitAccepted = false;- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);- candidate.deliver(delivery('MESSAGE_CREATE'));-- await expect(coordinator.complete(ACCOUNT_KEY)).rejects.toThrow(- `Foreground snapshot commit rejected ${ACCOUNT_KEY}`,- );- expect(host.adoptedSockets).toEqual([]);- expect(calls).not.toContain('detach');- expect(calls).not.toContain('adopt');- expect(calls.filter((call) => call === 'abortSnapshot')).toEqual(['abortSnapshot']);- });-- test('completing a promotion under another account key throws instead of driving it', async () => {- const {calls, host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);-- await expect(coordinator.complete('third.test::300')).rejects.toThrow(- `Foreground gateway promotion belongs to ${ACCOUNT_KEY}, not third.test::300`,- );- expect(calls).not.toContain('adopt');- await expect(coordinator.complete(ACCOUNT_KEY)).resolves.toEqual({mode: 'warm'});- });-- test('completing a promotion that never began throws', async () => {- const {host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await expect(coordinator.complete(ACCOUNT_KEY)).rejects.toThrow(- `No foreground gateway promotion is active for ${ACCOUNT_KEY}`,- );- });-- test('beginning a second promotion while one is active throws', async () => {- const {host} = createHarness();- const coordinator = new ForegroundPromoteCoordinator(host);-- await coordinator.begin(ACCOUNT_KEY);-- await expect(coordinator.begin('third.test::300')).rejects.toThrow(- `Foreground gateway promotion is already active for ${ACCOUNT_KEY}`,- );- });-});diff --git a/fluxer_app/src/features/gateway/transport/ForegroundPromoteCoordinator.ts b/fluxer_app/src/features/gateway/transport/ForegroundPromoteCoordinator.tsdeleted file mode 100644index f6373a60e..000000000--- a/fluxer_app/src/features/gateway/transport/ForegroundPromoteCoordinator.ts+++ /dev/null@@ -1,362 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- type BackgroundDispatchHandoverEnd,- BackgroundDispatchHandoverOutcome,-} from '@app/features/gateway/transport/BackgroundGatewayDispatchQueue';-import {exceedsDispatchBufferCapacity} from '@app/features/gateway/transport/GatewayDispatchBufferBounds';-import type {GatewayDispatchDelivery, GatewaySocket} from '@app/features/gateway/transport/GatewaySocket';-import {Logger} from '@app/features/platform/utils/AppLogger';--const logger = new Logger('ForegroundPromoteCoordinator');--const WARM_PROMOTE_READY_TIMEOUT_MS = 10_000;--export type ForegroundPromotionColdReason =- | 'no_candidate'- | 'candidate_not_ready_timeout'- | 'candidate_lost'- | 'snapshot_unavailable'- | 'buffer_capacity';--export type ForegroundPromotionOutcome =- | {readonly mode: 'warm'}- | {readonly mode: 'cold'; readonly reason: ForegroundPromotionColdReason};--export interface WarmForegroundCandidate {- readonly isBackgroundConnectionReady: boolean;- beginBackgroundDispatchHandover(listener: (delivery: GatewayDispatchDelivery) => void): void;- endBackgroundDispatchHandover(request: BackgroundDispatchHandoverEnd): void;- detachBackgroundSocket(): GatewaySocket | null;- waitForBackgroundConnectionReady(timeoutMs: number): Promise<boolean>;- waitForBackgroundDispatchIdle(): Promise<void>;-}--export interface ForegroundPromoteHost {- findWarmCandidate(accountKey: string): WarmForegroundCandidate | null;- prepareForegroundSnapshot(accountKey: string): Promise<boolean>;- hydrateForegroundSnapshot(accountKey: string): Promise<void>;- commitForegroundSnapshot(accountKey: string): boolean;- abortForegroundSnapshot(accountKey: string): void;- finalizeForegroundSnapshot(accountKey: string): void;- stopBackgroundConnection(accountKey: string): void | Promise<void>;- prepareForegroundReplay(): void;- adoptForegroundSocket(accountKey: string, socket: GatewaySocket): void;- replayForegroundDispatch(accountKey: string, delivery: GatewayDispatchDelivery): void | Promise<void>;- finalizeForeground(accountKey: string): void;- removeBackgroundConnection(accountKey: string): void;- discardDetachedSocket(socket: GatewaySocket): void;- discardForegroundConnection(accountKey: string): void;-}--interface PromoteDispatchBuffer {- readonly deliveries: Array<GatewayDispatchDelivery>;- retainedByteSize: number;- overflowed: boolean;-}--interface ColdPromotion {- readonly mode: 'cold';- readonly targetAccountKey: string;- readonly reason: ForegroundPromotionColdReason;-}--interface WarmingPromotion {- readonly mode: 'warming';- readonly targetAccountKey: string;- readonly candidate: WarmForegroundCandidate;-}--interface WarmPromotion {- readonly mode: 'warm';- readonly targetAccountKey: string;- readonly candidate: WarmForegroundCandidate;- readonly buffer: PromoteDispatchBuffer;- handoverActive: boolean;-}--type ActivePromotion = ColdPromotion | WarmingPromotion | WarmPromotion;--export class ForegroundPromoteCoordinator {- private active: ActivePromotion | null = null;-- constructor(private readonly host: ForegroundPromoteHost) {}-- async begin(targetAccountKey: string): Promise<void> {- if (this.active !== null) {- throw new Error(`Foreground gateway promotion is already active for ${this.active.targetAccountKey}`);- }- const candidate = this.host.findWarmCandidate(targetAccountKey);- if (candidate === null) {- this.active = {mode: 'cold', targetAccountKey, reason: 'no_candidate'};- return;- }- if (!candidate.isBackgroundConnectionReady) {- const coldReason = await this.waitForWarmCandidate(targetAccountKey, candidate);- if (coldReason !== null) {- this.active = {mode: 'cold', targetAccountKey, reason: coldReason};- return;- }- }- const active: WarmPromotion = {- mode: 'warm',- targetAccountKey,- candidate,- buffer: {deliveries: [], retainedByteSize: 0, overflowed: false},- handoverActive: false,- };- this.active = active;- try {- candidate.beginBackgroundDispatchHandover((delivery) => this.captureDispatch(active.buffer, delivery));- active.handoverActive = true;- const handoverReason = await this.settleWarmCheckpoint(active);- if (handoverReason !== null) {- this.fallbackToCold(active, handoverReason);- return;- }- const snapshotPrepared = await this.host.prepareForegroundSnapshot(targetAccountKey);- const snapshotReason = await this.settleWarmCheckpoint(active);- if (snapshotReason !== null) {- this.fallbackToCold(active, snapshotReason);- return;- }- if (!snapshotPrepared) {- this.fallbackToCold(active, 'snapshot_unavailable');- }- } catch (error) {- await this.abortFailedWarmPromotion(active);- throw error;- }- }-- async complete(targetAccountKey: string): Promise<ForegroundPromotionOutcome> {- const active = this.requireActivePromotion(targetAccountKey);- if (active.mode === 'cold') {- this.active = null;- await this.host.stopBackgroundConnection(targetAccountKey);- return {mode: 'cold', reason: active.reason};- }- if (active.mode === 'warming') {- throw new Error(`Foreground gateway promotion for ${targetAccountKey} is still warming`);- }- let detachedSocket: GatewaySocket | null = null;- let foregroundAdopted = false;- try {- const handoverReason = await this.settleWarmCheckpoint(active);- if (handoverReason !== null) {- return await this.finishCold(active, handoverReason);- }- this.host.prepareForegroundReplay();- try {- await this.host.hydrateForegroundSnapshot(targetAccountKey);- } catch (error) {- logger.warn('Falling back to a cold foreground promotion after snapshot hydration failed', {- targetAccountKey,- error,- });- return await this.finishCold(active, 'snapshot_unavailable');- }- const hydrationReason = await this.settleWarmCheckpoint(active);- if (hydrationReason !== null) {- return await this.finishCold(active, hydrationReason);- }- if (!this.host.commitForegroundSnapshot(targetAccountKey)) {- throw new Error(`Foreground snapshot commit rejected ${targetAccountKey}`);- }- this.endHandover(active, {outcome: BackgroundDispatchHandoverOutcome.CONSUMED});- detachedSocket = active.candidate.detachBackgroundSocket();- if (detachedSocket === null) {- throw new Error(`Ready background gateway ${targetAccountKey} had no socket to promote`);- }- this.host.removeBackgroundConnection(targetAccountKey);- this.host.adoptForegroundSocket(targetAccountKey, detachedSocket);- foregroundAdopted = true;- for (const delivery of active.buffer.deliveries) {- await this.host.replayForegroundDispatch(targetAccountKey, delivery);- }- this.clearBuffer(active.buffer);- this.host.finalizeForeground(targetAccountKey);- this.host.finalizeForegroundSnapshot(targetAccountKey);- this.active = null;- return {mode: 'warm'};- } catch (error) {- if (this.active === active) {- await this.cleanFailedCompletion(active, detachedSocket, foregroundAdopted);- }- throw error;- }- }-- async rollback(targetAccountKey: string): Promise<void> {- const active = this.active;- if (active === null) {- return;- }- if (active.targetAccountKey !== targetAccountKey) {- throw new Error(- `Cannot roll back foreground gateway promotion for ${targetAccountKey} because ${active.targetAccountKey} is active`,- );- }- if (active.mode === 'cold' || active.mode === 'warming') {- this.active = null;- return;- }- try {- await active.candidate.waitForBackgroundDispatchIdle();- this.restoreOrDiscardHandover(active);- this.host.abortForegroundSnapshot(targetAccountKey);- this.active = null;- } catch (error) {- await this.abortFailedWarmPromotion(active);- throw error;- }- }-- private captureDispatch(buffer: PromoteDispatchBuffer, delivery: GatewayDispatchDelivery): void {- if (buffer.overflowed) {- return;- }- if (- exceedsDispatchBufferCapacity(- buffer.deliveries.length + 1,- buffer.retainedByteSize + delivery.retainedByteSize,- delivery.retainedByteSize,- )- ) {- buffer.overflowed = true;- return;- }- buffer.deliveries.push(delivery);- buffer.retainedByteSize += delivery.retainedByteSize;- }-- private requireActivePromotion(targetAccountKey: string): ActivePromotion {- const active = this.active;- if (active === null) {- throw new Error(`No foreground gateway promotion is active for ${targetAccountKey}`);- }- if (active.targetAccountKey !== targetAccountKey) {- throw new Error(`Foreground gateway promotion belongs to ${active.targetAccountKey}, not ${targetAccountKey}`);- }- return active;- }-- private async settleWarmCheckpoint(active: WarmPromotion): Promise<ForegroundPromotionColdReason | null> {- await active.candidate.waitForBackgroundDispatchIdle();- if (active.buffer.overflowed) {- return 'buffer_capacity';- }- if (!this.isWarmPromotionAvailable(active)) {- return 'candidate_lost';- }- return null;- }-- private isWarmPromotionAvailable(active: WarmPromotion): boolean {- return (- active.candidate.isBackgroundConnectionReady &&- this.host.findWarmCandidate(active.targetAccountKey) === active.candidate- );- }-- private async waitForWarmCandidate(- targetAccountKey: string,- candidate: WarmForegroundCandidate,- ): Promise<ForegroundPromotionColdReason | null> {- const active: WarmingPromotion = {mode: 'warming', targetAccountKey, candidate};- this.active = active;- try {- const ready = await candidate.waitForBackgroundConnectionReady(WARM_PROMOTE_READY_TIMEOUT_MS);- if (this.active !== active || this.host.findWarmCandidate(targetAccountKey) !== candidate) {- return 'candidate_lost';- }- if (!ready) {- return 'candidate_not_ready_timeout';- }- if (!candidate.isBackgroundConnectionReady) {- return 'candidate_lost';- }- return null;- } catch (error) {- if (this.active === active) {- this.active = null;- }- throw error;- }- }-- private fallbackToCold(active: WarmPromotion, reason: ForegroundPromotionColdReason): void {- this.restoreOrDiscardHandover(active);- this.host.abortForegroundSnapshot(active.targetAccountKey);- this.active = {mode: 'cold', targetAccountKey: active.targetAccountKey, reason};- }-- private async finishCold(- active: WarmPromotion,- reason: ForegroundPromotionColdReason,- ): Promise<ForegroundPromotionOutcome> {- this.restoreOrDiscardHandover(active);- this.host.abortForegroundSnapshot(active.targetAccountKey);- this.active = null;- await this.host.stopBackgroundConnection(active.targetAccountKey);- return {mode: 'cold', reason};- }-- private restoreOrDiscardHandover(active: WarmPromotion): void {- this.endHandover(- active,- active.buffer.overflowed- ? {outcome: BackgroundDispatchHandoverOutcome.LOST}- : {outcome: BackgroundDispatchHandoverOutcome.RESTORED, deliveries: active.buffer.deliveries},- );- this.clearBuffer(active.buffer);- }-- private endHandover(active: WarmPromotion, request: BackgroundDispatchHandoverEnd): void {- if (!active.handoverActive) {- return;- }- active.handoverActive = false;- active.candidate.endBackgroundDispatchHandover(request);- }-- private async abortFailedWarmPromotion(active: WarmPromotion): Promise<void> {- try {- if (active.handoverActive) {- this.endHandover(active, {outcome: BackgroundDispatchHandoverOutcome.LOST});- }- } finally {- this.clearBuffer(active.buffer);- this.host.abortForegroundSnapshot(active.targetAccountKey);- this.active = null;- await this.host.stopBackgroundConnection(active.targetAccountKey);- }- }-- private async cleanFailedCompletion(- active: WarmPromotion,- detachedSocket: GatewaySocket | null,- foregroundAdopted: boolean,- ): Promise<void> {- try {- if (active.handoverActive) {- this.endHandover(active, {outcome: BackgroundDispatchHandoverOutcome.LOST});- }- if (foregroundAdopted) {- this.host.discardForegroundConnection(active.targetAccountKey);- } else if (detachedSocket !== null) {- this.host.discardDetachedSocket(detachedSocket);- }- } finally {- this.clearBuffer(active.buffer);- this.host.abortForegroundSnapshot(active.targetAccountKey);- this.active = null;- await this.host.stopBackgroundConnection(active.targetAccountKey);- }- }-- private clearBuffer(buffer: PromoteDispatchBuffer): void {- buffer.deliveries.length = 0;- buffer.retainedByteSize = 0;- }-}diff --git a/fluxer_app/src/features/gateway/transport/ForegroundPromotionReplayBuffer.ts b/fluxer_app/src/features/gateway/transport/ForegroundPromotionReplayBuffer.tsdeleted file mode 100644index 7488fc1f4..000000000--- a/fluxer_app/src/features/gateway/transport/ForegroundPromotionReplayBuffer.ts+++ /dev/null@@ -1,94 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {exceedsDispatchBufferCapacity} from '@app/features/gateway/transport/GatewayDispatchBufferBounds';-import type {GatewayDispatchDelivery, GatewaySocket} from '@app/features/gateway/transport/GatewaySocket';--interface ActiveForegroundPromotionReplay {- readonly accountKey: string;- readonly socket: GatewaySocket;- readonly deliveries: Array<GatewayDispatchDelivery>;- retainedByteSize: number;- inFlightEntryCount: number;- overflowed: boolean;-}--export type ForegroundPromotionDispatch = (delivery: GatewayDispatchDelivery) => void;--class ForegroundPromotionReplayBufferOverflowError extends Error {- constructor(entryCount: number, retainedByteSize: number) {- super(- `Foreground gateway promotion replay buffer exceeded its bound at ${entryCount} entries and ${retainedByteSize} bytes`,- );- this.name = 'ForegroundPromotionReplayBufferOverflowError';- }-}--export class ForegroundPromotionReplayBuffer {- private active: ActiveForegroundPromotionReplay | null = null;-- begin(accountKey: string, socket: GatewaySocket): void {- if (this.active !== null) {- throw new Error(`Foreground gateway promotion replay is already active for ${this.active.accountKey}`);- }- this.active = {- accountKey,- socket,- deliveries: [],- retainedByteSize: 0,- inFlightEntryCount: 0,- overflowed: false,- };- }-- capture(socket: GatewaySocket, accountKey: string | null, delivery: GatewayDispatchDelivery): boolean {- const active = this.active;- if (active === null || active.socket !== socket || active.accountKey !== accountKey) {- return false;- }- const nextEntryCount = active.inFlightEntryCount + active.deliveries.length + 1;- const nextRetainedByteSize = active.retainedByteSize + delivery.retainedByteSize;- if (exceedsDispatchBufferCapacity(nextEntryCount, nextRetainedByteSize, delivery.retainedByteSize)) {- active.overflowed = true;- active.socket.failDispatchProcessing(- delivery.receipt,- new ForegroundPromotionReplayBufferOverflowError(nextEntryCount, nextRetainedByteSize),- );- return true;- }- active.deliveries.push(delivery);- active.retainedByteSize = nextRetainedByteSize;- return true;- }-- drain(accountKey: string, socket: GatewaySocket, dispatch: ForegroundPromotionDispatch): void {- const active = this.active;- if (active === null || active.accountKey !== accountKey || active.socket !== socket || active.overflowed) {- throw new Error('Cannot finalize a promoted foreground gateway with an invalid replay buffer');- }- while (active.deliveries.length > 0) {- const queued: Array<GatewayDispatchDelivery | null> = active.deliveries.splice(0, active.deliveries.length);- active.inFlightEntryCount = queued.length;- for (let index = 0; index < queued.length; index += 1) {- const delivery = queued[index];- if (delivery === null) {- throw new Error('Foreground promotion replay queue released an unprocessed dispatch');- }- try {- dispatch(delivery);- } finally {- queued[index] = null;- active.inFlightEntryCount -= 1;- active.retainedByteSize -= delivery.retainedByteSize;- }- }- }- if (active.inFlightEntryCount !== 0 || active.retainedByteSize !== 0) {- throw new Error('Foreground promotion replay queue accounting did not drain to zero');- }- this.active = null;- }-- clear(): void {- this.active = null;- }-}