Skip to content

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

TypeScript fluxerfluxerapp

refactor(app): sync account snapshots through the account engine

Hampus3e729ee7f799
diff --git a/fluxer_app/src/features/gateway/snapshot/SnapshotHydration.ts b/fluxer_app/src/features/gateway/snapshot/SnapshotHydration.ts
index e21a58d07..4a741fab8 100644
--- a/fluxer_app/src/features/gateway/snapshot/SnapshotHydration.ts
+++ b/fluxer_app/src/features/gateway/snapshot/SnapshotHydration.ts
@@ -24,10 +24,7 @@ import {
type SnapshotUserRow,
snapshotUserKey,
} from '@app/features/gateway/snapshot/SnapshotEntities';
-import SnapshotSync, {
- disposeAndEvictDesktopSnapshot,
- isDesktopSnapshotAvailable,
-} from '@app/features/gateway/snapshot/SnapshotSync';
+import SnapshotSync from '@app/features/gateway/snapshot/SnapshotSync';
import type {StateSnapshotEntries, StateSyncCursor} from '@app/features/gateway/snapshot/SnapshotTypes';
import type {GuildReadyData} from '@app/features/gateway/types/GatewayGuildTypes';
import type {VoiceState} from '@app/features/gateway/types/GatewayVoiceTypes';
@@ -86,7 +83,7 @@ interface ParsedSnapshot {
readonly voiceStates: Map<string, ReadonlyArray<VoiceState>>;
}
-export interface SnapshotHydrationDependencies {
+interface SnapshotHydrationDependencies {
readonly readSnapshot: (storageKey: string) => Promise<StateSnapshotEntries> | null;
readonly readCursor: (storageKey: string) => Promise<StateSyncCursor | null> | null;
readonly resolveSelfUserId: (storageKey: string) => string | null | Promise<string | null>;
@@ -108,7 +105,7 @@ const defaultDependencies: SnapshotHydrationDependencies = {
readCursor: (storageKey) => SnapshotSync.readCursor(storageKey),
resolveSelfUserId: (storageKey) => SessionManager.getAccount(storageKey)?.userId ?? null,
resolveCheckedSelfUser: (storageKey) => AccountAccess.getCheckedUser(storageKey),
- evictSnapshot: (storageKey) => disposeAndEvictDesktopSnapshot(storageKey),
+ evictSnapshot: (storageKey) => SnapshotSync.evict(storageKey),
};
let hydrationEpoch = 0;
@@ -290,11 +287,7 @@ function overlayMentionCounts(
return overlaid;
}
-export function captureForegroundMentionCounts(): Map<string, number> {
- return ReadStates.captureMentionCounts();
-}
-
-export async function runSnapshotScopeHydration(
+async function runSnapshotScopeHydration(
storageKey: string,
dependencies: SnapshotHydrationDependencies,
mentionCounts: ReadonlyMap<string, number> | null,
@@ -349,7 +342,7 @@ export async function hydrateStoresFromSnapshotScope(
storageKey: string,
mentionCounts: ReadonlyMap<string, number> | null,
): Promise<void> {
- if (!isDesktopSnapshotAvailable()) {
+ if (!SnapshotSync.enabled) {
throw new SnapshotHydrationUnavailableError(storageKey);
}
try {
diff --git a/fluxer_app/src/features/gateway/snapshot/SnapshotSync.ts b/fluxer_app/src/features/gateway/snapshot/SnapshotSync.ts
index ac4d7dcb3..40e28994c 100644
--- a/fluxer_app/src/features/gateway/snapshot/SnapshotSync.ts
+++ b/fluxer_app/src/features/gateway/snapshot/SnapshotSync.ts
@@ -1,12 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import AccountEngine from '@app/features/account_engine/state/AccountEngine';
import type {ReadyPayload} from '@app/features/gateway/events/GatewayReady';
-import {DiskBackedSnapshotReducer} from '@app/features/gateway/snapshot/DiskBackedSnapshotReducer';
-import {
- assertSnapshotEntriesCapacity,
- InMemorySnapshotStore,
-} from '@app/features/gateway/snapshot/InMemorySnapshotStore';
+import {InMemorySnapshotStore} from '@app/features/gateway/snapshot/InMemorySnapshotStore';
import type {SnapshotDispatch} from '@app/features/gateway/snapshot/SnapshotDispatchEvent';
+import {parseSnapshotEntity, parseSnapshotSingleton} from '@app/features/gateway/snapshot/SnapshotEntities';
import {SnapshotReducer} from '@app/features/gateway/snapshot/SnapshotReducer';
import type {
StateSnapshotCapture,
@@ -14,95 +12,87 @@ import type {
StateSyncCursor,
} from '@app/features/gateway/snapshot/SnapshotTypes';
import {SnapshotWriter} from '@app/features/gateway/snapshot/SnapshotWriter';
-import {isDesktopNativeGatewayTransportAvailable} from '@app/features/gateway/transport/GatewayWireTransport';
import {Logger} from '@app/features/platform/utils/AppLogger';
-export type SnapshotAccountMode = 'foreground' | 'background';
-
interface SnapshotAccount {
- mode: SnapshotAccountMode;
- writer: SnapshotWriter;
- foreground: SnapshotReducer | null;
- background: DiskBackedSnapshotReducer | null;
-}
-
-interface PreparedPromotion {
- readonly storageKey: string;
- readonly entries: StateSnapshotEntries;
+ readonly writer: SnapshotWriter;
readonly reducer: SnapshotReducer;
- readonly account: SnapshotAccount;
- readonly background: DiskBackedSnapshotReducer;
-}
-
-interface CommittedPromotion {
- readonly storageKey: string;
- readonly account: SnapshotAccount;
- readonly retiredBackground: DiskBackedSnapshotReducer;
}
const logger = new Logger('SnapshotSync');
-const snapshotTransportAvailable = isDesktopNativeGatewayTransportAvailable();
+
+function snapshotSyncError(error: unknown): Error {
+ if (error instanceof Error) {
+ return error;
+ }
+ return new Error('Snapshot synchronization failed with a non-error value');
+}
class SnapshotSyncOwner {
private readonly store = new InMemorySnapshotStore();
private readonly accounts = new Map<string, SnapshotAccount>();
- private preparedPromotion: PreparedPromotion | null = null;
- private committedPromotion: CommittedPromotion | null = null;
- applyReady(storageKey: string, data: ReadyPayload, mode: SnapshotAccountMode): void {
- if (!snapshotTransportAvailable) {
+ constructor(private readonly isEnabled: () => boolean) {}
+
+ get enabled(): boolean {
+ return this.isEnabled();
+ }
+
+ applyReady(storageKey: string, data: ReadyPayload): void {
+ if (!this.enabled) {
return;
}
- this.clearPreparedPromotion(storageKey);
try {
- const account = this.ensureAccountForReady(storageKey, mode);
- if (account.mode === 'foreground' && account.foreground != null) {
- const cursor = account.foreground.applyReady(account.writer.enqueue, data);
- account.writer.setCursor(cursor);
- return;
- }
- account.background?.applyReady(data);
+ this.evictOthers(storageKey);
+ const account = this.accounts.get(storageKey) ?? this.createAccount(storageKey, new SnapshotReducer());
+ account.writer.setCursor(account.reducer.applyReady(account.writer.enqueue, data));
} catch (error) {
- this.invalidateStorageKey(storageKey, snapshotSyncError(error));
+ this.invalidate(storageKey, snapshotSyncError(error));
}
}
applyDispatch(storageKey: string, dispatch: SnapshotDispatch): void {
- if (!snapshotTransportAvailable) {
- return;
- }
const account = this.accounts.get(storageKey);
- if (account == null) {
+ if (account === undefined) {
return;
}
- this.clearPreparedPromotion(storageKey);
try {
- if (account.mode === 'foreground' && account.foreground != null) {
- account.foreground.applyDispatch(account.writer.enqueue, dispatch);
- } else {
- account.background?.applyDispatch(dispatch);
- }
+ account.reducer.applyDispatch(account.writer.enqueue, dispatch);
} catch (error) {
- this.invalidateStorageKey(storageKey, snapshotSyncError(error));
+ this.invalidate(storageKey, snapshotSyncError(error));
}
}
- readSnapshot(storageKey: string): Promise<StateSnapshotEntries> | null {
- if (!snapshotTransportAvailable) {
- return null;
+ adoptPromotedSnapshot(storageKey: string, selfUserId: string, capture: StateSnapshotCapture): boolean {
+ if (!this.enabled) {
+ return false;
}
- const prepared = this.preparedPromotion;
- if (prepared?.storageKey === storageKey) {
- return Promise.resolve(prepared.entries);
+ this.evict(storageKey);
+ this.evictOthers(storageKey);
+ try {
+ this.store.load(storageKey, capture);
+ const reducer = new SnapshotReducer();
+ reducer.importShellState({
+ selfUserId,
+ shellUserIds: new Set(parseSnapshotEntity(capture.entries, 'user').keys()),
+ userSettings: parseSnapshotSingleton(capture.entries, 'user_settings'),
+ accountMetadata: parseSnapshotSingleton(capture.entries, 'account_metadata'),
+ });
+ reducer.loadHeavyMapsFromEntries(capture.entries);
+ this.createAccount(storageKey, reducer);
+ return true;
+ } catch (error) {
+ this.invalidate(storageKey, snapshotSyncError(error));
+ return false;
}
+ }
+
+ readSnapshot(storageKey: string): Promise<StateSnapshotEntries> | null {
const entries = this.store.getAll(storageKey);
return entries == null ? null : Promise.resolve(entries);
}
readCursor(storageKey: string): Promise<StateSyncCursor | null> | null {
- if (!snapshotTransportAvailable) {
- return null;
- }
if (!this.store.has(storageKey)) {
return null;
}
@@ -110,280 +100,54 @@ class SnapshotSyncOwner {
}
captureDemotionSnapshot(storageKey: string): StateSnapshotCapture | null {
- if (!snapshotTransportAvailable) {
- return null;
- }
return this.store.capture(storageKey);
}
flush(storageKey: string): Promise<void> {
- if (!snapshotTransportAvailable) {
- return Promise.resolve();
- }
- const account = this.accounts.get(storageKey);
- if (account == null) {
- return Promise.resolve();
- }
- if (account.mode === 'background' && account.background != null) {
- return account.background.flush();
- }
- return account.writer.flush();
+ return this.accounts.get(storageKey)?.writer.flush() ?? Promise.resolve();
}
- private dispose(storageKey: string): void {
+ evict(storageKey: string): void {
const account = this.accounts.get(storageKey);
- if (account != null) {
- account.background?.dispose();
+ if (account !== undefined) {
account.writer.dispose();
this.accounts.delete(storageKey);
}
- this.clearPreparedPromotion(storageKey);
- this.clearCommittedPromotion(storageKey);
- }
-
- demoteForeground(storageKey: string): StateSnapshotCapture | null {
- if (!snapshotTransportAvailable) {
- return null;
- }
- const account = this.accounts.get(storageKey);
- if (account?.mode !== 'foreground' || account.foreground == null) {
- return null;
- }
- const capture = this.store.capture(storageKey);
- if (capture == null) {
- return null;
- }
- const driver = this.createBackgroundDriver(storageKey, account);
- driver.setShellState(account.foreground.exportShellState());
- account.foreground = null;
- account.background = driver;
- account.mode = 'background';
- return capture;
- }
-
- prepareForegroundPromotion(storageKey: string, entries: StateSnapshotEntries): boolean {
- if (!snapshotTransportAvailable) {
- return false;
- }
- if (!this.store.has(storageKey) || this.preparedPromotion !== null || this.committedPromotion !== null) {
- return false;
- }
- const account = this.accounts.get(storageKey);
- const background = account?.mode === 'background' ? account.background : null;
- if (account == null || background == null) {
- return false;
- }
- try {
- assertSnapshotEntriesCapacity(entries);
- const reducer = new SnapshotReducer();
- reducer.loadHeavyMapsFromEntries(entries);
- reducer.importShellState(background.takeShellState());
- this.preparedPromotion = {storageKey, entries, reducer, account, background};
- return true;
- } catch (error) {
- this.invalidateStorageKey(storageKey, snapshotSyncError(error));
- return false;
- }
- }
-
- commitForegroundPromotion(storageKey: string): boolean {
- if (!snapshotTransportAvailable) {
- return false;
- }
- const prepared = this.preparedPromotion;
- if (prepared?.storageKey !== storageKey) {
- return false;
- }
- if (!this.store.has(storageKey)) {
- this.preparedPromotion = null;
- return false;
- }
- if (
- this.committedPromotion !== null ||
- this.accounts.get(storageKey) !== prepared.account ||
- prepared.account.mode !== 'background' ||
- prepared.account.background !== prepared.background
- ) {
- this.preparedPromotion = null;
- return false;
- }
- this.preparedPromotion = null;
- prepared.account.background = null;
- prepared.account.foreground = prepared.reducer;
- prepared.account.mode = 'foreground';
- this.committedPromotion = {
- storageKey,
- account: prepared.account,
- retiredBackground: prepared.background,
- };
- return true;
- }
-
- abortForegroundPromotion(storageKey: string): void {
- this.clearPreparedPromotion(storageKey);
- const committed = this.committedPromotion;
- if (committed?.storageKey !== storageKey) {
- return;
- }
- this.committedPromotion = null;
- committed.retiredBackground.dispose();
- if (this.accounts.get(storageKey) === committed.account) {
- committed.account.foreground = null;
- committed.account.writer.dispose();
- this.accounts.delete(storageKey);
- }
this.store.evict(storageKey);
}
- finalizeForegroundPromotion(storageKey: string): void {
- const committed = this.committedPromotion;
- if (
- committed?.storageKey !== storageKey ||
- this.accounts.get(storageKey) !== committed.account ||
- committed.account.mode !== 'foreground' ||
- committed.account.foreground == null ||
- committed.account.background !== null
- ) {
- throw new Error(`Foreground snapshot finalization rejected ${storageKey}`);
- }
- this.committedPromotion = null;
- committed.retiredBackground.dispose();
- }
-
- evict(storageKey: string): void {
- this.dispose(storageKey);
- this.store.evict(storageKey);
- }
-
- prune(knownStorageKeys: ReadonlyArray<string>): void {
- for (const storageKey of Array.from(this.accounts.keys())) {
- if (!knownStorageKeys.includes(storageKey)) {
- this.dispose(storageKey);
- }
- }
- const preparedStorageKey = this.preparedPromotion?.storageKey;
- if (preparedStorageKey != null && !knownStorageKeys.includes(preparedStorageKey)) {
- this.preparedPromotion = null;
- }
- const committedStorageKey = this.committedPromotion?.storageKey;
- if (committedStorageKey != null && !knownStorageKeys.includes(committedStorageKey)) {
- this.clearCommittedPromotion(committedStorageKey);
- }
- this.store.prune(knownStorageKeys);
- }
-
- private ensureAccountForReady(storageKey: string, mode: SnapshotAccountMode): SnapshotAccount {
- const existing = this.accounts.get(storageKey);
- if (existing != null) {
- if (existing.mode !== mode) {
- this.flipAccountMode(storageKey, existing, mode);
+ private evictOthers(storageKey: string): void {
+ for (const other of Array.from(this.accounts.keys())) {
+ if (other !== storageKey) {
+ this.evict(other);
}
- return existing;
}
- const account = this.createAccount(storageKey, mode, null);
- this.accounts.set(storageKey, account);
- return account;
}
- private createAccount(
- storageKey: string,
- mode: SnapshotAccountMode,
- foregroundSeed: SnapshotReducer | null,
- ): SnapshotAccount {
- let account: SnapshotAccount;
- const onInvalid = (error: Error): void => this.invalidateAccount(storageKey, account, error);
- const writer = new SnapshotWriter({storageKey, store: this.store, onInvalid});
- account = {
- mode,
- writer,
- foreground: mode === 'foreground' ? (foregroundSeed ?? new SnapshotReducer()) : null,
- background: null,
- };
- if (mode === 'background') {
- account.background = this.createBackgroundDriver(storageKey, account);
- }
- return account;
- }
-
- private createBackgroundDriver(storageKey: string, account: SnapshotAccount): DiskBackedSnapshotReducer {
- return new DiskBackedSnapshotReducer({
+ private createAccount(storageKey: string, reducer: SnapshotReducer): SnapshotAccount {
+ const writer = new SnapshotWriter({
storageKey,
store: this.store,
- writer: account.writer,
onInvalid: (error) => this.invalidateAccount(storageKey, account, error),
});
- }
-
- private flipAccountMode(storageKey: string, account: SnapshotAccount, mode: SnapshotAccountMode): void {
- if (mode === 'foreground') {
- account.background?.dispose();
- account.background = null;
- account.foreground = new SnapshotReducer();
- } else {
- account.foreground = null;
- account.background = this.createBackgroundDriver(storageKey, account);
- }
- account.mode = mode;
- }
-
- private clearPreparedPromotion(storageKey: string): void {
- if (this.preparedPromotion?.storageKey === storageKey) {
- this.preparedPromotion = null;
- }
- }
-
- private clearCommittedPromotion(storageKey: string): void {
- if (this.committedPromotion?.storageKey === storageKey) {
- this.committedPromotion.retiredBackground.dispose();
- this.committedPromotion = null;
- }
+ const account: SnapshotAccount = {writer, reducer};
+ this.accounts.set(storageKey, account);
+ return account;
}
private invalidateAccount(storageKey: string, account: SnapshotAccount, error: Error): void {
if (this.accounts.get(storageKey) !== account) {
return;
}
- logger.warn('Invalidating unavailable app-shell snapshot', {storageKey, error});
- account.background?.dispose();
- account.writer.dispose();
- this.accounts.delete(storageKey);
- this.clearPreparedPromotion(storageKey);
- this.clearCommittedPromotion(storageKey);
- this.store.evict(storageKey);
+ this.invalidate(storageKey, error);
}
- private invalidateStorageKey(storageKey: string, error: Error): void {
- const account = this.accounts.get(storageKey);
- if (account != null) {
- this.invalidateAccount(storageKey, account, error);
- return;
- }
+ private invalidate(storageKey: string, error: Error): void {
logger.warn('Invalidating unavailable app-shell snapshot', {storageKey, error});
- this.clearPreparedPromotion(storageKey);
- this.clearCommittedPromotion(storageKey);
- this.store.evict(storageKey);
- }
-}
-
-function snapshotSyncError(error: unknown): Error {
- if (error instanceof Error) {
- return error;
+ this.evict(storageKey);
}
- return new Error('Snapshot synchronization failed with a non-error value');
-}
-
-const snapshotSync = new SnapshotSyncOwner();
-
-export function isDesktopSnapshotAvailable(): boolean {
- return snapshotTransportAvailable;
-}
-
-export async function disposeAndEvictDesktopSnapshot(storageKey: string): Promise<void> {
- snapshotSync.evict(storageKey);
}
-export async function pruneOrphanedDesktopStateStores(knownStorageKeys: ReadonlyArray<string>): Promise<void> {
- snapshotSync.prune(knownStorageKeys);
-}
+const snapshotSync = new SnapshotSyncOwner(() => AccountEngine.available);
export default snapshotSync;
diff --git a/fluxer_app/src/features/gateway/transport/ForegroundGatewayDispatchProcessor.ts b/fluxer_app/src/features/gateway/transport/ForegroundGatewayDispatchProcessor.ts
index 57a96ffa4..3434c2156 100644
--- a/fluxer_app/src/features/gateway/transport/ForegroundGatewayDispatchProcessor.ts
+++ b/fluxer_app/src/features/gateway/transport/ForegroundGatewayDispatchProcessor.ts
@@ -26,7 +26,7 @@ export interface ForegroundGatewayDispatchHost {
markGuildSynced(guildId: string): void;
}
-export class ForegroundGatewayDispatchAccountUserUnknownError extends Error {
+class ForegroundGatewayDispatchAccountUserUnknownError extends Error {
constructor(accountKey: string) {
super(`Gateway dispatch account ${accountKey} has no stored user`);
this.name = 'ForegroundGatewayDispatchAccountUserUnknownError';
@@ -91,7 +91,7 @@ export class ForegroundGatewayDispatchProcessor {
if (receivedUserId !== expectedUserId) {
throw new Error(`Gateway READY user mismatch: expected ${expectedUserId}, received ${String(receivedUserId)}`);
}
- SnapshotSync.applyReady(accountKey, event.data, 'foreground');
+ SnapshotSync.applyReady(accountKey, event.data);
return;
}
SnapshotSync.applyDispatch(accountKey, event);