Skip to content

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

TypeScript fluxerfluxerapp

refactor(api): share lexical and snowflake comparators

Hampusf2b1fad4c0ee
diff --git a/fluxer_api/src/api/channel/services/message/CrosspostDeliveryService.ts b/fluxer_api/src/api/channel/services/message/CrosspostDeliveryService.ts
index e0d437172..724e0a66c 100644
--- a/fluxer_api/src/api/channel/services/message/CrosspostDeliveryService.ts
+++ b/fluxer_api/src/api/channel/services/message/CrosspostDeliveryService.ts
@@ -50,6 +50,7 @@ import type {Message} from '@app/api/models/Message';
import type {Webhook} from '@app/api/models/Webhook';
import {deleteMessageSearchDocuments} from '@app/api/search/MessageSearchIndexCleanup';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {compareText} from '@app/api/utils/StringComparison';
import type {WebhookRepository} from '@app/api/webhook/WebhookRepository';
import {
CROSSPOST_PENDING_RECLAIM_AFTER_MS,
@@ -151,7 +152,7 @@ function toStableValue(value: unknown): unknown {
if (value instanceof Map) {
return [...value.entries()]
.map(([key, entry]) => [String(key), toStableValue(entry)] as const)
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
+ .sort(([a], [b]) => compareText(a, b));
}
if (Array.isArray(value)) return value.map(toStableValue);
if (typeof value === 'object') {
@@ -251,7 +252,7 @@ export class CrosspostDeliveryService {
return {kind: 'ready', context};
}
- isSourceGuildActive(guild: GuildResponse): boolean {
+ private isSourceGuildActive(guild: GuildResponse): boolean {
return (
!isGuildUnavailable(guild) &&
!isOperationDisabled(guild, GuildOperations.SEND_MESSAGE) &&
diff --git a/fluxer_api/src/api/guild/tests/GuildMemberManagement.test.ts b/fluxer_api/src/api/guild/tests/GuildMemberManagement.test.ts
index e53108b2e..c58d98eb0 100644
--- a/fluxer_api/src/api/guild/tests/GuildMemberManagement.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildMemberManagement.test.ts
@@ -22,10 +22,6 @@ import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import type {GuildBanResponse, GuildMemberResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
-function sortSnowflakes(ids: Array<string>): Array<string> {
- return [...ids].sort((a, b) => (BigInt(a) < BigInt(b) ? -1 : BigInt(a) > BigInt(b) ? 1 : 0));
-}
-
describe('Guild Member Management', () => {
let harness: ApiTestHarness;
beforeEach(async () => {
@@ -274,17 +270,16 @@ describe('Guild Member Management', () => {
});
test('should support limit parameter for listing members', async () => {
const {owner, members, guild} = await setupTestGuildWithMembers(harness, 3);
- const expectedIds = sortSnowflakes([owner.userId, ...members.map((member) => member.userId)]);
const firstPage = await createBuilder<Array<GuildMemberResponse>>(harness, owner.token)
.get(`/guilds/${guild.id}/members?limit=2`)
.expect(HTTP_STATUS.OK)
.execute();
- expect(firstPage.map((entry) => entry.user.id)).toEqual(expectedIds.slice(0, 2));
+ expect(firstPage.map((entry) => entry.user.id)).toEqual([owner.userId, members[0].userId]);
const secondPage = await createBuilder<Array<GuildMemberResponse>>(harness, owner.token)
- .get(`/guilds/${guild.id}/members?limit=2&after=${firstPage[1]!.user.id}`)
+ .get(`/guilds/${guild.id}/members?limit=2&after=${members[0].userId}`)
.expect(HTTP_STATUS.OK)
.execute();
- expect(secondPage.map((entry) => entry.user.id)).toEqual(expectedIds.slice(2));
+ expect(secondPage.map((entry) => entry.user.id)).toEqual([members[1].userId, members[2].userId]);
});
});
describe('Get Member Permission Checks', () => {
diff --git a/fluxer_api/src/api/infrastructure/UsersServiceClient.ts b/fluxer_api/src/api/infrastructure/UsersServiceClient.ts
index c23760160..087250628 100644
--- a/fluxer_api/src/api/infrastructure/UsersServiceClient.ts
+++ b/fluxer_api/src/api/infrastructure/UsersServiceClient.ts
@@ -3,10 +3,12 @@
import type {UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import {requestSvcJson} from '@app/api/infrastructure/SvcErrorReply';
+import {getInstanceProductName} from '@app/api/instance/ProductName';
import {Logger} from '@app/api/Logger';
import {awaitAll} from '@app/api/utils/ConcurrencyUtils';
import {readOptionalEnv, readOptionalIntegerEnv, requireIntegerInRange} from '@app/api/utils/IntegerOptions';
import {isJsonRecord} from '@app/api/utils/JsonBoundaryUtils';
+import {compareText} from '@app/api/utils/StringComparison';
import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';
import {NatsConnectionManager} from '@pkgs/nats/src/NatsConnectionManager';
@@ -27,6 +29,7 @@ type UsersServiceRequest =
| {
op: 'GetApiPartialsByIds';
user_ids: Array<string>;
+ instance_name: string;
}
| {
op: 'Invalidate';
@@ -106,6 +109,7 @@ export class NatsUsersServiceClient implements IUsersServiceClient {
{
op: 'GetApiPartialsByIds',
user_ids: Array.from(requestedUserIds.keys()),
+ instance_name: getInstanceProductName(),
},
isUserPartialsResponse,
);
@@ -205,6 +209,6 @@ function uniqueSortedUserIds(userIds: Array<UserID>): Array<UserID> {
seen.set(userId.toString(), userId);
}
return Array.from(seen.entries())
- .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
+ .sort(([left], [right]) => compareText(left, right))
.map(([, userId]) => userId);
}
diff --git a/fluxer_api/src/api/test/mocks/MockStorageService.ts b/fluxer_api/src/api/test/mocks/MockStorageService.ts
index 0531f815e..d6c5e6cb4 100644
--- a/fluxer_api/src/api/test/mocks/MockStorageService.ts
+++ b/fluxer_api/src/api/test/mocks/MockStorageService.ts
@@ -6,12 +6,11 @@ import {Readable} from 'node:stream';
import {Config} from '@app/api/Config';
import {
type IStorageService,
- type ProcessedStorageObjectMetadata,
StorageObjectListingOverflowError,
StorageObjectRangeNotSatisfiableError,
} from '@app/api/infrastructure/IStorageService';
+import {compareText} from '@app/api/utils/StringComparison';
import {S3ServiceException} from '@aws-sdk/client-s3';
-import {isSupportedMediaContentType} from '@pkgs/mime_utils/src/ContentTypeUtils';
import {vi} from 'vitest';
const OBJECT_ID_SEPARATOR = '\u0000';
@@ -284,35 +283,6 @@ export class MockStorageService implements IStorageService {
}
}
- async copyObjectWithMetadataStripping(params: {
- sourceBucket: string;
- sourceKey: string;
- destinationBucket: string;
- destinationKey: string;
- contentType: string;
- sourceLocalPath?: string;
- }): Promise<ProcessedStorageObjectMetadata | null> {
- await this.copyObject({
- sourceBucket: params.sourceBucket,
- sourceKey: params.sourceKey,
- destinationBucket: params.destinationBucket,
- destinationKey: params.destinationKey,
- newContentType: params.contentType,
- });
- if (!isSupportedMediaContentType(params.contentType)) {
- return null;
- }
- const data =
- this.objects.get(this.objectId(params.destinationBucket, params.destinationKey))?.data ?? new Uint8Array();
- return {
- contentType: params.contentType,
- contentLength: data.length,
- contentHash: createHash('sha256').update(data).digest('hex'),
- width: 100,
- height: 100,
- };
- }
-
async getPresignedDownloadURL(_params: {
bucket: string;
key: string;
@@ -369,7 +339,7 @@ export class MockStorageService implements IStorageService {
const matches = [...this.objects.entries()]
.filter(([id]) => id.startsWith(this.objectId(params.bucket, params.prefix)))
.map(([id, object]) => ({key: id.slice(keyOffset), lastModified: object.lastModified}))
- .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
+ .sort((a, b) => compareText(a.key, b.key));
if (params.maxObjects !== undefined && matches.length > params.maxObjects) {
throw new StorageObjectListingOverflowError(params.bucket, params.prefix, params.maxObjects);
}
diff --git a/fluxer_api/src/api/utils/StringComparison.ts b/fluxer_api/src/api/utils/StringComparison.ts
new file mode 100644
index 000000000..97d2d43da
--- /dev/null
+++ b/fluxer_api/src/api/utils/StringComparison.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+export function compareText(left: string, right: string): number {
+ if (left < right) {
+ return -1;
+ }
+ if (left > right) {
+ return 1;
+ }
+ return 0;
+}
diff --git a/fluxer_api/src/api/voice/VoiceRegionSelection.ts b/fluxer_api/src/api/voice/VoiceRegionSelection.ts
index cdb14af02..9185e7163 100644
--- a/fluxer_api/src/api/voice/VoiceRegionSelection.ts
+++ b/fluxer_api/src/api/voice/VoiceRegionSelection.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {calculateDistance, parseCoordinate} from '@app/api/utils/GeoUtils';
+import {compareText} from '@app/api/utils/StringComparison';
import type {VoiceRegionAvailability, VoiceServerRecord} from '@app/api/voice/VoiceModel';
interface VoiceRegionPreference {
@@ -203,16 +204,6 @@ function hashSelectionKey(selectionKey: string): number {
return hash >>> 0;
}
-function compareText(left: string, right: string): number {
- if (left < right) {
- return -1;
- }
- if (left > right) {
- return 1;
- }
- return 0;
-}
-
function compareVoiceServers(left: VoiceServerRecord, right: VoiceServerRecord): number {
const regionComparison = compareText(left.regionId, right.regionId);
if (regionComparison !== 0) {