A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(desktop): add engine row store, scheduler and dispatch pump
Hampus2970f6247d66
diff --git a/fluxer_desktop/src/engine/DispatchPump.ts b/fluxer_desktop/src/engine/DispatchPump.tsnew file mode 100644index 000000000..1d7b1d23c--- /dev/null+++ b/fluxer_desktop/src/engine/DispatchPump.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++const DISPATCH_SLICE_MS = 8;++export interface DispatchConsumer {+ hasPending(): boolean;+ processNext(): void;+}++export class DispatchPump {+ private readonly pending = new Set<DispatchConsumer>();+ private scheduled = false;+ private readonly sliceMs: number;+ private readonly now: () => number;++ constructor(sliceMs = DISPATCH_SLICE_MS, now: () => number = () => performance.now()) {+ this.sliceMs = sliceMs;+ this.now = now;+ }++ schedule(consumer: DispatchConsumer): void {+ this.pending.add(consumer);+ if (!this.scheduled) {+ this.scheduled = true;+ setImmediate(() => this.run());+ }+ }++ forget(consumer: DispatchConsumer): void {+ this.pending.delete(consumer);+ }++ private run(): void {+ this.scheduled = false;+ this.runSlice();+ if (this.pending.size > 0 && !this.scheduled) {+ this.scheduled = true;+ setImmediate(() => this.run());+ }+ }++ private runSlice(): void {+ const startedAt = this.now();+ while (this.pending.size > 0 && this.now() - startedAt < this.sliceMs) {+ for (const consumer of Array.from(this.pending)) {+ if (!consumer.hasPending()) {+ this.pending.delete(consumer);+ continue;+ }+ consumer.processNext();+ if (!consumer.hasPending()) {+ this.pending.delete(consumer);+ }+ if (this.now() - startedAt >= this.sliceMs) {+ return;+ }+ }+ }+ }+}diff --git a/fluxer_desktop/src/engine/MentionLog.ts b/fluxer_desktop/src/engine/MentionLog.tsnew file mode 100644index 000000000..08dfa688d--- /dev/null+++ b/fluxer_desktop/src/engine/MentionLog.ts@@ -0,0 +1,86 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {CacheDatabase} from '@electron/engine/CacheDatabase';+import type {AccountEngineMention} from '@fluxer/desktop_ipc/src/AccountEngineContract';+import {isRecord} from '@fluxer/record_utils/src/RecordGuards';++const MENTION_LOG_KEEP = 200;++function mentionCreatedAt(mention: AccountEngineMention): number {+ const parsed = Date.parse(mention.timestamp);+ return Number.isFinite(parsed) ? parsed : 0;+}++export class MentionLog {+ private readonly db: CacheDatabase;++ constructor(db: CacheDatabase) {+ this.db = db;+ }++ record(accountKey: string, mention: AccountEngineMention): void {+ this.db.insertMention(+ accountKey,+ mention.messageId,+ mentionCreatedAt(mention),+ JSON.stringify(mention),+ MENTION_LOG_KEEP,+ );+ }++ list(accountKey: string, limit: number): Array<AccountEngineMention> {+ if (limit <= 0) {+ return [];+ }+ const mentions: Array<AccountEngineMention> = [];+ for (const json of this.db.listMentions(accountKey, Math.min(limit, MENTION_LOG_KEEP))) {+ let value: unknown;+ try {+ value = JSON.parse(json);+ } catch (error) {+ if (error instanceof SyntaxError) {+ continue;+ }+ throw error;+ }+ if (!isRecord(value) || !isRecord(value.author)) {+ continue;+ }+ const {messageId, channelId, guildId, channelType, channelName, guildName, author, content, gated, timestamp} =+ value;+ const {id, username, globalName, avatar, discriminator} = author;+ if (+ typeof messageId !== 'string' ||+ typeof channelId !== 'string' ||+ (guildId !== null && typeof guildId !== 'string') ||+ (channelType !== null && typeof channelType !== 'number') ||+ (channelName !== null && typeof channelName !== 'string') ||+ (guildName !== null && typeof guildName !== 'string') ||+ typeof id !== 'string' ||+ typeof username !== 'string' ||+ (globalName !== null && typeof globalName !== 'string') ||+ (avatar !== null && typeof avatar !== 'string') ||+ (discriminator !== null && typeof discriminator !== 'string') ||+ typeof content !== 'string' ||+ (gated !== undefined && typeof gated !== 'boolean') ||+ typeof timestamp !== 'string'+ ) {+ continue;+ }+ mentions.push({+ ...value,+ messageId,+ channelId,+ guildId,+ channelType,+ channelName,+ guildName,+ author: {...author, id, username, globalName, avatar, discriminator},+ content,+ gated: gated ?? false,+ timestamp,+ });+ }+ return mentions;+ }+}diff --git a/fluxer_desktop/src/engine/SessionScheduler.ts b/fluxer_desktop/src/engine/SessionScheduler.tsnew file mode 100644index 000000000..2f9b5afc5--- /dev/null+++ b/fluxer_desktop/src/engine/SessionScheduler.ts@@ -0,0 +1,227 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {EngineClock, EngineTimer} from '@electron/engine/EngineClock';++export const SCHEDULER_LIMITS = Object.freeze({+ perOriginHandshakes: 2,+ totalHandshakes: 6,+ originStaggerMs: 250,+ resumeStaggerMs: 50,+ slotTimeoutMs: 15_000,+ backoffBaseMs: 1_000,+ backoffCapMs: 60_000,+ rateLimitFloorMs: 30_000,+ onlineResumeStaggerMs: 50,+});++export interface SchedulerClient {+ readonly accountKey: string;+ readonly origin: string;+ readonly priority: number;+ readonly resuming?: boolean;+ onSlotGranted(): void;+}++interface QueueEntry {+ readonly client: SchedulerClient;+ readonly order: number;+}++interface HeldSlot {+ readonly origin: string;+ readonly timer: EngineTimer;+}++interface RetryEntry {+ readonly run: () => void;+ readonly dueAt: number;+ timer: EngineTimer | null;+}++export class SessionScheduler {+ private readonly clock: EngineClock;+ private readonly queue: Array<QueueEntry> = [];+ private readonly held = new Map<string, HeldSlot>();+ private readonly inFlightByOrigin = new Map<string, number>();+ private readonly nextStartByOrigin = new Map<string, number>();+ private readonly retries = new Map<string, RetryEntry>();+ private pumpTimer: EngineTimer | null = null;+ private order = 0;+ private online = true;+ private pumping = false;+ private pumpAgain = false;++ constructor(clock: EngineClock) {+ this.clock = clock;+ }++ get isOnline(): boolean {+ return this.online;+ }++ requestSlot(client: SchedulerClient): void {+ this.cancel(client.accountKey);+ this.queue.push({client, order: this.order++});+ this.pump();+ }++ releaseSlot(accountKey: string): void {+ const slot = this.held.get(accountKey);+ if (slot === undefined) {+ return;+ }+ this.held.delete(accountKey);+ this.clock.clearTimeout(slot.timer);+ const remaining = (this.inFlightByOrigin.get(slot.origin) ?? 1) - 1;+ if (remaining <= 0) {+ this.inFlightByOrigin.delete(slot.origin);+ } else {+ this.inFlightByOrigin.set(slot.origin, remaining);+ }+ this.pump();+ }++ cancel(accountKey: string): void {+ const index = this.queue.findIndex((entry) => entry.client.accountKey === accountKey);+ if (index >= 0) {+ this.queue.splice(index, 1);+ }+ this.cancelRetry(accountKey);+ this.releaseSlot(accountKey);+ }++ backoffDelay(attempt: number, floorMs = 0): number {+ const exponent = Math.min(Math.max(0, attempt), 16);+ const ceiling = Math.min(SCHEDULER_LIMITS.backoffCapMs, SCHEDULER_LIMITS.backoffBaseMs * 2 ** exponent);+ const jittered = Math.floor(this.clock.random() * ceiling);+ return Math.max(floorMs, jittered);+ }++ scheduleRetry(accountKey: string, delayMs: number, run: () => void): number {+ this.cancelRetry(accountKey);+ const entry: RetryEntry = {run, dueAt: this.clock.now() + delayMs, timer: null};+ this.retries.set(accountKey, entry);+ if (this.online) {+ this.armRetry(accountKey, entry, delayMs);+ }+ return entry.dueAt;+ }++ cancelRetry(accountKey: string): void {+ const entry = this.retries.get(accountKey);+ if (entry === undefined) {+ return;+ }+ this.retries.delete(accountKey);+ if (entry.timer !== null) {+ this.clock.clearTimeout(entry.timer);+ }+ }++ setOnline(online: boolean): void {+ if (this.online === online) {+ return;+ }+ this.online = online;+ if (!online) {+ for (const entry of this.retries.values()) {+ if (entry.timer !== null) {+ this.clock.clearTimeout(entry.timer);+ entry.timer = null;+ }+ }+ return;+ }+ let index = 0;+ for (const [accountKey, entry] of this.retries) {+ this.armRetry(accountKey, entry, index * SCHEDULER_LIMITS.onlineResumeStaggerMs);+ index += 1;+ }+ this.pump();+ }++ dispose(): void {+ for (const accountKey of Array.from(this.retries.keys())) {+ this.cancelRetry(accountKey);+ }+ for (const slot of this.held.values()) {+ this.clock.clearTimeout(slot.timer);+ }+ this.held.clear();+ this.inFlightByOrigin.clear();+ this.queue.length = 0;+ if (this.pumpTimer !== null) {+ this.clock.clearTimeout(this.pumpTimer);+ this.pumpTimer = null;+ }+ }++ private armRetry(accountKey: string, entry: RetryEntry, delayMs: number): void {+ entry.timer = this.clock.setTimeout(() => {+ if (this.retries.get(accountKey) !== entry) {+ return;+ }+ this.retries.delete(accountKey);+ entry.run();+ }, delayMs);+ }++ private pump(): void {+ if (this.pumping) {+ this.pumpAgain = true;+ return;+ }+ this.pumping = true;+ try {+ do {+ this.pumpAgain = false;+ this.pumpOnce();+ } while (this.pumpAgain);+ } finally {+ this.pumping = false;+ }+ }++ private pumpOnce(): void {+ if (!this.online || this.queue.length === 0) {+ return;+ }+ this.queue.sort((left, right) => right.client.priority - left.client.priority || left.order - right.order);+ const now = this.clock.now();+ let earliestWait = Number.POSITIVE_INFINITY;+ for (let index = 0; index < this.queue.length && this.held.size < SCHEDULER_LIMITS.totalHandshakes; ) {+ const {client} = this.queue[index];+ const origin = client.origin;+ if ((this.inFlightByOrigin.get(origin) ?? 0) >= SCHEDULER_LIMITS.perOriginHandshakes) {+ index += 1;+ continue;+ }+ const nextStart = this.nextStartByOrigin.get(origin) ?? 0;+ if (nextStart > now) {+ earliestWait = Math.min(earliestWait, nextStart - now);+ index += 1;+ continue;+ }+ this.queue.splice(index, 1);+ this.grant(client, now);+ }+ if (Number.isFinite(earliestWait) && this.pumpTimer === null) {+ this.pumpTimer = this.clock.setTimeout(() => {+ this.pumpTimer = null;+ this.pump();+ }, earliestWait);+ }+ }++ private grant(client: SchedulerClient, now: number): void {+ const origin = client.origin;+ this.inFlightByOrigin.set(origin, (this.inFlightByOrigin.get(origin) ?? 0) + 1);+ this.nextStartByOrigin.set(+ origin,+ now + (client.resuming === true ? SCHEDULER_LIMITS.resumeStaggerMs : SCHEDULER_LIMITS.originStaggerMs),+ );+ const timer = this.clock.setTimeout(() => this.releaseSlot(client.accountKey), SCHEDULER_LIMITS.slotTimeoutMs);+ this.held.set(client.accountKey, {origin, timer});+ client.onSlotGranted();+ }+}diff --git a/fluxer_desktop/src/engine/SqliteRowStore.ts b/fluxer_desktop/src/engine/SqliteRowStore.tsnew file mode 100644index 000000000..e2fc23195--- /dev/null+++ b/fluxer_desktop/src/engine/SqliteRowStore.ts@@ -0,0 +1,154 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {+ CACHE_ACCOUNT_MAX_ROWS,+ CACHE_ACCOUNT_MAX_VALUE_BYTES,+ type CacheDatabase,+} from '@electron/engine/CacheDatabase';+import type {+ AccountEngineSnapshotCapture,+ AccountEngineSnapshotCursor,+} from '@fluxer/desktop_ipc/src/AccountEngineContract';+import type {AccountEngineRowOp, AccountEngineRowStore} from '@fluxer/desktop_ipc/src/AccountEngineCoreContract';++const ROW_STORE_VALUE_MAX_BYTES = 256 * 1024;++class RowStoreCapacityError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'RowStoreCapacityError';+ }+}++function valueByteLength(value: string): number {+ const bytes = Buffer.byteLength(value, 'utf8');+ if (bytes > ROW_STORE_VALUE_MAX_BYTES) {+ throw new RowStoreCapacityError(`Snapshot value exceeded ${ROW_STORE_VALUE_MAX_BYTES} bytes`);+ }+ return bytes;+}++function serializeValue(value: unknown): {value: string; bytes: number} {+ const serialized = JSON.stringify(value);+ if (serialized === undefined) {+ throw new Error('Snapshot value serialization returned undefined');+ }+ return {value: serialized, bytes: valueByteLength(serialized)};+}++export class SqliteRowStore implements AccountEngineRowStore {+ private readonly db: CacheDatabase;+ private readonly maxRows: number;+ private readonly maxBytes: number;++ constructor(db: CacheDatabase, limits: {maxRows?: number; maxBytes?: number} = {}) {+ this.db = db;+ this.maxRows = limits.maxRows ?? CACHE_ACCOUNT_MAX_ROWS;+ this.maxBytes = limits.maxBytes ?? CACHE_ACCOUNT_MAX_VALUE_BYTES;+ }++ has(storageKey: string): boolean {+ return this.db.readCursor(storageKey) !== null;+ }++ get(storageKey: string, entity: string, key: string): string | null {+ return this.db.getRow(storageKey, entity, key);+ }++ entriesByPrefix(storageKey: string, entity: string, prefix: string): Iterable<{key: string; value: string}> {+ return this.db.rowsByPrefix(storageKey, entity, prefix);+ }++ apply(storageKey: string, op: AccountEngineRowOp): void {+ switch (op.kind) {+ case 'upsert': {+ const {value, bytes} = serializeValue(op.value);+ this.assertCapacity(storageKey, 1, bytes);+ this.db.upsertRow(storageKey, op.entity, op.key, value);+ return;+ }+ case 'delete':+ this.db.deleteRow(storageKey, op.entity, op.key);+ return;+ case 'deleteByPrefix':+ this.db.deleteRowsByPrefix(storageKey, op.entity, op.keyPrefix);+ return;+ case 'replaceEntity': {+ const seen = new Set<string>();+ const entries: Array<readonly [string, string]> = [];+ let bytes = 0;+ for (const entry of op.entries) {+ if (seen.has(entry.key)) {+ throw new Error(`Snapshot replacement contains duplicate key ${entry.key}`);+ }+ seen.add(entry.key);+ const serialized = serializeValue(entry.value);+ bytes += serialized.bytes;+ entries.push([entry.key, serialized.value]);+ }+ this.assertCapacity(storageKey, entries.length, bytes);+ this.db.replaceEntity(storageKey, op.entity, entries);+ return;+ }+ }+ }++ writeCursor(storageKey: string, cursor: AccountEngineSnapshotCursor): void {+ this.db.writeCursor(storageKey, cursor);+ }++ readCursor(storageKey: string): AccountEngineSnapshotCursor | null {+ return this.db.readCursor(storageKey);+ }++ capture(storageKey: string): AccountEngineSnapshotCapture | null {+ const cursor = this.db.readCursor(storageKey);+ if (cursor === null) {+ return null;+ }+ return {entries: this.db.captureAccount(storageKey), cursor};+ }++ replaceAccount(storageKey: string, capture: AccountEngineSnapshotCapture): void {+ let rows = 0;+ let bytes = 0;+ const entities: Array<readonly [string, Array<readonly [string, string]>]> = [];+ for (const [entity, values] of Object.entries(capture.entries)) {+ const entries: Array<readonly [string, string]> = [];+ for (const [key, value] of Object.entries(values)) {+ if (typeof value !== 'string') {+ throw new Error(`Snapshot row ${entity}/${key} is not serialized`);+ }+ bytes += valueByteLength(value);+ rows += 1;+ entries.push([key, value]);+ }+ entities.push([entity, entries]);+ }+ if (rows > this.maxRows) {+ throw new RowStoreCapacityError(`The cache for ${storageKey} exceeded ${this.maxRows} rows`);+ }+ if (bytes > this.maxBytes) {+ throw new RowStoreCapacityError(`The cache for ${storageKey} exceeded ${this.maxBytes} value bytes`);+ }+ this.db.deleteAccountSnapshot(storageKey);+ for (const [entity, entries] of entities) {+ this.db.replaceEntity(storageKey, entity, entries);+ }+ this.db.writeCursor(storageKey, capture.cursor);+ }++ evict(storageKey: string): void {+ this.db.deleteAccountSnapshot(storageKey);+ }++ private assertCapacity(storageKey: string, addedRows: number, addedBytes: number): void {+ const usage = this.db.usageFor(storageKey);+ if (usage.rows + addedRows > this.maxRows) {+ throw new RowStoreCapacityError(`The cache for ${storageKey} exceeded ${this.maxRows} rows`);+ }+ if (usage.bytes + addedBytes > this.maxBytes) {+ throw new RowStoreCapacityError(`The cache for ${storageKey} exceeded ${this.maxBytes} value bytes`);+ }+ }+}diff --git a/fluxer_desktop/src/engine/SummaryPublisher.ts b/fluxer_desktop/src/engine/SummaryPublisher.tsnew file mode 100644index 000000000..4cd29743d--- /dev/null+++ b/fluxer_desktop/src/engine/SummaryPublisher.ts@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {EngineClock, EngineTimer} from '@electron/engine/EngineClock';+import type {AccountEngineAccountSummary} from '@fluxer/desktop_ipc/src/AccountEngineContract';++const SUMMARY_PERSIST_DEBOUNCE_MS = 2_000;++interface SummaryPublisherOptions {+ readonly clock: EngineClock;+ readonly coalesceMs: number;+ readonly emit: (summaries: ReadonlyArray<AccountEngineAccountSummary>) => void;+ readonly persist: (summary: AccountEngineAccountSummary) => void;+}++export class SummaryPublisher {+ private readonly options: SummaryPublisherOptions;+ private readonly summaries = new Map<string, AccountEngineAccountSummary>();+ private readonly changed = new Set<string>();+ private readonly unpersisted = new Set<string>();+ private emitTimer: EngineTimer | null = null;+ private persistTimer: EngineTimer | null = null;++ constructor(options: SummaryPublisherOptions) {+ this.options = options;+ }++ seed(summary: AccountEngineAccountSummary): void {+ this.summaries.set(summary.accountKey, summary);+ }++ update(summary: AccountEngineAccountSummary): void {+ this.summaries.set(summary.accountKey, summary);+ this.changed.add(summary.accountKey);+ this.unpersisted.add(summary.accountKey);+ if (this.emitTimer === null) {+ this.emitTimer = this.options.clock.setTimeout(() => this.emitNow(), this.options.coalesceMs);+ }+ if (this.persistTimer === null) {+ this.persistTimer = this.options.clock.setTimeout(() => this.persistNow(), SUMMARY_PERSIST_DEBOUNCE_MS);+ }+ }++ remove(accountKey: string): void {+ this.summaries.delete(accountKey);+ this.changed.delete(accountKey);+ this.unpersisted.delete(accountKey);+ }++ private emitNow(): void {+ if (this.emitTimer !== null) {+ this.options.clock.clearTimeout(this.emitTimer);+ this.emitTimer = null;+ }+ if (this.changed.size === 0) {+ return;+ }+ const batch: Array<AccountEngineAccountSummary> = [];+ for (const accountKey of this.changed) {+ const summary = this.summaries.get(accountKey);+ if (summary !== undefined) {+ batch.push(summary);+ }+ }+ this.changed.clear();+ if (batch.length > 0) {+ this.options.emit(batch);+ }+ }++ persistNow(): void {+ if (this.persistTimer !== null) {+ this.options.clock.clearTimeout(this.persistTimer);+ this.persistTimer = null;+ }+ for (const accountKey of this.unpersisted) {+ const summary = this.summaries.get(accountKey);+ if (summary !== undefined) {+ this.options.persist(summary);+ }+ }+ this.unpersisted.clear();+ }+}diff --git a/fluxer_desktop/src/engine/ZstdStreamCodec.ts b/fluxer_desktop/src/engine/ZstdStreamCodec.tsnew file mode 100644index 000000000..bda1d4a06--- /dev/null+++ b/fluxer_desktop/src/engine/ZstdStreamCodec.ts@@ -0,0 +1,96 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {constants, createZstdCompress, createZstdDecompress, type ZstdCompress, type ZstdDecompress} from 'node:zlib';++class ZstdStreamCodecError extends Error {+ constructor(message: string, options?: {cause?: unknown}) {+ super(message, options);+ this.name = 'ZstdStreamCodecError';+ }+}++type ZstdStream = ZstdCompress | ZstdDecompress;++class SerialStream {+ private readonly stream: ZstdStream;+ private readonly flushKind: number | null;+ private tail: Promise<unknown> = Promise.resolve();+ private chunks: Array<Buffer> = [];+ private pendingReject: ((error: Error) => void) | null = null;+ private failure: Error | null = null;++ constructor(stream: ZstdStream, flushKind: number | null) {+ this.stream = stream;+ this.flushKind = flushKind;+ stream.on('data', (chunk: Buffer) => {+ this.chunks.push(chunk);+ });+ stream.on('error', (error: Error) => {+ this.failure = new ZstdStreamCodecError(error.message, {cause: error});+ this.pendingReject?.(this.failure);+ this.pendingReject = null;+ });+ }++ process(input: Buffer): Promise<Buffer> {+ const run = this.tail.then(() => this.processNow(input));+ this.tail = run.catch(() => undefined);+ return run;+ }++ dispose(): void {+ this.failure ??= new ZstdStreamCodecError('The zstd stream is disposed');+ this.pendingReject?.(this.failure);+ this.pendingReject = null;+ this.stream.destroy();+ }++ private processNow(input: Buffer): Promise<Buffer> {+ if (this.failure !== null) {+ return Promise.reject(this.failure);+ }+ return new Promise<Buffer>((resolve, reject) => {+ this.chunks = [];+ this.pendingReject = reject;+ const done = (): void => {+ if (this.pendingReject !== reject) {+ return;+ }+ this.pendingReject = null;+ const output = Buffer.concat(this.chunks);+ this.chunks = [];+ resolve(output);+ };+ this.stream.write(input);+ if (this.flushKind === null) {+ this.stream.flush(done);+ } else {+ this.stream.flush(this.flushKind, done);+ }+ });+ }+}++export class ZstdStreamCodec {+ private readonly decoder = new SerialStream(createZstdDecompress(), null);+ private readonly encoder = new SerialStream(createZstdCompress(), constants.ZSTD_e_flush);+ private readonly textDecoder = new TextDecoder('utf-8', {fatal: true});++ async decompress(input: Buffer): Promise<string> {+ const output = await this.decoder.process(input);+ try {+ return this.textDecoder.decode(output);+ } catch (error) {+ throw new ZstdStreamCodecError('Decompressed gateway frame is not valid UTF-8', {cause: error});+ }+ }++ compress(text: string): Promise<Buffer> {+ return this.encoder.process(Buffer.from(text, 'utf8'));+ }++ dispose(): void {+ this.decoder.dispose();+ this.encoder.dispose();+ }+}