A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
perf(api): load the cassandra driver only in cassandra mode
Hampusaf4ea66c1b8f
diff --git a/fluxer_api/pkgs/cassandra/src/Client.ts b/fluxer_api/pkgs/cassandra/src/Client.tsindex 9a5ecd95d..3ec33f1d2 100644--- a/fluxer_api/pkgs/cassandra/src/Client.ts+++ b/fluxer_api/pkgs/cassandra/src/Client.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import cassandra from 'cassandra-driver';+import type cassandra from 'cassandra-driver';-const distance = cassandra.types.distance;+type CassandraDriver = typeof cassandra;const MAX_REQUESTS_PER_CONNECTION = 2048;const CONNECT_TIMEOUT_MS = 5000;@@ -28,6 +28,12 @@ const defaultClientState: DefaultClientState = {client: null,};+let loadedDriver: CassandraDriver | null = null;++export function getLoadedCassandraDriver(): CassandraDriver | null {+ return loadedDriver;+}+class CassandraClient {private readonly config: CassandraConfig;private client: cassandra.Client | null;@@ -49,10 +55,13 @@ class CassandraClient {if (this.client !== null) {return;}+ const {default: driver} = await import('cassandra-driver');+ loadedDriver = driver;+ const distance = driver.types.distance;const authProvider = this.config.username- ? new cassandra.auth.PlainTextAuthProvider(this.config.username, this.config.password ?? '')+ ? new driver.auth.PlainTextAuthProvider(this.config.username, this.config.password ?? ''): undefined;- const client = new cassandra.Client({+ const client = new driver.Client({contactPoints: this.config.hosts,keyspace: this.config.keyspace,localDataCenter: this.config.localDc,diff --git a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts b/fluxer_api/src/api/admin/services/AdminUserProfileService.tsindex 9585c62fe..12d4f9ecd 100644--- a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts+++ b/fluxer_api/src/api/admin/services/AdminUserProfileService.ts@@ -5,6 +5,7 @@ import {mapUserToAdminResponse} from '@app/api/admin/models/UserTypes';import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService';import {confirmEmailOwnership} from '@app/api/auth/EmailOwnership';import {createUserID, type UserID} from '@app/api/BrandedTypes';+import {LocalDate} from '@app/api/database/LocalDate';import type {EnforcementDecisionRow} from '@app/api/database/types/EnforcementTypes';import type {EnforcementActor} from '@app/api/enforcement/EnforcementActor';import {decisionAuditMetadata, type EnforcementDecisionService} from '@app/api/enforcement/EnforcementDecisionService';@@ -383,7 +384,7 @@ export class AdminUserProfileService {let updatedUser = await userRepository.patchUpsert(userId,{- date_of_birth: types.LocalDate.fromString(data.date_of_birth),+ date_of_birth: LocalDate.fromString(data.date_of_birth),traits: traits.size > 0 ? traits : null,},user.toRow(),diff --git a/fluxer_api/src/api/auth/AuthRegistration.ts b/fluxer_api/src/api/auth/AuthRegistration.tsindex c434d8c62..42255d194 100644--- a/fluxer_api/src/api/auth/AuthRegistration.ts+++ b/fluxer_api/src/api/auth/AuthRegistration.ts@@ -20,6 +20,7 @@ import {} from '@app/api/auth/InstanceAddress';import {createInviteCode, createUserID, type UserID} from '@app/api/BrandedTypes';import type {APIConfig} from '@app/api/config/APIConfig';+import type {LocalDate} from '@app/api/database/LocalDate';import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';import {emitActivity} from '@app/api/infrastructure/activity/ActivityEvents';import type {RegMethod} from '@app/api/infrastructure/activity/Contract.generated';@@ -534,7 +535,7 @@ async function createAccountUnlocked(}interface RegistrationDateOfBirth {- date: types.LocalDate | null;+ date: LocalDate | null;adult: boolean;deferred: boolean;}diff --git a/fluxer_api/src/api/database/CassandraQueryExecution.ts b/fluxer_api/src/api/database/CassandraQueryExecution.tsindex 25b419e05..e76ee33e9 100644--- a/fluxer_api/src/api/database/CassandraQueryExecution.ts+++ b/fluxer_api/src/api/database/CassandraQueryExecution.ts@@ -3,6 +3,7 @@import {logBatch, logQuery} from '@app/api/database/CassandraDevLogger';import {getIsDev} from '@app/api/database/CassandraMetaRegistry';import type {+ CassandraParam,CassandraParams,KvAdvance,KvQueryMeta,@@ -16,26 +17,37 @@ import {normalizeExecuteArgs,normalizeInParams,} from '@app/api/database/CassandraTypes';+import {LocalDate} from '@app/api/database/LocalDate';import {Logger} from '@app/api/Logger';import {chunkArray} from '@app/api/utils/ArrayUtils';import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';-import {getClient} from '@pkgs/cassandra/src/Client';-import cassandra from 'cassandra-driver';+import {getClient, getLoadedCassandraDriver} from '@pkgs/cassandra/src/Client';+import type cassandra from 'cassandra-driver';const DEFAULT_MAX_PARTITION_KEYS_PER_QUERY = 100;+function isBusyConnectionError(err: unknown): boolean {+ return err instanceof Error && err.name === 'BusyConnectionError';+}+function isDriverOverloadError(err: unknown): boolean {- if (err instanceof cassandra.errors.BusyConnectionError) {+ if (isBusyConnectionError(err)) {return true;}- if (err instanceof cassandra.errors.NoHostAvailableError && err.innerErrors) {- return Object.values(err.innerErrors as Record<string, unknown>).some(- (innerError) => innerError instanceof cassandra.errors.BusyConnectionError,- );+ if (err instanceof Error && err.name === 'NoHostAvailableError' && 'innerErrors' in err && err.innerErrors) {+ return Object.values(err.innerErrors as Record<string, unknown>).some(isBusyConnectionError);}return false;}+function driverParams(params: object): Record<string, CassandraParam> {+ const out: Record<string, CassandraParam> = {};+ for (const [key, value] of Object.entries(params)) {+ out[key] = value instanceof LocalDate ? value.toString() : value;+ }+ return out;+}+export function mapCassandraDriverError(err: unknown): unknown {return isDriverOverloadError(err) ? new ServiceUnavailableError() : err;}@@ -131,9 +143,9 @@ export async function executeQuery<T = Record<string, unknown>, P extends Cassanconst isDev = getIsDev();const startTime = isDev ? performance.now() : 0;try {- const result = await getClient().execute(cql, bound, {+ const result = await getClient().execute(cql, driverParams(bound), {prepare: true,- ...(readOptions ? {consistency: cassandra.types.consistencies[readOptions.consistency]} : {}),+ ...(readOptions ? {consistency: getLoadedCassandraDriver()?.types.consistencies[readOptions.consistency]} : {}),});const rows = await collectSelectRows<T>(meta.type, result);if (isDev) {@@ -227,7 +239,7 @@ export async function fetchPage<T = Record<string, unknown>, P extends CassandrapageState: null,};}- const result = await getClient().execute(cql, bound, {+ const result = await getClient().execute(cql, driverParams(bound), {prepare: true,fetchSize: options.pageSize,pageState: options.pageState ?? undefined,@@ -335,7 +347,7 @@ async function executeBatch(queries: Array<BatchQuery>, atomic = true): Promise<await getClient().batch(queries.map(({query, params}) => ({query,- params: normalizeInParams(getStatementMeta(query), params as CassandraParams),+ params: driverParams(normalizeInParams(getStatementMeta(query), params as CassandraParams)),})),options,);diff --git a/fluxer_api/src/api/database/CassandraTypes.ts b/fluxer_api/src/api/database/CassandraTypes.tsindex dca6df4af..1d7193a3f 100644--- a/fluxer_api/src/api/database/CassandraTypes.ts+++ b/fluxer_api/src/api/database/CassandraTypes.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type cassandra from 'cassandra-driver';+import {LocalDate} from '@app/api/database/LocalDate';const MAX_TTL_SECONDS = 630_720_000;@@ -42,7 +42,7 @@ export type CassandraParam =| boolean| Buffer| Date- | cassandra.types.LocalDate+ | LocalDate| Set<unknown>| Map<unknown, unknown>| Array<unknown>@@ -353,7 +353,7 @@ function findUndefinedPath(value: unknown): string | null {const t = typeof value;if (t === 'string' || t === 'number' || t === 'bigint' || t === 'boolean') return null;if (value instanceof Date || value instanceof Buffer) return null;- if (t === 'object' && value.constructor?.name === 'LocalDate') return null;+ if (value instanceof LocalDate) return null;if (Array.isArray(value)) {for (let i = 0; i < value.length; i++) {const suffix = findUndefinedPath(value[i]);diff --git a/fluxer_api/src/api/database/LocalDate.ts b/fluxer_api/src/api/database/LocalDate.tsnew file mode 100644index 000000000..4961fa4e1--- /dev/null+++ b/fluxer_api/src/api/database/LocalDate.ts@@ -0,0 +1,29 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++const LOCAL_DATE_PATTERN = /^(-?\d+)-(\d{1,2})-(\d{1,2})$/;++export class LocalDate {+ readonly year: number;+ readonly month: number;+ readonly day: number;++ constructor(year: number, month: number, day: number) {+ this.year = year;+ this.month = month;+ this.day = day;+ }++ static fromString(value: string): LocalDate {+ const match = LOCAL_DATE_PATTERN.exec(value);+ if (!match) {+ throw new Error(`Invalid local date: ${value}`);+ }+ return new LocalDate(Number(match[1]), Number(match[2]), Number(match[3]));+ }++ toString(): string {+ const sign = this.year < 0 ? '-' : '';+ const year = String(Math.abs(this.year)).padStart(4, '0');+ return `${sign}${year}-${String(this.month).padStart(2, '0')}-${String(this.day).padStart(2, '0')}`;+ }+}diff --git a/fluxer_api/src/api/database/PostgresKvExactnessFuzz.test.ts b/fluxer_api/src/api/database/PostgresKvExactnessFuzz.test.tsindex acdc0dd49..d082e01fe 100644--- a/fluxer_api/src/api/database/PostgresKvExactnessFuzz.test.ts+++ b/fluxer_api/src/api/database/PostgresKvExactnessFuzz.test.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {CassandraParams, KvQueryMeta, KvTableSpec, WhereExpr} from '@app/api/database/CassandraTypes';+import {LocalDate} from '@app/api/database/LocalDate';import {buildCandidatePlan, keyFromColumns, matchesWhere} from '@app/api/database/PostgresKvQueryExecutor';import {describe, expect, it} from 'vitest';@@ -36,7 +37,7 @@ const VALUES: Array<[string, unknown]> = [['date-epoch-2', new Date(0)],['buf-a', Buffer.from('a')],['buf-a-2', Buffer.from('a')],- ['localdate', cassandra.types.LocalDate.fromString('2020-01-01')],+ ['localdate', LocalDate.fromString('2020-01-01')],['localdate-str', '2020-01-01'],];diff --git a/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts b/fluxer_api/src/api/database/PostgresKvQueryExecutor.tsindex 4a1094d8c..0ff1631ad 100644--- a/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts+++ b/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts@@ -11,6 +11,7 @@ import type {WhereExpr,} from '@app/api/database/CassandraTypes';import {isConditionalQuery, validateTtlSeconds} from '@app/api/database/CassandraTypes';+import {LocalDate} from '@app/api/database/LocalDate';import {Logger} from '@app/api/Logger';import {type IPostgresClient, type PostgresQueryable, quoteIdentifier} from '@pkgs/postgres/src/Client';@@ -178,7 +179,7 @@ function encodeValue(value: unknown): unknown {value: [...value.entries()].map(([key, entry]) => [encodeValue(key), encodeValue(entry)]),};}- if (typeof value === 'object' && value.constructor?.name === 'LocalDate') {+ if (value instanceof LocalDate) {return {[ENCODED_TYPE_KEY]: 'local_date', value: value.toString()};}if (Array.isArray(value)) return value.map(encodeValue);@@ -205,7 +206,7 @@ function decodeValue(value: unknown): unknown {((value.value as Array<[unknown, unknown]>) ?? []).map(([key, entry]) => [decodeValue(key), decodeValue(entry)]),);}- if (encodedType === 'local_date') return cassandra.types.LocalDate.fromString(String(value.value));+ if (encodedType === 'local_date') return LocalDate.fromString(String(value.value));const decoded: Record<string, unknown> = {};for (const [key, entry] of Object.entries(value)) {decoded[key] = decodeValue(entry);@@ -307,7 +308,7 @@ function comparisonValue(value: unknown): unknown {if (value instanceof Date) {return value.getTime();}- return value?.constructor?.name === 'LocalDate' ? value.toString() : value;+ return value instanceof LocalDate ? value.toString() : value;}function compareValues(left: unknown, right: unknown): number {@@ -328,7 +329,7 @@ export function valuesEqual(left: unknown, right: unknown): boolean {if (left == null && right == null) return true;if (left instanceof Date && right instanceof Date) return left.getTime() === right.getTime();if (Buffer.isBuffer(left) && Buffer.isBuffer(right)) return left.equals(right);- if (left?.constructor?.name === 'LocalDate' && right?.constructor?.name === 'LocalDate') {+ if (left instanceof LocalDate && right instanceof LocalDate) {return left.toString() === right.toString();}return left === right;diff --git a/fluxer_api/src/api/database/PostgresKvQueryPlan.test.ts b/fluxer_api/src/api/database/PostgresKvQueryPlan.test.tsindex a933d7329..eb6e21de0 100644--- a/fluxer_api/src/api/database/PostgresKvQueryPlan.test.ts+++ b/fluxer_api/src/api/database/PostgresKvQueryPlan.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import cassandra from 'cassandra-driver';+import {LocalDate} from '@app/api/database/LocalDate';import {describe, expect, it} from 'vitest';import '@app/api/Tables';import {getTableMetadata} from '@app/api/database/CassandraMetaRegistry';@@ -439,8 +439,8 @@ describe('PostgresKvQueryExecutor key equality', () => {['false', false],['date', new Date('2020-01-01T00:00:00.000Z')],['buffer', Buffer.from('2020-01-01')],- ['local-date', cassandra.types.LocalDate.fromString('2020-01-01')],- ['other-local-date', cassandra.types.LocalDate.fromString('2021-06-05')],+ ['local-date', LocalDate.fromString('2020-01-01')],+ ['other-local-date', LocalDate.fromString('2021-06-05')],];it('accepts an equality exactly when both sides share a row key', () => {@@ -457,7 +457,7 @@ describe('PostgresKvQueryExecutor key equality', () => {});it('does not equate a LocalDate with its string rendering', () => {- const localDate = cassandra.types.LocalDate.fromString('2020-01-01');+ const localDate = LocalDate.fromString('2020-01-01');expect(matchesWhere({a: localDate}, eqWhere, {a: localDate} as CassandraParams)).toBe(true);expect(matchesWhere({a: localDate}, eqWhere, {a: '2020-01-01'} as CassandraParams)).toBe(false);expect(matchesWhere({a: '2020-01-01'}, eqWhere, {a: localDate} as CassandraParams)).toBe(false);diff --git a/fluxer_api/src/api/database/types/UserTypes.ts b/fluxer_api/src/api/database/types/UserTypes.tsindex 504418a2f..3336130b3 100644--- a/fluxer_api/src/api/database/types/UserTypes.ts+++ b/fluxer_api/src/api/database/types/UserTypes.ts@@ -10,6 +10,7 @@ import type {MessageID,UserID,} from '@app/api/BrandedTypes';+import type {LocalDate} from '@app/api/database/LocalDate';import type {LocaleCode} from '@fluxer/constants/src/Locales';import type {GuildFolderIcon, MentionReplyPreference} from '@fluxer/constants/src/UserConstants';import type {types} from 'cassandra-driver';@@ -44,7 +45,7 @@ export interface UserRow {accent_color: number | null;timezone: string | null;timezone_privacy_flags: number | null;- date_of_birth: types.LocalDate | null;+ date_of_birth: LocalDate | null;locale: string | null;flags: bigint | null;premium_flags?: number | null;diff --git a/fluxer_api/src/api/models/User.ts b/fluxer_api/src/api/models/User.tsindex 8695b5636..d79183421 100644--- a/fluxer_api/src/api/models/User.ts+++ b/fluxer_api/src/api/models/User.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {UserID} from '@app/api/BrandedTypes';+import {LocalDate} from '@app/api/database/LocalDate';import type {UserRow} from '@app/api/database/types/UserTypes';import {checkIsPremium, getEffectivePremiumUntil} from '@app/api/user/UserHelpers';import {@@ -179,7 +180,7 @@ export class User {accent_color: this.accentColor,timezone: this.timezone,timezone_privacy_flags: this.timezonePrivacyFlags,- date_of_birth: this.dateOfBirth ? types.LocalDate.fromString(this.dateOfBirth) : null,+ date_of_birth: this.dateOfBirth ? LocalDate.fromString(this.dateOfBirth) : null,locale: this.locale,flags: this.flags,premium_flags: this.premiumFlags,diff --git a/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.ts b/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.tsindex f30dd4bee..dc100560f 100644--- a/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.ts+++ b/fluxer_api/src/api/user/tests/AccountTierServiceGates.test.ts@@ -6,6 +6,7 @@ import {createTotpSecret, totpCodeNow} from '@app/api/auth/tests/AuthTestUtils';import {createGuildID, createUserID} from '@app/api/BrandedTypes';import {Config} from '@app/api/Config';import {createApiContext} from '@app/api/CreateApiContext';+import {LocalDate} from '@app/api/database/LocalDate';import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';import {setCachedAccountIdentity} from '@app/api/instance/AccountIdentityModeCache';import {@@ -46,7 +47,7 @@ function createUser(overrides: Partial<UserRow> = {}): User {password_hash: 'hash',traits: new Set<string>(),flags: UserFlags.HAS_SESSION_STARTED,- date_of_birth: types.LocalDate.fromString('1990-01-01'),+ date_of_birth: LocalDate.fromString('1990-01-01'),...overrides,});}diff --git a/fluxer_api/src/api/utils/AgeUtils.ts b/fluxer_api/src/api/utils/AgeUtils.tsindex cb6968df1..797d17815 100644--- a/fluxer_api/src/api/utils/AgeUtils.ts+++ b/fluxer_api/src/api/utils/AgeUtils.ts@@ -1,18 +1,19 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {LocalDate} from '@app/api/database/LocalDate';import {instanceCollectsDateOfBirth} from '@app/api/instance/DateOfBirthCollectionCache';import {isPlausibleDateOfBirth} from '@fluxer/constants/src/RegionalMinimumAge';import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';-export function parseDateOfBirth(value: string, now: Date = new Date()): types.LocalDate {+export function parseDateOfBirth(value: string, now: Date = new Date()): LocalDate {const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);const birth = match ? {year: Number(match[1]), month: Number(match[2]), day: Number(match[3])} : null;const today = {year: now.getUTCFullYear(), month: now.getUTCMonth() + 1, day: now.getUTCDate()};if (birth === null || !isPlausibleDateOfBirth(birth, today)) {throw InputValidationError.fromCode('date_of_birth', ValidationErrorCodes.INVALID_DATE_OF_BIRTH_FORMAT);}- return new types.LocalDate(birth.year, birth.month, birth.day);+ return new LocalDate(birth.year, birth.month, birth.day);}export function calculateAge(