A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(app): remove the background gateway session manager
Hampuscecef57acd49
diff --git a/fluxer_app/src/features/gateway/transport/BackgroundGatewayDispatchQueue.ts b/fluxer_app/src/features/gateway/transport/BackgroundGatewayDispatchQueue.tsdeleted file mode 100644index 74325ef2d..000000000--- a/fluxer_app/src/features/gateway/transport/BackgroundGatewayDispatchQueue.ts+++ /dev/null@@ -1,256 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {- exceedsDispatchBufferCapacity,- GATEWAY_DISPATCH_BUFFER_MAX_BYTES,-} from '@app/features/gateway/transport/GatewayDispatchBufferBounds';-import type {GatewayDispatchDelivery, GatewaySocket} from '@app/features/gateway/transport/GatewaySocket';--const BACKGROUND_DISPATCH_IDLE_WAITER_MAX_ENTRIES = 8;--export const BackgroundDispatchHandoverOutcome = Object.freeze({- CONSUMED: 'consumed',- RESTORED: 'restored',- LOST: 'lost',-} as const);--export type BackgroundDispatchHandoverOutcome =- (typeof BackgroundDispatchHandoverOutcome)[keyof typeof BackgroundDispatchHandoverOutcome];--export type BackgroundDispatchHandoverEnd =- | {readonly outcome: typeof BackgroundDispatchHandoverOutcome.CONSUMED}- | {- readonly outcome: typeof BackgroundDispatchHandoverOutcome.RESTORED;- readonly deliveries: ReadonlyArray<GatewayDispatchDelivery>;- }- | {readonly outcome: typeof BackgroundDispatchHandoverOutcome.LOST};--interface QueuedBackgroundDispatch {- readonly socket: GatewaySocket;- readonly delivery: GatewayDispatchDelivery;-}--export interface BackgroundGatewayDispatchQueueHost {- isCurrentSocket(socket: GatewaySocket): boolean;- persistHandoverAuthToken(socket: GatewaySocket, delivery: GatewayDispatchDelivery): Promise<GatewayDispatchDelivery>;- processDispatch(socket: GatewaySocket, delivery: GatewayDispatchDelivery): Promise<void>;- handleQueueOverflow(socket: GatewaySocket, delivery: GatewayDispatchDelivery, error: Error): void;- handleQueueFailure(error: unknown): void;-}--class BackgroundGatewayDispatchQueueOverflowError extends Error {- constructor(entryCount: number, retainedByteSize: number) {- super(- `Background gateway dispatch queue exceeded its bound at ${entryCount} entries and ${retainedByteSize} bytes`,- );- this.name = 'BackgroundGatewayDispatchQueueOverflowError';- }-}--class BackgroundGatewayDispatchIdleWaiterCapacityError extends Error {- constructor() {- super(- `Background gateway dispatch queue reached its ${BACKGROUND_DISPATCH_IDLE_WAITER_MAX_ENTRIES} idle waiter bound`,- );- this.name = 'BackgroundGatewayDispatchIdleWaiterCapacityError';- }-}--export class BackgroundGatewayDispatchQueue {- private handoverListener: ((delivery: GatewayDispatchDelivery) => void) | null = null;- private queued: Array<QueuedBackgroundDispatch> = [];- private queuedRetainedByteSize = 0;- private inFlightEntryCount = 0;- private inFlightRetainedByteSize = 0;- private drainScheduled = false;- private idleWaiters: Array<() => void> = [];-- constructor(private readonly host: BackgroundGatewayDispatchQueueHost) {}-- get isHandoverActive(): boolean {- return this.handoverListener !== null;- }-- beginHandover(listener: (delivery: GatewayDispatchDelivery) => void): void {- if (this.handoverListener !== null) {- throw new Error('Background gateway dispatch handover is already active');- }- this.handoverListener = listener;- }-- endHandover(request: BackgroundDispatchHandoverEnd, socket: GatewaySocket | null): boolean {- if (this.handoverListener === null) {- throw new Error('Background gateway dispatch handover is not active');- }- this.handoverListener = null;- if (socket === null) {- return false;- }- switch (request.outcome) {- case BackgroundDispatchHandoverOutcome.CONSUMED:- return false;- case BackgroundDispatchHandoverOutcome.RESTORED:- this.restore(socket, request.deliveries);- return false;- case BackgroundDispatchHandoverOutcome.LOST:- return true;- }- }-- waitForIdle(): Promise<void> {- if (this.isIdle()) {- return Promise.resolve();- }- if (this.idleWaiters.length >= BACKGROUND_DISPATCH_IDLE_WAITER_MAX_ENTRIES) {- return Promise.reject(new BackgroundGatewayDispatchIdleWaiterCapacityError());- }- return new Promise((resolve) => {- this.idleWaiters.push(resolve);- });- }-- assertDetachable(): void {- if (this.handoverListener !== null) {- throw new Error('Background gateway socket cannot detach during an active dispatch handover');- }- if (!this.isIdle()) {- throw new Error('Background gateway socket cannot detach with queued dispatches');- }- }-- enqueue(socket: GatewaySocket, delivery: GatewayDispatchDelivery): void {- const nextEntryCount = this.inFlightEntryCount + this.queued.length + 1;- const nextRetainedByteSize =- this.inFlightRetainedByteSize + this.queuedRetainedByteSize + delivery.retainedByteSize;- if (exceedsDispatchBufferCapacity(nextEntryCount, nextRetainedByteSize, delivery.retainedByteSize)) {- this.clearQueued();- this.host.handleQueueOverflow(- socket,- delivery,- new BackgroundGatewayDispatchQueueOverflowError(nextEntryCount, nextRetainedByteSize),- );- return;- }- this.queued.push({socket, delivery});- this.queuedRetainedByteSize += delivery.retainedByteSize;- this.scheduleDrain();- }-- stop(): void {- this.handoverListener = null;- this.clearQueued();- }-- private restore(socket: GatewaySocket, deliveries: ReadonlyArray<GatewayDispatchDelivery>): void {- const retained = deliveries.filter((delivery) => socket.isDispatchActive(delivery.receipt));- if (retained.length === 0) {- return;- }- const restoredByteSize = retained.reduce((total, delivery) => total + delivery.retainedByteSize, 0);- const nextEntryCount = this.inFlightEntryCount + this.queued.length + retained.length;- const nextRetainedByteSize = this.inFlightRetainedByteSize + this.queuedRetainedByteSize + restoredByteSize;- const oversizedDelivery = retained.find(- (delivery) => delivery.retainedByteSize >= GATEWAY_DISPATCH_BUFFER_MAX_BYTES,- );- if (exceedsDispatchBufferCapacity(nextEntryCount, nextRetainedByteSize, oversizedDelivery?.retainedByteSize ?? 0)) {- const firstRetainedDelivery = retained[0];- if (firstRetainedDelivery === undefined) {- throw new Error('Background gateway dispatch restoration lost its retained delivery');- }- this.clearQueued();- this.host.handleQueueOverflow(- socket,- oversizedDelivery ?? firstRetainedDelivery,- new BackgroundGatewayDispatchQueueOverflowError(nextEntryCount, nextRetainedByteSize),- );- return;- }- this.queued = [...retained.map((delivery) => ({socket, delivery})), ...this.queued];- this.queuedRetainedByteSize += restoredByteSize;- this.scheduleDrain();- }-- private scheduleDrain(): void {- if (this.drainScheduled) {- return;- }- this.drainScheduled = true;- queueMicrotask(() => void this.drain());- }-- private async drain(): Promise<void> {- try {- while (this.queued.length > 0) {- const batch: Array<QueuedBackgroundDispatch | null> = this.queued;- this.inFlightEntryCount = batch.length;- this.inFlightRetainedByteSize = this.queuedRetainedByteSize;- this.queued = [];- this.queuedRetainedByteSize = 0;- for (let index = 0; index < batch.length; index += 1) {- const entry = batch[index];- if (entry === null) {- throw new Error('Background gateway dispatch queue released an unprocessed entry');- }- try {- if (!this.host.isCurrentSocket(entry.socket) || !entry.socket.isDispatchActive(entry.delivery.receipt)) {- continue;- }- const delivery =- this.handoverListener === null- ? entry.delivery- : await this.host.persistHandoverAuthToken(entry.socket, entry.delivery);- if (!this.host.isCurrentSocket(entry.socket) || !entry.socket.isDispatchActive(delivery.receipt)) {- continue;- }- const handoverListener = this.handoverListener;- if (handoverListener === null) {- await this.host.processDispatch(entry.socket, delivery);- } else {- handoverListener(delivery);- }- } finally {- batch[index] = null;- this.inFlightEntryCount -= 1;- this.inFlightRetainedByteSize -= entry.delivery.retainedByteSize;- }- }- }- if (this.inFlightEntryCount !== 0 || this.inFlightRetainedByteSize !== 0) {- throw new Error('Background gateway dispatch queue accounting did not drain to zero');- }- } catch (error) {- this.clearQueued();- this.inFlightEntryCount = 0;- this.inFlightRetainedByteSize = 0;- this.host.handleQueueFailure(error);- } finally {- this.drainScheduled = false;- this.resolveIdleWaiters();- }- }-- private isIdle(): boolean {- return (- !this.drainScheduled &&- this.queued.length === 0 &&- this.inFlightEntryCount === 0 &&- this.inFlightRetainedByteSize === 0- );- }-- private clearQueued(): void {- this.queued = [];- this.queuedRetainedByteSize = 0;- if (!this.drainScheduled) {- this.resolveIdleWaiters();- }- }-- private resolveIdleWaiters(): void {- const waiters = this.idleWaiters;- this.idleWaiters = [];- for (const resolve of waiters) {- resolve();- }- }-}diff --git a/fluxer_app/src/features/gateway/transport/BackgroundGatewaySessionManager.ts b/fluxer_app/src/features/gateway/transport/BackgroundGatewaySessionManager.tsdeleted file mode 100644index 46b9733b7..000000000--- a/fluxer_app/src/features/gateway/transport/BackgroundGatewaySessionManager.ts+++ /dev/null@@ -1,384 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import AccountAccess, {AccountAccessDecision, AccountAccessPhase} from '@app/features/auth/state/AccountAccess';-import {getAccountKey} from '@app/features/auth/state/AccountStorageKey';-import {readAuthenticatedRuntimeContext} from '@app/features/auth/state/AuthenticatedRuntime';-import {pruneOrphanedDesktopStateStores} from '@app/features/gateway/snapshot/SnapshotSync';-import {- backgroundSessionNeedsRestart,- gatewayEndpointForAccount,- selectBackgroundAccounts,-} from '@app/features/gateway/transport/BackgroundGatewayAccounts';-import BackgroundGatewaySessions from '@app/features/gateway/transport/BackgroundGatewayConnectionRegistry';-import {BackgroundGatewaySession} from '@app/features/gateway/transport/BackgroundGatewaySession';-import {installDeferredReaction} from '@app/features/gateway/transport/DeferredReaction';-import type {GatewaySocketProperties} from '@app/features/gateway/transport/GatewaySocket';-import {isDesktopNativeGatewayTransportAvailable} from '@app/features/gateway/transport/GatewayWireTransport';-import {AccountScopedWork} from '@app/features/platform/state/AccountScopedWork';-import SessionManager, {type Account} from '@app/features/platform/state/AuthSession';-import {Logger} from '@app/features/platform/utils/AppLogger';-import {getGatewayClientProperties} from '@app/features/platform/utils/ClientInfo';-import Idle from '@app/features/ui/state/Idle';-import {compareStructural, reaction} from 'mobx';--const logger = new Logger('BackgroundGatewaySessionManager');--export const MAX_BACKGROUND_GATEWAY_CONNECTIONS = 6;-export const BACKGROUND_RESUME_STAGGER_MS = 250;--export class InvalidBackgroundGatewayConnectionLimitError extends Error {- constructor(configured: number) {- super(`Background gateway connection limit must be a non-negative integer, got ${configured}`);- this.name = 'InvalidBackgroundGatewayConnectionLimitError';- }-}--export function readMaxBackgroundGatewayConnections(configured: number | undefined): number {- if (configured === undefined) {- return MAX_BACKGROUND_GATEWAY_CONNECTIONS;- }- if (!Number.isInteger(configured) || configured < 0) {- throw new InvalidBackgroundGatewayConnectionLimitError(configured);- }- return Math.min(configured, MAX_BACKGROUND_GATEWAY_CONNECTIONS);-}--function normalizeBackgroundStartError(error: unknown): Error {- return error instanceof Error ? error : new Error(String(error));-}--export class BackgroundGatewaySessionManager {- private syncRevision = 0;- private bootstrapped = false;- private propertiesPromise: Promise<GatewaySocketProperties> | null = null;- private properties: GatewaySocketProperties | null = null;- private propertiesGeneration = 0;- private retryTimer: number | null = null;- private readonly resumeTimers = new Set<number>();- private readonly protectedAccountKeys = new Set<string>();- private disposers: Array<() => void> = [];-- get isBootstrapped(): boolean {- return this.bootstrapped;- }-- get connectionCount(): number {- return BackgroundGatewaySessions.size;- }-- get cachedProperties(): GatewaySocketProperties | null {- return this.properties;- }-- isTransportAvailable(): boolean {- return isDesktopNativeGatewayTransportAvailable();- }-- start(): void {- if (this.bootstrapped || !this.isTransportAvailable()) {- return;- }- this.bootstrapped = true;- this.disposers.push(- AccountScopedWork.registerTransition({- suspend: () => {- this.invalidateSync();- },- resume: () => undefined,- released: () => this.sync(),- }),- );- this.disposers.push(- installDeferredReaction(() =>- reaction(- () => Idle.isAfk(),- () => {- for (const session of BackgroundGatewaySessions.values()) {- session.refreshPresence();- }- },- {equals: compareStructural},- ),- ),- );- this.disposers.push(- installDeferredReaction(() =>- reaction(- () => {- const accounts = SessionManager.accounts.map((account) => ({- accountKey: getAccountKey(account),- token: account.token,- isValid: account.isValid,- gatewayEndpoint: gatewayEndpointForAccount(account),- lastActive: account.lastActive,- }));- const runtimeContext = SessionManager.isSwitching ? null : readAuthenticatedRuntimeContext();- return {- sessionState: SessionManager.state,- currentAccountKey: SessionManager.currentAccountKey,- maxConnections:- runtimeContext === null- ? null- : readMaxBackgroundGatewayConnections(- runtimeContext.runtime.features.max_background_gateway_connections,- ),- accessRevision: AccountAccess.revision,- accounts,- };- },- () => this.sync(),- {equals: compareStructural, fireImmediately: true},- ),- ),- );- const onlineListener = () => this.resumeAfterConnectivityChange();- window.addEventListener('online', onlineListener);- this.disposers.push(() => window.removeEventListener('online', onlineListener));- }-- shutdown(): void {- this.bootstrapped = false;- this.syncRevision += 1;- this.propertiesGeneration += 1;- this.propertiesPromise = null;- this.properties = null;- this.protectedAccountKeys.clear();- this.clearRetry();- this.clearResumeTimers();- const disposers = this.disposers;- this.disposers = [];- for (const dispose of disposers) {- dispose();- }- for (const accountKey of BackgroundGatewaySessions.keys()) {- this.stop(accountKey);- }- }-- protect(accountKey: string): void {- if (!this.protectedAccountKeys.has(accountKey)) {- this.protectedAccountKeys.add(accountKey);- this.invalidateSync();- }- }-- unprotect(accountKey: string): void {- this.protectedAccountKeys.delete(accountKey);- }-- invalidateSync(): number {- this.syncRevision += 1;- return this.syncRevision;- }-- isCurrentSync(revision: number): boolean {- return this.bootstrapped && revision === this.syncRevision;- }-- find(accountKey: string): BackgroundGatewaySession | null {- return BackgroundGatewaySessions.get(accountKey);- }-- stop(accountKey: string): void {- const session = BackgroundGatewaySessions.get(accountKey);- if (session === null) {- return;- }- BackgroundGatewaySessions.delete(accountKey);- session.stop();- }-- adopt(accountKey: string, session: BackgroundGatewaySession): void {- this.stop(accountKey);- BackgroundGatewaySessions.set(accountKey, session);- }-- detachRegistration(accountKey: string): boolean {- return BackgroundGatewaySessions.delete(accountKey);- }-- async preloadProperties(): Promise<GatewaySocketProperties> {- if (this.properties !== null) {- return this.properties;- }- if (this.propertiesPromise === null) {- const generation = this.propertiesGeneration;- this.propertiesPromise = getGatewayClientProperties()- .then((properties) => {- if (generation !== this.propertiesGeneration) {- throw new Error('Background gateway client metadata request was superseded');- }- this.properties = properties;- return properties;- })- .catch((error: unknown) => {- if (generation === this.propertiesGeneration) {- this.propertiesPromise = null;- }- throw normalizeBackgroundStartError(error);- });- }- return this.propertiesPromise;- }-- sync(): void {- if (- !this.bootstrapped ||- !this.isTransportAvailable() ||- SessionManager.isSwitching ||- AccountScopedWork.isSuspended- ) {- return;- }- const revision = this.invalidateSync();- const runtimeContext = readAuthenticatedRuntimeContext();- if (runtimeContext === null) {- this.clearRetry();- for (const accountKey of BackgroundGatewaySessions.keys()) {- this.stop(accountKey);- }- this.pruneSnapshots([]);- return;- }- const {desired, unresolved} = selectBackgroundAccounts({- accounts: SessionManager.accounts,- currentAccountKey: SessionManager.currentAccountKey,- maxConnections: readMaxBackgroundGatewayConnections(- runtimeContext.runtime.features.max_background_gateway_connections,- ),- });- for (const accountKey of BackgroundGatewaySessions.keys()) {- if (this.protectedAccountKeys.has(accountKey) || unresolved.has(accountKey)) {- continue;- }- const account = desired.get(accountKey);- const session = BackgroundGatewaySessions.get(accountKey);- if (session?.hasPendingAuthMutation) {- continue;- }- if (account === undefined || session === null || backgroundSessionNeedsRestart(session.account, account)) {- this.stop(accountKey);- }- }- for (const [accountKey, account] of desired) {- if (this.protectedAccountKeys.has(accountKey) || BackgroundGatewaySessions.has(accountKey)) {- continue;- }- void this.startSession(accountKey, account, revision);- }- this.scheduleRetry(desired);- this.pruneSnapshots(desired.keys());- }-- private pruneSnapshots(desiredAccountKeys: Iterable<string>): void {- const knownAccountKeys = new Set<string>([- ...BackgroundGatewaySessions.keys(),- ...desiredAccountKeys,- ...this.protectedAccountKeys,- ]);- const currentAccountKey = SessionManager.currentAccountKey;- if (currentAccountKey !== null) {- knownAccountKeys.add(currentAccountKey);- }- void pruneOrphanedDesktopStateStores([...knownAccountKeys]).catch((error: unknown) => {- logger.warn('Failed to prune orphaned app-shell snapshots', error);- });- }-- private async startSession(accountKey: string, account: Account, revision: number): Promise<void> {- const gatewayEndpoint = gatewayEndpointForAccount(account);- if (gatewayEndpoint === null) {- return;- }- const retryingAfterFailure = AccountAccess.getPhase(accountKey) === AccountAccessPhase.UNAVAILABLE;- if (retryingAfterFailure && Date.now() < AccountAccess.getRetryEligibleAt(accountKey)) {- return;- }- const decision = await AccountAccess.ensureAccountChecked(- accountKey,- retryingAfterFailure ? {force: true, resetFailures: false} : {},- );- if (- !this.isCurrentSync(revision) ||- this.protectedAccountKeys.has(accountKey) ||- decision !== AccountAccessDecision.ALLOWED- ) {- return;- }- let properties: GatewaySocketProperties;- try {- properties = await this.preloadProperties();- } catch (error) {- logger.warn('Failed to gather client metadata for a background gateway session', error);- AccountAccess.markGatewayUnavailable(accountKey, normalizeBackgroundStartError(error));- return;- }- if (- !this.isCurrentSync(revision) ||- this.protectedAccountKeys.has(accountKey) ||- BackgroundGatewaySessions.has(accountKey)- ) {- return;- }- const session = new BackgroundGatewaySession({- account,- gatewayEndpoint,- properties,- onStopRequested: () => this.stop(accountKey),- });- BackgroundGatewaySessions.set(accountKey, session);- session.connect();- }-- private scheduleRetry(desired: ReadonlyMap<string, Account>): void {- this.clearRetry();- const now = Date.now();- let retryAt = Number.POSITIVE_INFINITY;- for (const accountKey of desired.keys()) {- if (this.protectedAccountKeys.has(accountKey) || BackgroundGatewaySessions.has(accountKey)) {- continue;- }- if (AccountAccess.getPhase(accountKey) !== AccountAccessPhase.UNAVAILABLE) {- continue;- }- const retryEligibleAt = AccountAccess.getRetryEligibleAt(accountKey);- if (retryEligibleAt > now) {- retryAt = Math.min(retryAt, retryEligibleAt);- }- }- if (!Number.isFinite(retryAt)) {- return;- }- this.retryTimer = window.setTimeout(() => {- this.retryTimer = null;- this.sync();- }, retryAt - now);- }-- private clearRetry(): void {- if (this.retryTimer !== null) {- clearTimeout(this.retryTimer);- this.retryTimer = null;- }- }-- private resumeAfterConnectivityChange(): void {- this.clearResumeTimers();- const sessions = BackgroundGatewaySessions.values();- for (let index = 0; index < sessions.length; index += 1) {- const session = sessions[index];- const timer = window.setTimeout(() => {- this.resumeTimers.delete(timer);- session.probeAfterResume();- }, index * BACKGROUND_RESUME_STAGGER_MS);- this.resumeTimers.add(timer);- }- }-- private clearResumeTimers(): void {- for (const timer of this.resumeTimers) {- clearTimeout(timer);- }- this.resumeTimers.clear();- }-}diff --git a/fluxer_app/src/features/gateway/transport/DesktopBackgroundGateway.ts b/fluxer_app/src/features/gateway/transport/DesktopBackgroundGateway.tsdeleted file mode 100644index 01a6930eb..000000000--- a/fluxer_app/src/features/gateway/transport/DesktopBackgroundGateway.ts+++ /dev/null@@ -1,20 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {setAccountMentionCountSource} from '@app/features/auth/components/accounts/account_switcher_modal/AccountMentionCounts';-import BackgroundGatewaySessions from '@app/features/gateway/transport/BackgroundGatewayConnectionRegistry';--class DesktopBackgroundGateway {- get totalMentionCount(): number {- return BackgroundGatewaySessions.totalMentionCount;- }-- getAccountMentionCount(accountKey: string): number {- return BackgroundGatewaySessions.getAccountMentionCount(accountKey);- }-}--const DesktopBackgroundGatewaySurface = new DesktopBackgroundGateway();--setAccountMentionCountSource(DesktopBackgroundGatewaySurface);--export default DesktopBackgroundGatewaySurface;diff --git a/fluxer_app/src/features/gateway/transport/GatewayConnectionRole.ts b/fluxer_app/src/features/gateway/transport/GatewayConnectionRole.tsdeleted file mode 100644index f64655874..000000000--- a/fluxer_app/src/features/gateway/transport/GatewayConnectionRole.ts+++ /dev/null@@ -1,8 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--export const GatewayConnectionRole = Object.freeze({- FOREGROUND: 'foreground',- BACKGROUND: 'background',-} as const);--export type GatewayConnectionRole = (typeof GatewayConnectionRole)[keyof typeof GatewayConnectionRole];