A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createChannelID, createGuildID, createMessageID, createUserID} from '@app/api/BrandedTypes';
import {
MESSAGE_BUILD_BATCH_MAX_BYTES,
MessageResponseDataService,
} from '@app/api/channel/services/message/MessageResponseDataService';
import {Message} from '@app/api/models/Message';
import {FakeNatsConnectionManager} from '@app/api/test/mocks/FakeNatsConnectionManager';
import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';
import {afterEach, describe, expect, it, vi} from 'vitest';
function createConnectionManager() {
const orphanedMessageIds = new Set<string>();
return Object.assign(
new FakeNatsConnectionManager(
(_subject, payload) => {
if (payload.op === 'BuildResponses') {
const messages = (payload.messages as Array<{message_id: string; channel_id: string}>).filter(
(message) => !orphanedMessageIds.has(message.message_id),
);
return {FoundApiMany: messages.map((message) => fakeMessageResponse(message.message_id, message.channel_id))};
}
return {FoundApi: fakeMessageResponse('2')};
},
{startConnected: true},
),
{orphanedMessageIds},
);
}
function fakeMessageResponse(messageId: string, channelId: string = '1'): Record<string, unknown> {
return {
id: messageId,
channel_id: channelId,
author: {id: '3', username: 'author', discriminator: '0001', avatar: null, flags: 0},
type: MessageTypes.DEFAULT,
flags: 0,
content: '',
timestamp: '2026-01-01T00:00:00.000Z',
edited_timestamp: null,
pinned: false,
mention_everyone: false,
tts: false,
mentions: [],
mention_roles: [],
embeds: [],
attachments: [],
stickers: [],
};
}
function makeMessage(messageId: bigint = 2n, content: string = '', channelId: bigint = 1n): Message {
return new Message({
channel_id: createChannelID(channelId),
bucket: 0,
message_id: createMessageID(messageId),
author_id: createUserID(3n),
type: MessageTypes.DEFAULT,
webhook_id: null,
webhook_name: null,
webhook_avatar_hash: null,
content,
edited_timestamp: null,
pinned_timestamp: null,
flags: 0,
mention_everyone: false,
mention_users: null,
mention_roles: null,
mention_channels: null,
attachments: null,
embeds: null,
sticker_items: null,
message_reference: null,
message_snapshots: null,
call: null,
has_reaction: null,
version: 1,
});
}
const BASE_MESSAGE_ID = 1000000000000000000n;
const VIEWER_ID = createUserID(3n);
const ACCESS = {sourceGuildId: null, messageHistoryCutoff: null, canReadMessageHistory: true};
async function measureSerializedMessageBytes(): Promise<number> {
const connectionManager = createConnectionManager();
const service = new MessageResponseDataService(connectionManager);
await service.buildMessages({userId: VIEWER_ID, messages: [makeMessage(BASE_MESSAGE_ID)], access: ACCESS});
const {messages} = connectionManager.requests[0]!.body as {messages: Array<unknown>};
return Buffer.byteLength(JSON.stringify(messages[0]));
}
function makeSizedMessage(index: number, totalBytes: number, baseBytes: number, channelId: bigint = 1n): Message {
return makeMessage(BASE_MESSAGE_ID + BigInt(index), 'a'.repeat(totalBytes - baseBytes), channelId);
}
function messageId(index: number): string {
return (BASE_MESSAGE_ID + BigInt(index)).toString();
}
function batchSizes(connectionManager: FakeNatsConnectionManager): Array<number> {
return connectionManager.requests.map(({body: payload}) => (payload as {messages: Array<unknown>}).messages.length);
}
describe('MessageResponseDataService', () => {
afterEach(() => {
vi.restoreAllMocks();
});
it('splits into ordered batches once one more byte would cross the budget', async () => {
const baseBytes = await measureSerializedMessageBytes();
const connectionManager = createConnectionManager();
const service = new MessageResponseDataService(connectionManager);
const messages = [
makeSizedMessage(0, MESSAGE_BUILD_BATCH_MAX_BYTES / 2, baseBytes),
makeSizedMessage(1, MESSAGE_BUILD_BATCH_MAX_BYTES / 2 + 1, baseBytes),
makeSizedMessage(2, baseBytes, baseBytes),
];
const responses = await service.buildMessages({userId: VIEWER_ID, messages, access: ACCESS});
expect(batchSizes(connectionManager)).toEqual([1, 2]);
expect(responses.map((response) => response.id)).toEqual(messages.map((message) => message.id.toString()));
});
it('drops a message the service leaves out instead of shifting later responses', async () => {
const connectionManager = createConnectionManager();
connectionManager.orphanedMessageIds.add(messageId(1));
const service = new MessageResponseDataService(connectionManager);
const messages = [0, 1, 2].map((index) => makeMessage(BASE_MESSAGE_ID + BigInt(index)));
const responses = await service.buildMessagesForChannels({
userId: VIEWER_ID,
messages,
channelById: new Map([['1', {guildId: null}]]),
});
expect(responses.map((response) => response.id)).toEqual([messageId(0), messageId(2)]);
});
it('keeps responses in input order when channels resolve to different guilds', async () => {
const connectionManager = createConnectionManager();
connectionManager.orphanedMessageIds.add(messageId(2));
const service = new MessageResponseDataService(connectionManager);
const messages = [
makeMessage(BASE_MESSAGE_ID, '', 10n),
makeMessage(BASE_MESSAGE_ID + 1n, '', 20n),
makeMessage(BASE_MESSAGE_ID + 2n, '', 10n),
makeMessage(BASE_MESSAGE_ID + 3n, '', 20n),
];
const responses = await service.buildMessagesForChannels({
userId: VIEWER_ID,
messages,
channelById: new Map([
['10', {guildId: createGuildID(100n)}],
['20', {guildId: createGuildID(200n)}],
]),
});
expect(batchSizes(connectionManager)).toEqual([2, 2]);
expect(responses.map((response) => response.id)).toEqual([messageId(0), messageId(1), messageId(3)]);
});
it('keeps other guilds aligned when an earlier batch drops a message', async () => {
const baseBytes = await measureSerializedMessageBytes();
const connectionManager = createConnectionManager();
connectionManager.orphanedMessageIds.add(messageId(0));
const service = new MessageResponseDataService(connectionManager);
const messages = [
makeSizedMessage(0, MESSAGE_BUILD_BATCH_MAX_BYTES / 2, baseBytes, 10n),
makeMessage(BASE_MESSAGE_ID + 1n, '', 20n),
makeSizedMessage(2, MESSAGE_BUILD_BATCH_MAX_BYTES / 2 + 1, baseBytes, 10n),
makeSizedMessage(3, baseBytes, baseBytes, 10n),
];
const responses = await service.buildMessagesForChannels({
userId: VIEWER_ID,
messages,
channelById: new Map([
['10', {guildId: createGuildID(100n)}],
['20', {guildId: createGuildID(200n)}],
]),
});
expect(batchSizes(connectionManager).sort()).toEqual([1, 1, 2]);
expect(responses.map((response) => response.id)).toEqual([messageId(1), messageId(2), messageId(3)]);
expect(responses.map((response) => response.channel_id)).toEqual(['20', '10', '10']);
});
});