Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

refactor(app): resume gateway on handoff, release subscriptions

Hampuse58dcc849d76
diff --git a/fluxer_app/src/features/gateway/transport/GatewaySocket.ts b/fluxer_app/src/features/gateway/transport/GatewaySocket.ts
index bd8fe8c3f..2b2d211c5 100644
--- a/fluxer_app/src/features/gateway/transport/GatewaySocket.ts
+++ b/fluxer_app/src/features/gateway/transport/GatewaySocket.ts
@@ -5,7 +5,6 @@ import {
GatewayCompression,
isGatewayCompressionError,
} from '@app/features/gateway/transport/GatewayCompression';
-import {GatewayConnectionRole} from '@app/features/gateway/transport/GatewayConnectionRole';
import {
DISPATCH_FLUSH_DELAY_MS,
DISPATCH_IDLE_RETRY_TIMEOUT_MS,
@@ -15,6 +14,11 @@ import {
shouldRetryIdleWait,
shouldSkipIdleWait,
} from '@app/features/gateway/transport/GatewayDispatchScheduling';
+import {
+ type GatewayGuildSubscriptions,
+ GatewaySubscriptionLedger,
+ type GatewaySubscriptionRelease,
+} from '@app/features/gateway/transport/GatewaySubscriptionLedger';
import {
formatGatewayReadyTimings,
type GatewayTimings,
@@ -30,7 +34,6 @@ import {
type GatewayWireTransport,
} from '@app/features/gateway/transport/GatewayWireTransport';
import {Logger, LogLevel} from '@app/features/platform/utils/AppLogger';
-import {ExponentialBackoff} from '@app/features/platform/utils/RetryScheduler';
import type {GatewayCustomStatusPayload} from '@app/features/user/state/CustomStatus';
import type {GatewayErrorCode} from '@fluxer/constants/src/GatewayConstants';
import {GatewayCloseCodes, GatewayOpcodes} from '@fluxer/constants/src/GatewayConstants';
@@ -86,7 +89,7 @@ export interface GatewaySocketProperties {
longitude?: string;
}
-export interface GatewayPresence {
+interface GatewayPresence {
status: string;
afk: boolean;
mobile: boolean;
@@ -112,7 +115,7 @@ export interface GatewayVoiceSignalParams {
data: object;
}
-export const VOICE_SIGNAL_MAX_JSON_BYTES = 16000;
+const VOICE_SIGNAL_MAX_JSON_BYTES = 16000;
export const VoiceSignalSendResult = {
Sent: 'sent',
@@ -132,15 +135,16 @@ export interface GatewaySocketOptions {
initialGuildId?: string | null;
isMobileLayout: () => boolean;
geo: () => {latitude: string | null; longitude: string | null};
- role: GatewayConnectionRole;
+ logName?: string;
}
-export interface GatewaySocketOwnership {
- readonly role: GatewayConnectionRole;
- readonly presence: GatewayPresence | undefined;
- readonly initialGuildId: string | null;
- readonly isMobileLayout: () => boolean;
- readonly geo: () => {latitude: string | null; longitude: string | null};
+export interface GatewayResumeSeed {
+ readonly sessionId: string;
+ readonly sequence: number;
+}
+
+export interface GatewayHandoffSeed extends GatewayResumeSeed {
+ readonly release: GatewaySubscriptionRelease | null;
}
interface GatewayResumeProbeOptions {
@@ -219,6 +223,7 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
private removeSocketMessageListener: (() => void) | null = null;
private connectionState: GatewayState = GatewayState.Disconnected;
private activeSessionId: string | null = null;
+ private readonly subscriptionLedger = new GatewaySubscriptionLedger();
private lastSequenceNumber = 0;
private lastReconnectAt = 0;
private connectStartedAt = 0;
@@ -252,11 +257,7 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
private readonly gatewayUrlWrapper?: (url: string) => string,
) {
super();
- this.log = new Logger('Gateway');
- this.reconnectBackoff = new ExponentialBackoff({
- minDelay: GATEWAY_TIMEOUTS.MinReconnect,
- maxDelay: GATEWAY_TIMEOUTS.MaxReconnect,
- });
+ this.log = new Logger(options.logName ?? 'Gateway');
}
private emitDeferred<K extends keyof GatewaySocketEvents>(event: K, ...args: GatewaySocketEventArgs<K>): void {
@@ -658,25 +659,10 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
});
}
- updateGuildSubscriptions(params: {
- subscriptions: Record<
- string,
- {
- active?: boolean;
- member_list_channels?: Record<string, Array<[number, number]>>;
- typing?: boolean;
- members?: Array<string>;
- sync?: boolean;
- threads?: boolean;
- thread_member_lists?: Array<string>;
- }
- >;
- }): void {
+ updateGuildSubscriptions(params: {subscriptions: GatewayGuildSubscriptions}): void {
if (!this.isConnected()) return;
- this.sendPayload({
- op: GatewayOpcodes.LAZY_REQUEST,
- d: params,
- });
+ if (!this.sendPayload({op: GatewayOpcodes.LAZY_REQUEST, d: params})) return;
+ this.subscriptionLedger.record(params.subscriptions);
}
requestGuildCounts(guildIds: Array<string>): void {
@@ -720,12 +706,47 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
this.options.token = token;
}
- configureOwnership(ownership: GatewaySocketOwnership): void {
- this.options.role = ownership.role;
- this.options.presence = ownership.presence;
- this.options.initialGuildId = ownership.initialGuildId;
- this.options.isMobileLayout = ownership.isMobileLayout;
- this.options.geo = ownership.geo;
+ seedResume(seed: GatewayResumeSeed): void {
+ if (this.connectionState !== GatewayState.Disconnected || this.socket !== null) {
+ throw new Error('A gateway resume can only be seeded before the socket connects');
+ }
+ if (seed.sessionId.length === 0 || !Number.isSafeInteger(seed.sequence) || seed.sequence < 0) {
+ throw new Error('A gateway resume seed needs a session id and a non-negative sequence');
+ }
+ this.clearSession();
+ this.activeSessionId = seed.sessionId;
+ this.lastSequenceNumber = seed.sequence;
+ this.lastGatewayMessageAt = Date.now();
+ }
+
+ closeForHandoff(code: number, reason: string): GatewayHandoffSeed | null {
+ this.log.info(`Closing for handoff: [${code}] ${reason}`);
+ const release = this.subscriptionLedger.release();
+ this.isUserInitiatedDisconnect = true;
+ this.shouldReconnectImmediately = false;
+ this.clearHelloTimeout();
+ this.clearResumeTimeout();
+ if (this.reconnectTimeoutId != null) {
+ clearTimeout(this.reconnectTimeoutId);
+ this.reconnectTimeoutId = null;
+ }
+ if (this.invalidSessionTimeoutId != null) {
+ clearTimeout(this.invalidSessionTimeoutId);
+ this.invalidSessionTimeoutId = null;
+ }
+ this.stopHeartbeat();
+ if (this.socket && this.socket.readyState === GatewayWireReadyState.OPEN) {
+ try {
+ this.socket.close(code, reason);
+ } catch (error) {
+ this.log.error('Error while closing the gateway transport for handoff', error);
+ }
+ }
+ this.teardownSocket();
+ this.updateState(GatewayState.Disconnected);
+ this.flushDeferredEmits();
+ const sessionId = this.activeSessionId;
+ return sessionId === null ? null : {sessionId, sequence: this.lastSequenceNumber, release};
}
getState(): GatewayState {
@@ -756,7 +777,7 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
this.compressionFallbackInProgress = false;
const transport = createGatewayWireTransport(url, {
binaryType: compression !== 'none' ? 'arraybuffer' : 'blob',
- adoptPrebootSocket: this.options.role === GatewayConnectionRole.FOREGROUND,
+ adoptPrebootSocket: true,
});
this.socket = transport;
transport.on('open', this.handleSocketOpen);
@@ -963,6 +984,7 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
session_id: string;
};
this.activeSessionId = data.session_id;
+ this.subscriptionLedger.clear();
this.resetHeartbeatHistory();
this.resetBackoffUnlessDispatchesKeepFailing();
this.updateState(GatewayState.Connected);
@@ -1307,6 +1329,7 @@ export class GatewaySocket extends EventEmitter<GatewaySocketEvents> {
private clearSession(): void {
const hadSession = Boolean(this.activeSessionId);
this.activeSessionId = null;
+ this.subscriptionLedger.clear();
this.lastSequenceNumber = 0;
this.lastGatewayMessageAt = null;
this.dispatchGeneration += 1;
diff --git a/fluxer_app/src/features/gateway/transport/GatewaySubscriptionLedger.ts b/fluxer_app/src/features/gateway/transport/GatewaySubscriptionLedger.ts
new file mode 100644
index 000000000..9ebdda290
--- /dev/null
+++ b/fluxer_app/src/features/gateway/transport/GatewaySubscriptionLedger.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+interface GatewayGuildSubscription {
+ active?: boolean;
+ member_list_channels?: Record<string, Array<[number, number]>>;
+ typing?: boolean;
+ members?: Array<string>;
+ sync?: boolean;
+ threads?: boolean;
+ thread_member_lists?: Array<string>;
+ focused_channel_id?: string | null;
+}
+
+export type GatewayGuildSubscriptions = Record<string, GatewayGuildSubscription>;
+
+interface GatewayGuildSubscriptionRelease {
+ member_list_channels?: Record<string, []>;
+ members?: [];
+ threads?: false;
+ thread_member_lists?: [];
+ focused_channel_id?: null;
+}
+
+export type GatewaySubscriptionRelease = Record<string, GatewayGuildSubscriptionRelease>;
+
+interface MemberListSubscription {
+ readonly guildId: string;
+ readonly channelId: string;
+}
+
+export class GatewaySubscriptionLedger {
+ private memberList: MemberListSubscription | null = null;
+ private readonly memberGuilds = new Set<string>();
+ private readonly threadGuilds = new Set<string>();
+ private readonly focusedGuilds = new Set<string>();
+
+ record(subscriptions: GatewayGuildSubscriptions): void {
+ for (const [guildId, subscription] of Object.entries(subscriptions)) {
+ for (const [channelId, ranges] of Object.entries(subscription.member_list_channels ?? {})) {
+ if (ranges.length > 0) {
+ this.memberList = {guildId, channelId};
+ } else if (this.memberList?.guildId === guildId && this.memberList.channelId === channelId) {
+ this.memberList = null;
+ }
+ }
+ if (subscription.members !== undefined) {
+ toggle(this.memberGuilds, guildId, subscription.members.length > 0);
+ }
+ if (subscription.threads === false) {
+ this.threadGuilds.delete(guildId);
+ } else if (subscription.threads === true || (subscription.thread_member_lists?.length ?? 0) > 0) {
+ this.threadGuilds.add(guildId);
+ }
+ if (subscription.focused_channel_id !== undefined) {
+ toggle(this.focusedGuilds, guildId, subscription.focused_channel_id !== null);
+ }
+ }
+ }
+
+ release(): GatewaySubscriptionRelease | null {
+ const release: GatewaySubscriptionRelease = {};
+ const entry = (guildId: string): GatewayGuildSubscriptionRelease => {
+ release[guildId] ??= {};
+ return release[guildId];
+ };
+ if (this.memberList !== null) {
+ entry(this.memberList.guildId).member_list_channels = {[this.memberList.channelId]: []};
+ }
+ for (const guildId of this.memberGuilds) {
+ entry(guildId).members = [];
+ }
+ for (const guildId of this.threadGuilds) {
+ Object.assign(entry(guildId), {threads: false, thread_member_lists: []});
+ }
+ for (const guildId of this.focusedGuilds) {
+ entry(guildId).focused_channel_id = null;
+ }
+ return Object.keys(release).length === 0 ? null : release;
+ }
+
+ clear(): void {
+ this.memberList = null;
+ this.memberGuilds.clear();
+ this.threadGuilds.clear();
+ this.focusedGuilds.clear();
+ }
+}
+
+function toggle(set: Set<string>, value: string, present: boolean): void {
+ if (present) {
+ set.add(value);
+ } else {
+ set.delete(value);
+ }
+}
diff --git a/fluxer_app/src/features/gateway/transport/PooledGatewayConnection.ts b/fluxer_app/src/features/gateway/transport/PooledGatewayConnection.ts
index 03855d737..730816297 100644
--- a/fluxer_app/src/features/gateway/transport/PooledGatewayConnection.ts
+++ b/fluxer_app/src/features/gateway/transport/PooledGatewayConnection.ts
@@ -3,13 +3,13 @@
import GeoIP from '@app/features/app/state/GeoIP';
import Initialization from '@app/features/app/state/Initialization';
import InstanceSnapshotStore, {runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';
+import {ResettableStates} from '@app/features/app/state/ResettableStates';
import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
import RuntimeCrash from '@app/features/app/state/RuntimeCrash';
+import {resolveAccountInstanceLabel} from '@app/features/auth/AccountDisplayUtils';
import AccountAccess from '@app/features/auth/state/AccountAccess';
import Authentication from '@app/features/auth/state/Authentication';
-import ChannelFrecency from '@app/features/channel/state/ChannelFrecency';
import Channels from '@app/features/channel/state/Channels';
-import FavoriteMemes from '@app/features/expressions/state/FavoriteMemes';
import ForumPosts from '@app/features/forum/state/ForumPosts';
import ForumReadState from '@app/features/forum/state/ForumReadState';
import {scheduleAccountReadyWork} from '@app/features/gateway/events/AccountReadyWork';
@@ -24,10 +24,8 @@ import {
GatewayAuthenticationFailedError,
} from '@app/features/gateway/transport/ForegroundGatewayConnectionFailure';
import {ForegroundGatewayDispatchProcessor} from '@app/features/gateway/transport/ForegroundGatewayDispatchProcessor';
-import {ForegroundPromotionReplayBuffer} from '@app/features/gateway/transport/ForegroundPromotionReplayBuffer';
import type {CompressionType} from '@app/features/gateway/transport/GatewayCompression';
import {GatewayConnectionInterruption} from '@app/features/gateway/transport/GatewayConnectionInterruption';
-import {GatewayConnectionRole} from '@app/features/gateway/transport/GatewayConnectionRole';
import {GatewayGuildSubscriptionSynchronizer} from '@app/features/gateway/transport/GatewayGuildSubscriptionSynchronizer';
import {
GatewayReadinessWaiters,
@@ -41,16 +39,15 @@ import {
import {
type GatewayDispatchDelivery,
type GatewayErrorData,
+ type GatewayHandoffSeed,
+ type GatewayResumeSeed,
GatewaySocket,
type GatewaySocketProperties,
GatewayState,
type GatewayVoiceStateUpdateParams,
} from '@app/features/gateway/transport/GatewaySocket';
import {selectGuildActivationTarget} from '@app/features/gateway/transport/GuildActivationTarget';
-import MemberSearch from '@app/features/member/state/MemberSearch';
-import AttachmentUrlRefresher from '@app/features/messaging/state/AttachmentUrlRefresher';
import Messages from '@app/features/messaging/state/MessagingMessages';
-import ReportFlows from '@app/features/moderation/state/ReportFlows';
import Navigation from '@app/features/navigation/state/Navigation';
import NavigationSideEffects from '@app/features/navigation/state/NavigationSideEffects';
import SelectedGuild from '@app/features/navigation/state/SelectedGuild';
@@ -60,12 +57,7 @@ import {ResetClientStateReason, resetClientState} from '@app/features/platform/s
import {Logger} from '@app/features/platform/utils/AppLogger';
import {getGatewayClientProperties} from '@app/features/platform/utils/ClientInfo';
import LocalPresence from '@app/features/presence/state/LocalPresence';
-import Presence from '@app/features/presence/state/Presence';
import QuickSwitcher from '@app/features/search/state/QuickSwitcher';
-import ChannelThreads from '@app/features/threads/state/ChannelThreads';
-import ThreadGuilds from '@app/features/threads/state/ThreadGuilds';
-import ThreadPanel from '@app/features/threads/state/ThreadPanel';
-import ThreadRoster from '@app/features/threads/state/ThreadRoster';
import ThreadSubscriptions from '@app/features/threads/state/ThreadSubscriptions';
import RollingTypingStore from '@app/features/typing/rolling/RollingTypingStore';
import LayerManager from '@app/features/ui/state/LayerManager';
@@ -77,6 +69,20 @@ import {action, actionBound, makeAutoObservable, observableRef, runInAction} fro
const logger = new Logger('GatewayConnection');
+function gatewayLogName(accountKey: string | null): string {
+ const account = accountKey === null ? null : SessionManager.getAccount(accountKey);
+ const host = account === null ? null : resolveAccountInstanceLabel(account);
+ if (account === null || host === null) {
+ const webAppEndpoint = RuntimeConfig.webAppEndpoint;
+ return URL.canParse(webAppEndpoint) ? `Gateway ${new URL(webAppEndpoint).host}` : 'Gateway';
+ }
+ const username = account.userData?.username;
+ const sharesInstance = SessionManager.accounts.some(
+ (other) => other.storageKey !== account.storageKey && resolveAccountInstanceLabel(other) === host,
+ );
+ return sharesInstance && username ? `Gateway ${host} ${username}` : `Gateway ${host}`;
+}
+
const FOREGROUND_SOCKET_EVENTS = [
'dispatch',
'disconnect',
@@ -87,14 +93,14 @@ const FOREGROUND_SOCKET_EVENTS = [
'resumed',
] as const;
-export class GatewaySessionSupersededError extends Error {
+class GatewaySessionSupersededError extends Error {
constructor() {
super('Gateway session was superseded before it became ready');
this.name = 'GatewaySessionSupersededError';
}
}
-export class GatewaySessionStartFailedError extends Error {
+class GatewaySessionStartFailedError extends Error {
constructor(status: GatewaySessionStartStatus) {
super(`Gateway session did not start: ${status}`);
this.name = 'GatewaySessionStartFailedError';
@@ -142,9 +148,8 @@ interface GatewayAuthenticationFailure {
readonly completion: Promise<void>;
}
-export interface ForegroundSocketAdoptionMeta {
- readonly accountKey: string;
- readonly sessionId: string;
+export interface GatewaySessionStartOptions {
+ readonly resume?: GatewayResumeSeed;
}
export function selectForegroundActivationGuildId(): string | null {
@@ -172,7 +177,6 @@ export class PooledGatewayConnection {
private readonly dispatchProcessor: ForegroundGatewayDispatchProcessor;
private readonly resumeListeners: GatewayResumeListenerOwner;
private readonly demotionHandover: ForegroundDemotionHandover;
- private readonly promotionReplay: ForegroundPromotionReplayBuffer;
private readonly readinessWaiters: GatewayReadinessWaiters;
private readonly guildSubscriptions: GatewayGuildSubscriptionSynchronizer;
private readonly connectionInterruption: GatewayConnectionInterruption;
@@ -181,6 +185,7 @@ export class PooledGatewayConnection {
private desired: DesiredSession | null = null;
private authenticationFailure: GatewayAuthenticationFailure | null = null;
private previousReadySessionId: string | null = null;
+ private promotedResumeAccountKey: string | null = null;
private isFatalCrashInProgress: boolean = false;
constructor() {
@@ -205,7 +210,6 @@ export class PooledGatewayConnection {
persistAccountToken: (accountKey, token) => SessionManager.setAccountToken(accountKey, token),
getAccountToken: (accountKey) => SessionManager.getAccount(accountKey)?.token ?? null,
});
- this.promotionReplay = new ForegroundPromotionReplayBuffer();
this.readinessWaiters = new GatewayReadinessWaiters((generation, accountKey, error) => {
this.handleReadyTimeout(generation, accountKey, error);
});
@@ -221,7 +225,7 @@ export class PooledGatewayConnection {
| 'dispatchProcessor'
| 'resumeListeners'
| 'demotionHandover'
- | 'promotionReplay'
+ | 'promotedResumeAccountKey'
| 'readinessWaiters'
| 'guildSubscriptions'
| 'connectionInterruption'
@@ -242,7 +246,7 @@ export class PooledGatewayConnection {
dispatchProcessor: false,
resumeListeners: false,
demotionHandover: false,
- promotionReplay: false,
+ promotedResumeAccountKey: false,
readinessWaiters: false,
guildSubscriptions: false,
connectionInterruption: false,
@@ -349,7 +353,7 @@ export class PooledGatewayConnection {
private cleanupSocket(): void {
const owner = this.socketOwner;
this.demotionHandover.clear();
- this.promotionReplay.clear();
+ this.promotedResumeAccountKey = null;
this.socketOwner = null;
this.isConnected = false;
this.isConnecting = false;
@@ -385,8 +389,8 @@ export class PooledGatewayConnection {
return true;
}
- async consumeForegroundDemotionHandover(accountKey: string): Promise<boolean> {
- return this.demotionHandover.consume(accountKey);
+ async finishForegroundDemotionHandover(accountKey: string): Promise<GatewayHandoffSeed | null> {
+ return this.demotionHandover.finish(accountKey);
}
async rollbackForegroundDemotionHandover(accountKey: string): Promise<void> {
@@ -430,120 +434,13 @@ export class PooledGatewayConnection {
}
}
- detachForegroundSocket(): GatewaySocket | null {
- if (this.demotionHandover.isActive) {
- throw new Error('Foreground gateway socket cannot detach during an active demotion handover');
- }
- const owner = this.socketOwner;
- if (owner === null) {
- return null;
- }
- this.generation += 1;
- for (const event of FOREGROUND_SOCKET_EVENTS) {
- owner.socket.removeAllListeners(event);
- }
- this.resumeListeners.dispose();
- this.socketOwner = null;
- this.connectionInterruption.restore();
- this.rejectReadyWaiters(new GatewaySessionSupersededError());
- this.resetConnectionLocalState();
- this.guildSubscriptions.clearInitialGuild();
- this.previousReadySessionId = null;
- this.promotionReplay.clear();
- return owner.socket;
- }
-
- adoptForegroundSocket(socket: GatewaySocket, meta: ForegroundSocketAdoptionMeta): void {
- if (this.socketOwner !== null) {
- throw new Error('Foreground gateway socket adoption requires an empty owner');
- }
- if (SessionManager.currentAccountKey !== meta.accountKey) {
- throw new Error('Foreground gateway socket adoption does not match the active account');
- }
- if (socket.getSessionId() !== meta.sessionId || !socket.isConnected()) {
- throw new Error('Foreground gateway socket adoption requires its live session');
- }
- const token = SessionManager.token;
- if (token === null) {
- throw new Error('Foreground gateway socket adoption requires an active token');
- }
- LocalPresence.updatePresence();
- const presence = LocalPresence.getGatewayPresence();
- socket.setToken(token);
- socket.configureOwnership({
- role: GatewayConnectionRole.FOREGROUND,
- presence:
- presence === null
- ? undefined
- : {
- status: presence.status,
- afk: presence.afk,
- mobile: presence.mobile,
- custom_status: presence.custom_status,
- },
- initialGuildId: null,
- isMobileLayout: () => MobileLayout.isMobileLayout(),
- geo: () => ({latitude: GeoIP.latitude, longitude: GeoIP.longitude}),
- });
- const generation = ++this.generation;
- this.socketOwner = {socket, accountKey: meta.accountKey};
- this.desired = {accountKey: meta.accountKey, token, userIdHint: SessionManager.userId};
- this.sessionId = meta.sessionId;
- this.previousReadySessionId = meta.sessionId;
- this.connectionEpoch += 1;
- this.isConnected = true;
- this.isConnecting = false;
- this.isReady = false;
- this.connectionInterruption.restore();
- this.guildSubscriptions.prepareAdoptedSession();
- this.promotionReplay.begin(meta.accountKey, socket);
- this.installSocketWiring(socket, generation, meta.accountKey);
- }
-
preparePromotedForegroundReplay(): void {
- this.resetEphemeralForegroundStates();
Initialization.setConnecting();
}
- replayForegroundDispatch(accountKey: string, delivery: GatewayDispatchDelivery): void {
- const socket = this.foregroundSocketForAccount(accountKey);
- if (socket === null) {
- throw new Error('Cannot replay a gateway dispatch without its account-owned foreground socket');
- }
- const isCurrent = (): boolean => this.foregroundSocketForAccount(accountKey) === socket;
- if (!socket.isDispatchActive(delivery.receipt)) {
- throw new Error('Cannot replay an inactive gateway dispatch receipt');
- }
- this.handleGatewayDispatch(socket, delivery, accountKey, isCurrent);
- if (!socket.isConnected()) {
- throw new Error('Foreground gateway disconnected while replaying a dispatch');
- }
- if (socket.isDispatchActive(delivery.receipt)) {
- throw new Error('Foreground gateway dispatch replay did not complete its receipt');
- }
- }
-
- finalizePromotedForegroundSession(accountKey: string): void {
- const socket = this.foregroundSocketForAccount(accountKey);
- if (socket === null || !socket.isConnected()) {
- throw new Error('Cannot finalize a promoted foreground gateway without its live socket');
- }
- const sessionId = socket.getSessionId();
- if (sessionId === null || sessionId !== this.sessionId) {
- throw new Error('Cannot finalize a promoted foreground gateway with a mismatched session');
- }
- const isCurrent = (): boolean => this.foregroundSocketForAccount(accountKey) === socket;
- this.promotionReplay.drain(accountKey, socket, (delivery) => {
- if (!socket.isDispatchActive(delivery.receipt)) {
- throw new Error('Cannot finalize a promoted foreground gateway with an inactive live dispatch');
- }
- this.handleGatewayDispatch(socket, delivery, accountKey, isCurrent);
- if (!socket.isConnected() || socket.isDispatchActive(delivery.receipt)) {
- throw new Error('Promoted foreground gateway failed while draining live dispatches');
- }
- });
- SessionManager.handleConnectionStarted();
- this.handleConnectionOpen(sessionId);
+ private completePromotedResume(accountKey: string, socket: GatewaySocket): void {
+ this.promotedResumeAccountKey = null;
+ this.previousReadySessionId = socket.getSessionId();
this.completeGatewayReady(accountKey);
Initialization.setReady();
Messages.handleGatewayReady();
@@ -554,10 +451,6 @@ export class PooledGatewayConnection {
if (userId !== null) {
scheduleAccountReadyWork(userId);
}
- const presence = LocalPresence.getGatewayPresence();
- if (presence !== null) {
- socket.updatePresence(presence.status, presence.afk, presence.mobile, presence.custom_status);
- }
}
private createGatewaySocket(
@@ -574,6 +467,7 @@ export class PooledGatewayConnection {
let identifyFlags = 0;
identifyFlags |= GatewayIdentifyFlags.DEBOUNCE_MESSAGE_REACTIONS;
identifyFlags |= GatewayIdentifyFlags.CHANNEL_THREADS;
+ identifyFlags |= GatewayIdentifyFlags.GUILD_VISITS;
const initialGuildId = SelectedGuild.selectedGuildId ?? null;
this.guildSubscriptions.recordInitialGuild(initialGuildId);
const socket = new GatewaySocket(gatewayUrl, {
@@ -593,7 +487,7 @@ export class PooledGatewayConnection {
initialGuildId,
isMobileLayout: () => MobileLayout.isMobileLayout(),
geo: () => ({latitude: GeoIP.latitude, longitude: GeoIP.longitude}),
- role: GatewayConnectionRole.FOREGROUND,
+ logName: gatewayLogName(accountKey),
});
this.installSocketWiring(socket, generation, accountKey);
return socket;
@@ -612,9 +506,6 @@ export class PooledGatewayConnection {
socket.on(
'dispatch',
whenCurrent((delivery: GatewayDispatchDelivery) => {
- if (this.promotionReplay.capture(socket, accountKey, delivery)) {
- return;
- }
this.handleGatewayDispatch(socket, delivery, accountKey, isCurrent);
}),
);
@@ -651,11 +542,28 @@ export class PooledGatewayConnection {
const readyData = data as {
session_id: string;
};
+ if (this.promotedResumeAccountKey === accountKey) {
+ this.promotedResumeAccountKey = null;
+ }
this.handleConnectionOpen(readyData.session_id);
}),
),
);
- socket.on('resumed', action(whenCurrent(() => this.handleConnectionResumed())));
+ socket.on(
+ 'resumed',
+ action(
+ whenCurrent(() => {
+ const promoted = accountKey !== null && this.promotedResumeAccountKey === accountKey;
+ if (promoted) {
+ this.sessionId = socket.getSessionId();
+ }
+ this.handleConnectionResumed();
+ if (promoted) {
+ this.completePromotedResume(accountKey, socket);
+ }
+ }),
+ ),
+ );
}
private handleSocketStateChange(newState: GatewayState, previousState: GatewayState): void {
@@ -716,7 +624,10 @@ export class PooledGatewayConnection {
this.guildSubscriptions.flush();
}
- async startSession(accountKey: string | null): Promise<GatewaySessionStartResult> {
+ async startSession(
+ accountKey: string | null,
+ options: GatewaySessionStartOptions = {},
+ ): Promise<GatewaySessionStartResult> {
const userIdHint = SessionManager.userId ?? null;
const storedToken = SessionManager.token;
const desired: DesiredSession = {
@@ -735,7 +646,11 @@ export class PooledGatewayConnection {
this.desired = desired;
const generation = ++this.generation;
this.rejectReadyWaiters(new GatewaySessionSupersededError());
- LocalPresence.handleSessionChanging();
+ if (options.resume === undefined) {
+ LocalPresence.handleSessionChanging();
+ } else {
+ LocalPresence.updatePresence();
+ }
if (this.socket !== null) {
this.cleanupSocket();
}
@@ -781,6 +696,11 @@ export class PooledGatewayConnection {
}
});
if (this.socket === socket) {
+ if (options.resume !== undefined && accountKey !== null) {
+ socket.seedResume(options.resume);
+ this.guildSubscriptions.clearInitialGuild();
+ this.promotedResumeAccountKey = accountKey;
+ }
socket.connect();
return {status: GatewaySessionStartStatus.STARTED, generation};
}
@@ -946,22 +866,6 @@ export class PooledGatewayConnection {
return sent;
}
- private resetEphemeralForegroundStates(): void {
- Presence.handleSessionInvalidated();
- Messages.handleSessionInvalidated();
- FavoriteMemes.reset();
- AttachmentUrlRefresher.reset();
- ChannelFrecency.handleLogout();
- MemberSearch.handleLogout();
- ReportFlows.reset();
- ThreadPanel.closeCreate();
- ThreadGuilds.reset();
- ChannelThreads.handleGatewayReady([]);
- ThreadRoster.reset();
- ForumPosts.reset();
- ForumReadState.handleGatewayReady();
- }
-
resetConnectionLocalState(): void {
this.isConnected = false;
this.isConnecting = false;
@@ -998,7 +902,7 @@ export class PooledGatewayConnection {
this.connectionInterruption.restore();
this.cleanupSocket();
this.rejectReadyWaiters(new GatewaySessionSupersededError());
- this.resetEphemeralForegroundStates();
+ ResettableStates.resetAll();
this.resetConnectionLocalState();
}