Skip to content

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

TypeScript fluxerfluxerapp
9.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {Logger} from '@app/features/platform/utils/AppLogger';
import {DEFAULT_SYNCED_FIELD_MAX_ENCODED_BYTES, decideOversizePush} from '@app/features/user/state/SyncedFieldBudget';
import {verifyRoundtripStability} from '@app/features/user/state/SyncedFieldRoundtrip';
import {
	createSyncedFieldMachineSnapshot,
	type SyncedFieldCommand,
	type SyncedFieldFailureReason,
	type SyncedFieldMachineEvent,
	selectSyncedFieldMachineModel,
	transitionSyncedFieldMachineSnapshot,
} from '@app/features/user/state/SyncedFieldStateMachine';
import type {SyncedPreferences, SyncedPreferencesField} from '@app/features/user/state/SyncedPreferencesEngine';
import {create, equals, type Message, type MessageInitShape, toBinary} from '@bufbuild/protobuf';
import type {GenMessage} from '@bufbuild/protobuf/codegenv2';
import {compareShallow, reaction, runInAction} from 'mobx';

const logger = new Logger('SyncedField');

interface SyncedFieldUserSettings {
	isHydrated(): boolean;
	getAccountEpoch(): number;
	getSubPreference<F extends SyncedPreferencesField>(field: F): SyncedPreferences[F] | undefined;
	setSubPreference<F extends SyncedPreferencesField>(field: F, value: NonNullable<SyncedPreferences[F]>): Promise<void>;
}

let announceUserSettings: (settings: SyncedFieldUserSettings) => void;
const userSettingsReady = new Promise<SyncedFieldUserSettings>((resolve) => {
	announceUserSettings = resolve;
});

export function setSyncedFieldUserSettings(settings: SyncedFieldUserSettings): void {
	announceUserSettings(settings);
}

function isMessageSchema(value: unknown): value is GenMessage<Message> {
	return (
		value != null &&
		typeof value === 'object' &&
		typeof (value as {typeName?: unknown}).typeName === 'string' &&
		Array.isArray((value as {fields?: unknown}).fields)
	);
}

export interface SyncedFieldConfig<
	T extends object,
	F extends SyncedPreferencesField,
	M extends Message & NonNullable<SyncedPreferences[F]>,
> {
	readonly field: F;
	readonly schema: GenMessage<M>;
	readonly persist: ReadonlyArray<keyof T>;
	toMessage(store: T): MessageInitShape<GenMessage<M>>;
	applyMessage(store: T, message: M): void;
	readonly version?: number;
	readonly debounceMs?: number;
	readonly syncAcrossTabs?: boolean;
	readonly maxEncodedBytes?: number;
	enabled?(): boolean;
	mergeRemote?(local: M, incoming: M): MessageInitShape<GenMessage<M>>;
}

export async function makeSyncedField<
	T extends object,
	F extends SyncedPreferencesField,
	M extends Message & NonNullable<SyncedPreferences[F]>,
>(store: T, config: SyncedFieldConfig<T, F, M>): Promise<void> {
	const tag = `${store.constructor.name}.${String(config.field)}`;
	const schema = config.schema;
	if (!isMessageSchema(schema)) {
		logger.error(`${tag}: invalid protobuf schema; synced persistence disabled.`);
		return;
	}
	const isEnabled = (): boolean => config.enabled?.() ?? true;
	let machine = createSyncedFieldMachineSnapshot();
	let lastPreparedBytes: number | null = null;
	let ownerEpoch: number | null = null;
	let observedEpoch = 0;
	const suspend = (reason: SyncedFieldFailureReason, message: string, error?: unknown): void => {
		logger.error(`${tag}: ${message}; synced persistence disabled:`, error);
		transitionMachine({
			type: 'sync.failed',
			failure: {
				reason,
				message,
				error,
			},
		});
	};
	const buildMessage = (): M => create(schema, config.toMessage(store)) as NonNullable<SyncedPreferences[F]> as M;
	const defaults = ((): M | null => {
		try {
			return buildMessage();
		} catch (error) {
			logger.error(`${tag}: failed to capture the default snapshot:`, error);
			return null;
		}
	})();
	const buildMessageOrSuspend = (message: string): M | null => {
		if (!selectSyncedFieldMachineModel(machine).isActive) return null;
		try {
			return buildMessage();
		} catch (error) {
			suspend('build-local', message, error);
			return null;
		}
	};
	const getRemoteSnapshot = (): SyncedPreferences[F] | undefined => {
		if (!selectSyncedFieldMachineModel(machine).isActive) return undefined;
		if (!isEnabled()) return undefined;
		try {
			return UserSettings.getSubPreference(config.field);
		} catch (error) {
			suspend('read-remote', 'failed to read the remote snapshot', error);
			return undefined;
		}
	};
	const compareRemote = (snapshot: M): void => {
		const candidate = buildMessageOrSuspend('failed to build the local snapshot before applying a remote update');
		if (candidate == null) return;
		try {
			if (equals(schema, snapshot, candidate)) {
				ownerEpoch = observedEpoch;
				transitionOnly({type: 'sync.remoteMatched'});
				return;
			}
			transitionOnly({type: 'sync.remoteNeedsApply'});
		} catch (error) {
			suspend('compare-remote', 'failed to compare the remote snapshot with local state', error);
		}
	};
	const applyRemote = (snapshot: M): void => {
		let effective = snapshot;
		if (config.mergeRemote && ownerEpoch === observedEpoch) {
			try {
				effective = create(schema, config.mergeRemote(buildMessage(), snapshot)) as M;
			} catch (error) {
				logger.error(`${tag}: mergeRemote threw; applying the remote snapshot as-is:`, error);
				effective = snapshot;
			}
		}
		try {
			runInAction(() => {
				config.applyMessage(store, effective);
			});
		} catch (error) {
			logger.error(`${tag}: applyMessage threw:`, error);
		}
		ownerEpoch = observedEpoch;
		transitionOnly({type: 'sync.applyFinished'});
	};
	const preparePush = (candidate: M): void => {
		if (!UserSettings.isHydrated() || ownerEpoch !== UserSettings.getAccountEpoch()) {
			transitionOnly({type: 'sync.localAlreadySynced'});
			return;
		}
		try {
			const current = UserSettings.getSubPreference(config.field);
			if (current !== undefined && equals(schema, current as M, candidate)) {
				transitionOnly({type: 'sync.localAlreadySynced'});
				return;
			}
			const encodedBytes = toBinary(schema, candidate).length;
			const decision = decideOversizePush({encodedBytes, maxEncodedBytes, lastPreparedBytes});
			lastPreparedBytes = encodedBytes;
			if (decision === 'drop') {
				logger.error(
					`${tag}: payload of ${encodedBytes} bytes exceeds per-field budget of ${maxEncodedBytes}; push dropped.`,
				);
				transitionOnly({type: 'sync.localAlreadySynced'});
				return;
			}
			if (decision === 'push-shrinks') {
				logger.warn(
					`${tag}: payload of ${encodedBytes} bytes is over the per-field budget of ${maxEncodedBytes} but smaller than the previous candidate. Pushing so removals persist.`,
				);
			}
			const stability = verifyRoundtripStability<T, M>({
				schema,
				store,
				toMessage: config.toMessage,
				applyMessage: config.applyMessage,
				candidate,
			});
			if (stability.threw !== undefined) {
				suspend('roundtrip-threw', 'applyMessage threw during roundtrip probe', stability.threw);
				return;
			}
			if (!stability.stable) {
				suspend(
					'roundtrip-unstable',
					'roundtrip-stability check failed (toMessage → applyMessage → toMessage produced a different message)',
				);
				return;
			}
		} catch (error) {
			suspend('encode-local', 'failed to encode or validate the local snapshot', error);
			return;
		}
		transitionOnly({type: 'sync.localReadyToPush'});
	};
	const push = (candidate: M): void => {
		void UserSettings.setSubPreference(config.field, candidate).catch((error) => {
			const status =
				error != null && typeof error === 'object' && typeof (error as {status?: unknown}).status === 'number'
					? ((error as {status: number}).status as number)
					: null;
			if (status === 429) return;
			logger.warn(`${tag}: failed to sync to server:`, error);
		});
		transitionOnly({type: 'sync.commandHandled'});
	};
	const executeCommand = (command: SyncedFieldCommand): void => {
		switch (command.type) {
			case 'compareRemote':
				compareRemote(command.snapshot as M);
				return;
			case 'applyRemote':
				applyRemote(command.snapshot as M);
				return;
			case 'preparePush':
				preparePush(command.candidate as M);
				return;
			case 'pushLocal':
				push(command.candidate as M);
				return;
		}
	};
	const processCommands = (): void => {
		for (let i = 0; i < 8; i++) {
			const command = selectSyncedFieldMachineModel(machine).command;
			if (command == null) return;
			executeCommand(command);
		}
		suspend('machine-loop', 'state machine command loop exceeded the safety limit');
	};
	function transitionOnly(event: SyncedFieldMachineEvent): void {
		machine = transitionSyncedFieldMachineSnapshot(machine, event);
	}
	function transitionMachine(event: SyncedFieldMachineEvent): void {
		transitionOnly(event);
		processCommands();
	}
	const maxEncodedBytes = config.maxEncodedBytes ?? DEFAULT_SYNCED_FIELD_MAX_ENCODED_BYTES;
	const UserSettings = await userSettingsReady;
	const applyDefaultsForAccountChange = (epoch: number, message: M): void => {
		try {
			runInAction(() => {
				config.applyMessage(store, message);
			});
		} catch (error) {
			logger.error(`${tag}: applyMessage threw while resetting to defaults after an account change:`, error);
		}
		ownerEpoch = epoch;
	};
	try {
		reaction(
			() => ({
				snapshot: getRemoteSnapshot(),
				epoch: UserSettings.getAccountEpoch(),
				hydrated: UserSettings.isHydrated(),
			}),
			({snapshot, epoch}) => {
				observedEpoch = epoch;
				if (ownerEpoch === null || !isEnabled()) {
					ownerEpoch = epoch;
				}
				if (
					snapshot === undefined &&
					ownerEpoch !== epoch &&
					defaults !== null &&
					selectSyncedFieldMachineModel(machine).isActive
				) {
					applyDefaultsForAccountChange(epoch, defaults);
				}
				transitionMachine({
					type: 'sync.remoteObserved',
					enabled: isEnabled(),
					snapshot,
				});
			},
			{fireImmediately: true, equals: compareShallow},
		);
		reaction(
			() => (isEnabled() ? buildMessageOrSuspend('failed to build the local snapshot for observation') : null),
			(candidate) => {
				transitionMachine({
					type: 'sync.localObserved',
					enabled: isEnabled(),
					candidate,
				});
			},
			config.debounceMs != null && config.debounceMs > 0 ? {delay: config.debounceMs} : undefined,
		);
	} catch (error) {
		suspend('initialize-reactions', 'failed to initialize reactions', error);
	}
}