Skip to content

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

TypeScript fluxerfluxerapp

test: drop tests that replace modules with vi.mock

Hampusac0cbf5c00bf
diff --git a/fluxer_api/pkgs/email/src/SmtpEmailProvider.test.ts b/fluxer_api/pkgs/email/src/SmtpEmailProvider.test.ts
deleted file mode 100644
index d37d8f014..000000000
--- a/fluxer_api/pkgs/email/src/SmtpEmailProvider.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {SmtpEmailProvider} from '@pkgs/email/src/SmtpEmailProvider';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const {sendMail, close, createTransport} = vi.hoisted(() => {
- const sendMail = vi.fn();
- const close = vi.fn();
- return {
- sendMail,
- close,
- createTransport: vi.fn((_options: Record<string, unknown>) => ({sendMail, close, verify: vi.fn()})),
- };
-});
-
-vi.mock('nodemailer', () => ({
- default: {createTransport},
-}));
-
-describe('SmtpEmailProvider', () => {
- beforeEach(() => {
- createTransport.mockClear();
- close.mockReset();
- sendMail.mockReset();
- sendMail.mockResolvedValue({});
- });
-
- it.each([
- {port: 465, tlsMode: undefined, secure: true, requireTLS: false, ignoreTLS: false},
- {port: 587, tlsMode: undefined, secure: false, requireTLS: true, ignoreTLS: false},
- {port: 587, tlsMode: null, secure: false, requireTLS: true, ignoreTLS: false},
- {port: 587, tlsMode: 'implicit', secure: true, requireTLS: false, ignoreTLS: false},
- {port: 465, tlsMode: 'starttls', secure: false, requireTLS: true, ignoreTLS: false},
- {port: 25, tlsMode: 'opportunistic', secure: false, requireTLS: false, ignoreTLS: false},
- {port: 587, tlsMode: 'none', secure: false, requireTLS: false, ignoreTLS: true},
- ] as const)('maps TLS mode $tlsMode on port $port to nodemailer options', ({port, tlsMode, ...expected}) => {
- new SmtpEmailProvider({host: 'smtp.example.com', port, username: 'user', password: 'pass', tlsMode});
- expect(createTransport).toHaveBeenCalledWith(expect.objectContaining(expected));
- });
-
- it('passes the html part, custom headers and a one-click unsubscribe link', async () => {
- await createProvider().sendEmail({
- ...MESSAGE,
- html: '<p>Body</p>',
- headers: {'X-Entity-Ref-ID': 'ref'},
- listUnsubscribe: {url: 'https://api.example.com/unsubscribe?token=abc', post: true},
- });
- expect(sendMail).toHaveBeenCalledWith({
- from: 'Fluxer <[email protected]>',
- subject: 'Subject',
- text: 'Body',
- html: '<p>Body</p>',
- list: {unsubscribe: {url: 'https://api.example.com/unsubscribe?token=abc'}},
- headers: {'X-Entity-Ref-ID': 'ref', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click'},
- });
- });
-
- it('leaves out the one-click header when the unsubscribe link does not accept a POST', async () => {
- await createProvider().sendEmail({
- ...MESSAGE,
- listUnsubscribe: {url: 'https://example.com/unsubscribe', post: false},
- });
- expect(sendMail.mock.calls[0][0]).toEqual({
- ...MESSAGE,
- from: 'Fluxer <[email protected]>',
- list: {unsubscribe: {url: 'https://example.com/unsubscribe'}},
- });
- });
-
- it('opens a pooled transport for bulk sends and closes it', async () => {
- const bulk = createProvider().openBulk();
- expect(createTransport).toHaveBeenCalledTimes(2);
- expect(createTransport.mock.calls[1][0]).toMatchObject({
- host: 'smtp.example.com',
- port: 587,
- auth: {user: 'user', pass: 'pass'},
- pool: true,
- maxConnections: 4,
- maxMessages: 100,
- });
- await expect(bulk.sendEmail(MESSAGE)).resolves.toBe(true);
- await bulk.close();
- expect(close).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_api/pkgs/kv_client/src/__tests__/KVClient.test.ts b/fluxer_api/pkgs/kv_client/src/__tests__/KVClient.test.ts
deleted file mode 100644
index 6484b11ca..000000000
--- a/fluxer_api/pkgs/kv_client/src/__tests__/KVClient.test.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createHash} from 'node:crypto';
-import {KVClient} from '@pkgs/kv_client/src/KVClient';
-import {KVClientErrorCode} from '@pkgs/kv_client/src/KVClientError';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const {evalshaMock, evalMock} = vi.hoisted(() => ({
- evalshaMock: vi.fn(),
- evalMock: vi.fn(),
-}));
-
-vi.mock('ioredis', () => {
- class MockRedis {
- evalsha = evalshaMock;
- eval = evalMock;
- }
- return {default: MockRedis, Cluster: MockRedis};
-});
-
-const RATE_LIMIT_REPLY = JSON.stringify({
- allowed: true,
- limit: 5,
- remaining: 4,
- resetAfterMs: 200,
- resetAtMs: 1717171717,
- retryAfterMs: 0,
-});
-
-const EXPECTED_RATE_LIMIT_RESULT = {
- allowed: true,
- limit: 5,
- remaining: 4,
- resetAfterMs: 200,
- resetAtMs: 1717171717,
- retryAfterMs: 0,
-};
-
-function createClient(): KVClient {
- return new KVClient('redis://127.0.0.1:6379');
-}
-
-function noScriptError(): Error {
- return new Error('NOSCRIPT No matching script. Please use EVAL.');
-}
-
-function getCallArguments(mock: typeof evalshaMock, index: number): Array<unknown> {
- const call = mock.mock.calls[index];
- if (!call) {
- throw new Error(`Expected a call at index ${index}`);
- }
- return call;
-}
-
-describe('KVClient script execution', () => {
- beforeEach(() => {
- evalshaMock.mockReset();
- evalMock.mockReset();
- });
-
- it('falls back to EVAL with the original script and identical arguments on NOSCRIPT', async () => {
- evalshaMock.mockRejectedValue(noScriptError());
- evalMock.mockResolvedValue(RATE_LIMIT_REPLY);
- const result = await createClient().checkLeakyBucketLimit('rate_limit:bucket', 5, 1000, 1);
- expect(evalshaMock).toHaveBeenCalledTimes(1);
- expect(evalMock).toHaveBeenCalledTimes(1);
- const [sha, ...evalshaRest] = getCallArguments(evalshaMock, 0);
- const [script, ...evalRest] = getCallArguments(evalMock, 0);
- expect(createHash('sha1').update(String(script)).digest('hex')).toBe(sha);
- expect(evalRest).toEqual(evalshaRest);
- expect(String(script)).toContain("local rawState = redis.call('GET', key)");
- expect(result).toEqual(EXPECTED_RATE_LIMIT_RESULT);
- });
-
- it('keeps using EVALSHA with the same digest after a NOSCRIPT fallback', async () => {
- evalshaMock.mockRejectedValueOnce(noScriptError()).mockResolvedValue(RATE_LIMIT_REPLY);
- evalMock.mockResolvedValue(RATE_LIMIT_REPLY);
- const client = createClient();
- const first = await client.checkLeakyBucketLimit('rate_limit:bucket', 5, 1000, 1);
- const second = await client.checkLeakyBucketLimit('rate_limit:bucket', 5, 1000, 1);
- expect(evalshaMock).toHaveBeenCalledTimes(2);
- expect(evalMock).toHaveBeenCalledTimes(1);
- expect(getCallArguments(evalshaMock, 1)[0]).toBe(getCallArguments(evalshaMock, 0)[0]);
- expect(first).toEqual(EXPECTED_RATE_LIMIT_RESULT);
- expect(second).toEqual(EXPECTED_RATE_LIMIT_RESULT);
- });
-
- it('does not retry with EVAL when the script fails for another reason', async () => {
- evalshaMock.mockRejectedValue(new Error('Connection is closed.'));
- await expect(createClient().releaseLock('lock:key', 'token')).rejects.toMatchObject({
- code: KVClientErrorCode.REQUEST_FAILED,
- message: 'KV request failed (releaseLock): Connection is closed.',
- });
- expect(evalMock).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_api/pkgs/kv_client/src/__tests__/KVClientFanout.test.ts b/fluxer_api/pkgs/kv_client/src/__tests__/KVClientFanout.test.ts
deleted file mode 100644
index 996dd9768..000000000
--- a/fluxer_api/pkgs/kv_client/src/__tests__/KVClientFanout.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {KVClient} from '@pkgs/kv_client/src/KVClient';
-import {computeHashSlot} from '@pkgs/kv_client/src/KVHashSlots';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-const MAX_CONCURRENT_ROUND_TRIPS = 16;
-
-const {commands, store, tracker} = vi.hoisted(() => ({
- commands: [] as Array<{name: string; keys: Array<string>}>,
- store: new Map<string, string>(),
- tracker: {inFlight: 0, peakInFlight: 0},
-}));
-
-vi.mock('ioredis', () => {
- const trackRoundTrip = async (name: string, keys: Array<string>): Promise<void> => {
- commands.push({name, keys});
- tracker.inFlight += 1;
- tracker.peakInFlight = Math.max(tracker.peakInFlight, tracker.inFlight);
- await new Promise((resolve) => setTimeout(resolve, 0));
- tracker.inFlight -= 1;
- };
- class MockRedis {
- async mget(...keys: Array<string>): Promise<Array<string | null>> {
- await trackRoundTrip('mget', keys);
- return keys.map((key) => store.get(key) ?? null);
- }
-
- async del(...keys: Array<string>): Promise<number> {
- await trackRoundTrip('del', keys);
- return keys.length;
- }
-
- async get(key: string): Promise<string | null> {
- await trackRoundTrip('get', [key]);
- return store.get(key) ?? null;
- }
-
- async set(key: string, value: string): Promise<string> {
- await trackRoundTrip('set', [key]);
- store.set(key, value);
- return 'OK';
- }
- }
- return {default: MockRedis, Cluster: MockRedis};
-});
-
-function createKeys(count: number): Array<string> {
- return Array.from({length: count}, (_unused, index) => `fanout:key:${index}`);
-}
-
-function crossSlotCommands(): Array<{name: string; keys: Array<string>}> {
- return commands.filter((command) => new Set(command.keys.map(computeHashSlot)).size > 1);
-}
-
-describe('KVClient multi key fan out', () => {
- beforeEach(() => {
- commands.length = 0;
- store.clear();
- tracker.inFlight = 0;
- tracker.peakInFlight = 0;
- });
-
- it('bounds concurrent round trips for a cluster read', async () => {
- const client = new KVClient({url: 'redis://127.0.0.1:6379', mode: 'cluster'});
-
- const values = await client.mget(...createKeys(1000));
-
- expect(values.length).toBe(1000);
- expect(tracker.peakInFlight).toBeLessThanOrEqual(MAX_CONCURRENT_ROUND_TRIPS);
- expect(crossSlotCommands()).toEqual([]);
- });
-
- it('keeps values ordered when a cluster read is split by slot', async () => {
- const client = new KVClient({url: 'redis://127.0.0.1:6379', mode: 'cluster'});
- store.set('fanout:a', 'one');
- store.set('fanout:b', 'two');
-
- const values = await client.mget('fanout:a', 'fanout:missing', 'fanout:b');
-
- expect(values).toEqual(['one', null, 'two']);
- });
-});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostWorkerTestUtils.ts b/fluxer_api/src/api/channel/tests/CrosspostWorkerTestUtils.ts
index 7c22770b4..cdb6b7810 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostWorkerTestUtils.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostWorkerTestUtils.ts
@@ -10,7 +10,7 @@ import {
publish,
} from '@app/api/channel/tests/AnnouncementTestUtils';
import {loadFixture, sendMessageWithAttachments} from '@app/api/channel/tests/AttachmentTestUtils';
-import type {ChannelRow, CrosspostedMessageRow} from '@app/api/database/types/ChannelTypes';
+import type {CrosspostedMessageRow} from '@app/api/database/types/ChannelTypes';
import {ensureSessionStarted, getMessages} from '@app/api/message/tests/MessageTestUtils';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import type {SyncTaskWorkerService} from '@app/api/test/SyncTaskWorkerService';
@@ -154,15 +154,6 @@ export async function deleteMessageRequest(
await createBuilder(harness, token).delete(`/channels/${channelId}/messages/${messageId}`).expect(204).execute();
}
-export async function patchChannelRow(channelId: string, patch: Partial<ChannelRow>): Promise<void> {
- const repository = new ChannelRepository();
- const channel = await repository.channelData.findUnique(createChannelID(BigInt(channelId)));
- if (!channel) {
- throw new Error(`channel ${channelId} not found`);
- }
- await repository.channelData.upsert({...channel.toRow(), ...patch});
-}
-
export function patchChannel(harness: ApiTestHarness, token: string, channelId: string, body: Record<string, unknown>) {
return createBuilder<ChannelResponse>(harness, token).patch(`/channels/${channelId}`).body(body);
}
diff --git a/fluxer_api/src/api/channel/tests/MessageCrosspostFanout.test.ts b/fluxer_api/src/api/channel/tests/MessageCrosspostFanout.test.ts
deleted file mode 100644
index 0a05245e9..000000000
--- a/fluxer_api/src/api/channel/tests/MessageCrosspostFanout.test.ts
+++ /dev/null
@@ -1,1004 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {AdminRepository} from '@app/api/admin/AdminRepository';
-import {setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
-import {
- createAttachmentID,
- createChannelID,
- createGuildID,
- createMessageID,
- createStickerID,
- createWebhookID,
-} from '@app/api/BrandedTypes';
-import {Config} from '@app/api/Config';
-import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {enqueueCrosspostSync} from '@app/api/channel/services/message/CrosspostPropagation';
-import {MessagePersistenceService} from '@app/api/channel/services/message/MessagePersistenceService';
-import {MessageSearchService} from '@app/api/channel/services/message/MessageSearchService';
-import {MessageWriteLock} from '@app/api/channel/services/message/MessageWriteLock';
-import {
- addGuildMember,
- createAnnouncementTargetGuild,
- createGuildChannel,
- disableCrosspostWorker,
- follow,
- publish,
-} from '@app/api/channel/tests/AnnouncementTestUtils';
-import {loadFixture} from '@app/api/channel/tests/AttachmentTestUtils';
-import {createPermissionOverwrite} from '@app/api/channel/tests/ChannelTestUtils';
-import {addGuildFeature, createStallGate, patchGuildRow} from '@app/api/channel/tests/CrosspostTestUtils';
-import {
- copiesOf,
- deleteMessageRequest,
- editRequest,
- type FanoutWorld,
- followInto,
- listCopies,
- mappingRow,
- patchChannel,
- patchChannelRow,
- postAndPublish,
- publishAndDrain,
- readRow,
- sendMessage,
- sendWithImage,
- setupFanoutWorld,
- writeRow,
-} from '@app/api/channel/tests/CrosspostWorkerTestUtils';
-import {Logger} from '@app/api/Logger';
-import {getMessages} from '@app/api/message/tests/MessageTestUtils';
-import {startContentBlocklistCaches, stopContentBlocklistCaches} from '@app/api/middleware/ContentBlocklistCaches';
-import {fileShaCache} from '@app/api/middleware/FileShaCache';
-import {getKVClient} from '@app/api/middleware/ServiceRegistry';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import crosspostMessageChunk from '@app/api/worker/tasks/CrosspostMessageChunk';
-import syncCrosspostCopies from '@app/api/worker/tasks/SyncCrosspostCopies';
-import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {CROSSPOST_SOURCE_DELETED_CONTENT} from '@fluxer/constants/src/AnnouncementConstants';
-import {
- ChannelTypes,
- MessageAttachmentFlags,
- MessageFlags,
- MessageTypes,
- Permissions,
-} from '@fluxer/constants/src/ChannelConstants';
-import {
- ContentWarningLevel,
- GuildExplicitContentFilterTypes,
- GuildFeatures,
- GuildOperations,
-} from '@fluxer/constants/src/GuildConstants';
-import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-function createBarrier(parties: number): () => Promise<void> {
- let arrived = 0;
- let open: () => void = () => {};
- const opened = new Promise<void>((resolve) => {
- open = resolve;
- });
- return async () => {
- arrived++;
- if (arrived >= parties) open();
- await opened;
- };
-}
-
-const fanoutSizes = vi.hoisted(() => ({chunk: null as number | null, page: null as number | null}));
-
-vi.mock('@fluxer/constants/src/AnnouncementConstants', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@fluxer/constants/src/AnnouncementConstants')>();
- return {
- ...actual,
- get CROSSPOST_FANOUT_CHUNK_SIZE() {
- return fanoutSizes.chunk ?? actual.CROSSPOST_FANOUT_CHUNK_SIZE;
- },
- get CROSSPOST_FANOUT_PAGE_SIZE() {
- return fanoutSizes.page ?? actual.CROSSPOST_FANOUT_PAGE_SIZE;
- },
- };
-});
-
-describe('Crosspost fan-out', () => {
- let harness: ApiTestHarness;
- let world: FanoutWorld;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- harness.storageService.reset();
- world = await setupFanoutWorld(harness);
- });
-
- afterEach(() => {
- fanoutSizes.chunk = null;
- fanoutSizes.page = null;
- disableCrosspostWorker();
- vi.restoreAllMocks();
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- async function createTextChannel(name: string): Promise<ChannelResponse> {
- return createGuildChannel(harness, world.b.owner.token, world.b.guild.id, {name, type: ChannelTypes.GUILD_TEXT});
- }
-
- function attachmentObjectCopies(): Array<string> {
- return harness.storageService
- .getCopiedObjects()
- .filter((entry) => entry.sourceBucket === Config.s3.buckets.cdn && entry.sourceKey.startsWith('attachments/'))
- .map((entry) => entry.destinationKey);
- }
-
- function deletedKeys(): Array<string> {
- return harness.storageService.getDeletedObjects().map((entry) => entry.key);
- }
-
- function failNextCopyCreate(webhookId?: string): void {
- const original = MessagePersistenceService.prototype.createMessage;
- let failed = false;
- vi.spyOn(MessagePersistenceService.prototype, 'createMessage').mockImplementation(async function (
- this: MessagePersistenceService,
- params,
- ) {
- const matches = webhookId ? params.webhookId?.toString() === webhookId : params.webhookId != null;
- if (!failed && matches) {
- failed = true;
- throw new Error('database hiccup');
- }
- return original.call(this, params);
- });
- }
-
- function stallNextCopyCreate(): ReturnType<typeof createStallGate> {
- const gate = createStallGate();
- const original = MessagePersistenceService.prototype.createMessage;
- let stalled = false;
- vi.spyOn(MessagePersistenceService.prototype, 'createMessage').mockImplementation(async function (
- this: MessagePersistenceService,
- params,
- ) {
- if (!stalled && params.webhookId != null) {
- stalled = true;
- await gate.hit();
- }
- return original.call(this, params);
- });
- return gate;
- }
-
- async function expectNoCopies(channelId: string): Promise<void> {
- expect(await listCopies(harness, world.b.owner.token, channelId)).toHaveLength(0);
- expect(world.worker.deadLetters).toHaveLength(0);
- }
-
- test('one follower receives a copy with the published wire shape', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const source = await postAndPublish(harness, world, {content: 'Version 2 is out'});
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id);
- expect(copy).toBeDefined();
- expect(copy!.type).toBe(MessageTypes.DEFAULT);
- expect(copy!.webhook_id).toBe(webhookId);
- expect(copy!.author.id).toBe(webhookId);
- expect(copy!.author.username).toBe(`${world.a.guild.name} #${world.a.ann.name}`);
- expect(copy!.author.bot).toBe(true);
- expect(copy!.flags).toBe(MessageFlags.IS_CROSSPOST);
- expect(copy!.content).toBe('Version 2 is out');
- expect(copy!.message_reference).toEqual({
- type: 0,
- guild_id: world.a.guild.id,
- channel_id: world.a.ann.id,
- message_id: source.id,
- });
- expect('referenced_message' in copy!).toBe(false);
- const row = await mappingRow(source.id, webhookId);
- expect(row?.state).toBe('delivered');
- expect(row?.target_message_id.toString()).toBe(copy!.id);
- expect(row?.target_guild_id.toString()).toBe(world.b.guild.id);
- });
-
- test('copies store no mentions and reading them does not repair any', async () => {
- await followInto(harness, world, world.b.t1.id);
- const content = `@everyone <@&${world.a.guild.id}> <@${world.a.member.userId}> hello`;
- const source = await postAndPublish(harness, world, {content});
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id);
- expect(copy!.content).toBe(content);
- expect(copy!.mention_everyone).toBe(false);
- expect(copy!.mentions).toEqual([]);
- expect(copy!.mention_roles).toEqual([]);
- const before = await readRow(world.b.t1.id, copy!.id);
- for (let index = 0; index < 3; index++) {
- await createBuilder(harness, world.b.owner.token)
- .get(`/channels/${world.b.t1.id}/messages/${copy!.id}`)
- .execute();
- await getMessages(harness, world.b.owner.token, world.b.t1.id);
- }
- const after = await readRow(world.b.t1.id, copy!.id);
- expect(after?.version).toBe(before?.version);
- expect(after?.mentionEveryone).toBe(false);
- expect(after?.mentionedUserIds.size).toBe(0);
- expect(after?.mentionedRoleIds.size).toBe(0);
- });
-
- test('the copy keeps the sendable flags', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'quiet'});
- const sendable = MessageFlags.SUPPRESS_EMBEDS | MessageFlags.SUPPRESS_NOTIFICATIONS | MessageFlags.VOICE_MESSAGE;
- await writeRow((await readRow(world.a.ann.id, message.id))!, {flags: sendable});
- await publishAndDrain(harness, world, message.id);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.flags).toBe(MessageFlags.IS_CROSSPOST | sendable);
- });
-
- test('copies have the source attachments and resolve to the source channel', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'files'}, [
- 'first.png',
- 'second.gif',
- ]);
- const row = (await readRow(world.a.ann.id, message.id))!;
- await writeRow(row, {
- attachments: row.attachments.map((attachment, index) => ({
- ...attachment.toMessageAttachment(),
- flags: index === 0 ? MessageAttachmentFlags.IS_SPOILER : 0,
- })),
- });
- await publishAndDrain(harness, world, message.id);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- const sourceAttachments = (await readRow(world.a.ann.id, message.id))!.attachments;
- const copyRow = (await readRow(world.b.t1.id, copy!.id))!;
- expect(copyRow.attachments.map((attachment) => attachment.toMessageAttachment())).toEqual(
- sourceAttachments.map((attachment) => attachment.toMessageAttachment()),
- );
- expect(copy!.attachments).toHaveLength(2);
- copy!.attachments!.forEach((attachment, index) => {
- const original = sourceAttachments[index]!;
- expect(attachment.id).toBe(original.id.toString());
- expect(attachment.url).toContain(`/attachments/${world.a.ann.id}/${original.id}/${original.filename}`);
- expect(attachment.url).not.toContain(`/attachments/${world.b.t1.id}/`);
- expect(attachment.proxy_url).toBe(attachment.url);
- });
- expect(attachmentObjectCopies()).toEqual([]);
- });
-
- test('rich embeds are copied with their source attachment urls', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {
- content: 'card',
- embeds: [{title: 'Release card', description: 'All the details', image: {url: 'attachment://yeah.png'}}],
- });
- const sourceRow = (await readRow(world.a.ann.id, message.id))!;
- expect(sourceRow.attachments).toHaveLength(0);
- const sourceImageUrl = sourceRow.embeds[0]!.image!.url!;
- expect(sourceImageUrl.startsWith(`${Config.endpoints.media}/attachments/${world.a.ann.id}/`)).toBe(true);
- const sourceKey = sourceImageUrl.slice(`${Config.endpoints.media}/`.length);
- await publishAndDrain(harness, world, message.id);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- const copyRow = (await readRow(world.b.t1.id, copy!.id))!;
- expect(copyRow.embeds[0]!.title).toBe('Release card');
- expect(copyRow.embeds[0]!.description).toBe('All the details');
- expect(copyRow.embeds[0]!.image!.url).toBe(sourceImageUrl);
- expect(copy!.embeds?.[0]?.image?.url).toContain(`/${sourceKey}`);
- expect(harness.storageService.hasObject(Config.s3.buckets.cdn, sourceKey)).toBe(true);
- expect(attachmentObjectCopies()).toEqual([]);
- await deleteMessageRequest(harness, world.a.owner.token, world.a.ann.id, message.id);
- await world.worker.drain();
- expect(deletedKeys().some((key) => key.startsWith(`attachments/${world.b.t1.id}/`))).toBe(false);
- const marked = (await readRow(world.b.t1.id, copy!.id))!;
- expect(marked.flags).toBe(MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED);
- });
-
- test('favoriting the embed image of a copy by embed index copies the source object', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {
- content: 'card',
- embeds: [{title: 'Release card', image: {url: 'attachment://yeah.png'}}],
- });
- const sourceRow = (await readRow(world.a.ann.id, message.id))!;
- const sourceKey = sourceRow.embeds[0]!.image!.url!.slice(`${Config.endpoints.media}/`.length);
- await publishAndDrain(harness, world, message.id);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- await createBuilder(harness, world.b.owner.token)
- .post(`/channels/${world.b.t1.id}/messages/${copy!.id}/memes`)
- .body({embed_index: 0, name: 'Release card'})
- .expect(201)
- .execute();
- const fromSource = harness.storageService
- .getCopiedObjects()
- .filter((entry) => entry.sourceBucket === Config.s3.buckets.cdn && entry.sourceKey === sourceKey);
- expect(fromSource).toHaveLength(1);
- });
-
- test('stickers are copied', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'sticker'});
- const stickerId = createStickerID(123456789012345678n);
- await writeRow((await readRow(world.a.ann.id, message.id))!, {
- sticker_items: [{sticker_id: stickerId, name: 'party', animated: false}],
- });
- await publishAndDrain(harness, world, message.id);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- const copyRow = (await readRow(world.b.t1.id, copy!.id))!;
- expect(copyRow.stickers.map((sticker) => [sticker.id, sticker.name])).toEqual([[stickerId, 'party']]);
- });
-
- test('several followers in several guilds each get one copy', async () => {
- const c = await createAnnouncementTargetGuild(harness, 'Third Community');
- await addGuildMember(harness, world.a.owner, world.a.guild, c.owner);
- await followInto(harness, world, world.b.t1.id);
- await followInto(harness, world, world.b.t2.id);
- await followInto(harness, world, c.t1.id, c.owner.token);
- const source = await postAndPublish(harness, world, {content: 'everyone gets this'});
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id)).toHaveLength(1);
- expect(await copiesOf(harness, world.b.owner.token, world.b.t2.id, source.id)).toHaveLength(1);
- expect(await copiesOf(harness, c.owner.token, c.t1.id, source.id)).toHaveLength(1);
- });
-
- test('small chunks and pages still give every follower exactly one copy', async () => {
- const targets = [world.b.t1, world.b.t2];
- for (const name of ['t3', 't4', 't5']) {
- targets.push(await createTextChannel(name));
- }
- for (const target of targets) {
- await followInto(harness, world, target.id);
- }
- fanoutSizes.chunk = 1;
- fanoutSizes.page = 2;
- const source = await postAndPublish(harness, world, {content: 'paged'});
- for (const target of targets) {
- expect(await copiesOf(harness, world.b.owner.token, target.id, source.id)).toHaveLength(1);
- }
- expect(world.worker.byTask('crosspostMessage')).toHaveLength(3);
- expect(world.worker.byTask('crosspostMessageChunk')).toHaveLength(5);
- });
-
- test('running a chunk twice for one follower creates one copy', async () => {
- const source = await postAndPublish(harness, world, {content: 'once'});
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const payload = {channelId: world.a.ann.id, messageId: source.id, webhookIds: [webhookId], attempt: 0};
- await crosspostMessageChunk(
- payload,
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- await crosspostMessageChunk(
- payload,
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id)).toHaveLength(1);
- });
-
- test('a stale pending reservation is reclaimed with a newer id, a fresh one waits', async () => {
- const staleSource = await postAndPublish(harness, world, {content: 'stale'});
- const freshSource = await postAndPublish(harness, world, {content: 'fresh'});
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const repository = new ChannelRepository();
- const staleTargetId = createMessageID(BigInt(staleSource.id));
- const base = {
- webhook_id: createWebhookID(BigInt(webhookId)),
- source_channel_id: createChannelID(BigInt(world.a.ann.id)),
- target_guild_id: createGuildID(BigInt(world.b.guild.id)),
- target_channel_id: createChannelID(BigInt(world.b.t1.id)),
- state: 'pending' as const,
- source_fingerprint: null,
- created_at: new Date(),
- };
- await repository.crossposts.insertPending({
- ...base,
- source_message_id: createMessageID(BigInt(staleSource.id)),
- target_message_id: staleTargetId,
- reserved_at: new Date(Date.now() - 120_000),
- });
- await repository.crossposts.insertPending({
- ...base,
- source_message_id: createMessageID(BigInt(freshSource.id)),
- target_message_id: createMessageID(BigInt(freshSource.id)),
- reserved_at: new Date(),
- });
- await crosspostMessageChunk(
- {channelId: world.a.ann.id, messageId: staleSource.id, webhookIds: [webhookId], attempt: 0},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, staleSource.id);
- expect(BigInt(copy!.id)).toBeGreaterThan(staleTargetId);
- expect((await mappingRow(staleSource.id, webhookId))?.state).toBe('delivered');
- const recordedBefore = world.worker.recorded.length;
- await crosspostMessageChunk(
- {channelId: world.a.ann.id, messageId: freshSource.id, webhookIds: [webhookId], attempt: 0},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, freshSource.id)).toHaveLength(0);
- const retries = world.worker.recorded.slice(recordedBefore);
- expect(retries).toHaveLength(1);
- expect(retries[0]!.taskType).toBe('crosspostMessageChunk');
- expect(retries[0]!.payload).toMatchObject({attempt: 1, webhookIds: [webhookId]});
- expect(retries[0]!.runAt!.getTime()).toBeGreaterThan(Date.now());
- expect(retries[0]!.jobKey).toBe(`crosspost-chunk:${freshSource.id}:${webhookId}:1`);
- });
-
- test('a copy delivered on retry still lands after newer target messages', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'late'});
- failNextCopyCreate();
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- await world.worker.drain({maxJobs: 2});
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id)).toHaveLength(0);
- const newer = await sendMessage(harness, world.b.owner.token, world.b.t1.id, {content: 'meanwhile'});
- await world.worker.drain();
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(BigInt(copy!.id)).toBeGreaterThan(BigInt(newer.id));
- const channel = await createBuilder<ChannelResponse>(harness, world.b.owner.token)
- .get(`/channels/${world.b.t1.id}`)
- .execute();
- expect(channel.last_message_id).toBe(copy!.id);
- });
-
- describe('skips without errors', () => {
- test('a deleted follower webhook', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- await createBuilder(harness, world.b.owner.token).delete(`/webhooks/${webhookId}`).expect(204).execute();
- await postAndPublish(harness, world, {content: 'nobody'});
- await expectNoCopies(world.b.t1.id);
- });
-
- test('a follower webhook removed while the chunk is queued', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'raced'});
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- await world.worker.drain({maxJobs: 1});
- await createBuilder(harness, world.b.owner.token).delete(`/webhooks/${webhookId}`).expect(204).execute();
- await world.worker.drain();
- await expectNoCopies(world.b.t1.id);
- });
-
- test('a deleted target channel', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'gone'});
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- await world.worker.drain({maxJobs: 1});
- await createBuilder(harness, world.b.owner.token).delete(`/channels/${world.b.t1.id}`).expect(204).execute();
- await world.worker.drain();
- expect(world.worker.deadLetters).toHaveLength(0);
- });
-
- test('a target converted to a non-text type', async () => {
- await followInto(harness, world, world.b.t1.id);
- await patchChannelRow(world.b.t1.id, {type: ChannelTypes.GUILD_ANNOUNCEMENT});
- await postAndPublish(harness, world, {content: 'wrong type'});
- await expectNoCopies(world.b.t1.id);
- });
-
- test('an age-restricted source into a target that lost its restriction', async () => {
- await patchChannel(harness, world.a.owner.token, world.a.ann.id, {nsfw_override: true}).execute();
- await followInto(harness, world, world.b.ageRestricted.id);
- await patchChannel(harness, world.b.owner.token, world.b.ageRestricted.id, {nsfw_override: false}).execute();
- await postAndPublish(harness, world, {content: 'restricted'});
- await expectNoCopies(world.b.ageRestricted.id);
- });
-
- test('a content-warning source into a target that lost its warning', async () => {
- await patchChannel(harness, world.a.owner.token, world.a.ann.id, {
- content_warning_level: ContentWarningLevel.CONTENT_WARNING,
- }).execute();
- await followInto(harness, world, world.b.contentWarning.id);
- await patchChannel(harness, world.b.owner.token, world.b.contentWarning.id, {
- content_warning_level: ContentWarningLevel.INHERIT,
- }).execute();
- await postAndPublish(harness, world, {content: 'warned'});
- await expectNoCopies(world.b.contentWarning.id);
- });
-
- test('a target guild with sending disabled', async () => {
- await followInto(harness, world, world.b.t1.id);
- await patchGuildRow(world.b.guild.id, {disabled_operations: GuildOperations.SEND_MESSAGE});
- await postAndPublish(harness, world, {content: 'muted target'});
- await patchGuildRow(world.b.guild.id, {disabled_operations: 0});
- await expectNoCopies(world.b.t1.id);
- });
-
- test('a source guild that disables announcement channels after publishing', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'switched off'});
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- await addGuildFeature(world.a.guild.id, GuildFeatures.ANNOUNCEMENT_CHANNELS_DISABLED);
- await world.worker.drain();
- await expectNoCopies(world.b.t1.id);
- });
-
- test('a follower creator who can no longer view the source', async () => {
- await followInto(harness, world, world.b.t1.id);
- await createPermissionOverwrite(harness, world.a.owner.token, world.a.ann.id, world.b.owner.userId, {
- type: 1,
- allow: '0',
- deny: Permissions.VIEW_CHANNEL.toString(),
- });
- const logger: {info(obj: object, message?: string): void} = Logger.child({});
- const infoSpy = vi.spyOn(logger, 'info');
- await postAndPublish(harness, world, {content: 'private'});
- await expectNoCopies(world.b.t1.id);
- expect(infoSpy.mock.calls.some(([, message]) => String(message).includes('cannot view'))).toBe(true);
- });
- });
-
- test('flagged media is stripped for targets that do not allow it', async () => {
- const c = await createAnnouncementTargetGuild(harness, 'Filtered Community');
- await addGuildMember(harness, world.a.owner, world.a.guild, c.owner);
- await patchGuildRow(world.a.guild.id, {explicit_content_filter: GuildExplicitContentFilterTypes.DISABLED});
- await followInto(harness, world, world.b.t1.id);
- await followInto(harness, world, world.b.ageRestricted.id);
- await followInto(harness, world, c.t1.id, c.owner.token);
- await addGuildFeature(world.b.guild.id, GuildFeatures.DISCOVERABLE);
- await patchGuildRow(c.guild.id, {explicit_content_filter: GuildExplicitContentFilterTypes.ALL_MEMBERS});
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {
- content: 'mixed',
- embeds: [{title: 'Safe card'}, {title: 'Flagged card'}],
- });
- const row = (await readRow(world.a.ann.id, message.id))!;
- await writeRow(row, {
- attachments: row.attachments.map((attachment) => ({...attachment.toMessageAttachment(), nsfw: true})),
- embeds: row.embeds.map((embed, index) => ({...embed.toMessageEmbed(), nsfw: index === 1})),
- });
- await publishAndDrain(harness, world, message.id);
- for (const [token, channelId] of [
- [world.b.owner.token, world.b.t1.id],
- [c.owner.token, c.t1.id],
- ] as const) {
- const [copy] = await copiesOf(harness, token, channelId, message.id);
- const copyRow = (await readRow(channelId, copy!.id))!;
- expect(copyRow.attachments).toHaveLength(0);
- expect(copyRow.embeds.map((embed) => embed.title)).toEqual(['Safe card']);
- }
- const [restricted] = await copiesOf(harness, world.b.owner.token, world.b.ageRestricted.id, message.id);
- const restrictedRow = (await readRow(world.b.ageRestricted.id, restricted!.id))!;
- expect(restrictedRow.attachments).toHaveLength(1);
- expect(restrictedRow.embeds.map((embed) => embed.title)).toEqual(['Safe card', 'Flagged card']);
- });
-
- test('a sha blocklisted after publishing stops the fan-out', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'image'});
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- const blockedSha = 'cd'.repeat(32);
- const row = (await readRow(world.a.ann.id, message.id))!;
- await writeRow(row, {
- attachments: row.attachments.map((attachment) => ({
- ...attachment.toMessageAttachment(),
- content_hash: blockedSha,
- })),
- });
- fileShaCache.add(blockedSha);
- const logger: {warn(obj: object, message?: string): void} = Logger.child({});
- const warnSpy = vi.spyOn(logger, 'warn');
- try {
- await world.worker.drain();
- } finally {
- fileShaCache.remove(blockedSha);
- }
- await expectNoCopies(world.b.t1.id);
- expect(warnSpy.mock.calls.some(([, text]) => String(text).includes('blocked content'))).toBe(true);
- });
-
- test('an edit that removes and adds attachments reaches the copies', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'v1'}, [
- 'first.png',
- 'second.png',
- ]);
- await publishAndDrain(harness, world, message.id);
- const row = (await readRow(world.a.ann.id, message.id))!;
- const [first, second] = row.attachments;
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.attachments?.map((attachment) => attachment.id)).toEqual([
- first!.id.toString(),
- second!.id.toString(),
- ]);
- await createBuilder(harness, world.a.owner.token)
- .delete(`/channels/${world.a.ann.id}/messages/${message.id}/attachments/${second!.id}`)
- .expect(204)
- .execute();
- await world.worker.drain();
- let copyRow = (await readRow(world.b.t1.id, copy!.id))!;
- expect(copyRow.attachments.map((attachment) => attachment.id)).toEqual([first!.id]);
- const secondKey = `attachments/${world.a.ann.id}/${second!.id}/${second!.filename}`;
- expect(deletedKeys().filter((key) => key === secondKey)).toHaveLength(1);
- const extraId = first!.id + 1000n;
- const edited = (await readRow(world.a.ann.id, message.id))!;
- await writeRow(edited, {
- content: 'v2',
- attachments: [
- first!.toMessageAttachment(),
- {...first!.toMessageAttachment(), attachment_id: createAttachmentID(extraId), filename: 'extra.png'},
- ],
- });
- await enqueueCrosspostSync(world.worker, {
- channelId: createChannelID(BigInt(world.a.ann.id)),
- messageId: createMessageID(BigInt(message.id)),
- mode: 'update',
- });
- await world.worker.drain();
- copyRow = (await readRow(world.b.t1.id, copy!.id))!;
- expect(copyRow.content).toBe('v2');
- expect(copyRow.attachments.map((attachment) => [attachment.id, attachment.filename])).toEqual([
- [first!.id, first!.filename],
- [extraId, 'extra.png'],
- ]);
- const [synced] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(synced!.attachments?.[1]?.url).toContain(`/attachments/${world.a.ann.id}/${extraId}/extra.png`);
- expect(attachmentObjectCopies()).toEqual([]);
- expect(deletedKeys().some((key) => key.startsWith(`attachments/${world.b.t1.id}/`))).toBe(false);
- });
-
- test('a published message with large attachments reaches every copy without copying bytes', async () => {
- await followInto(harness, world, world.b.t1.id);
- await followInto(harness, world, world.b.t2.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'big'});
- const row = (await readRow(world.a.ann.id, message.id))!;
- const large = 500n * 1024n * 1024n;
- await writeRow(row, {
- attachments: row.attachments.map((attachment) => ({...attachment.toMessageAttachment(), size: large})),
- });
- await publishAndDrain(harness, world, message.id);
- for (const target of [world.b.t1, world.b.t2]) {
- const [copy] = await copiesOf(harness, world.b.owner.token, target.id, message.id);
- expect(copy!.attachments).toHaveLength(1);
- expect(copy!.attachments![0]!.size).toBe(Number(large));
- expect(copy!.attachments![0]!.id).toBe(row.attachments[0]!.id.toString());
- }
- expect(attachmentObjectCopies()).toEqual([]);
- });
-
- test('a failed target is retried with backoff and only the missing copy is created', async () => {
- const webhookT1 = await followInto(harness, world, world.b.t1.id);
- const webhookT2 = await followInto(harness, world, world.b.t2.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'retry'});
- failNextCopyCreate();
- await publishAndDrain(harness, world, message.id);
- const retries = world.worker
- .byTask('crosspostMessageChunk')
- .filter((job) => (job.payload as {attempt: number}).attempt === 1);
- expect(retries).toHaveLength(1);
- expect(retries[0]!.runAt).toBeInstanceOf(Date);
- expect((retries[0]!.payload as {webhookIds: Array<string>}).webhookIds).toHaveLength(1);
- expect([webhookT1, webhookT2]).toContain((retries[0]!.payload as {webhookIds: Array<string>}).webhookIds[0]);
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id)).toHaveLength(1);
- expect(await copiesOf(harness, world.b.owner.token, world.b.t2.id, message.id)).toHaveLength(1);
- });
-
- test('an edit racing the delivery ends in the copy', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'draft'});
- const gate = stallNextCopyCreate();
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- const draining = world.worker.drain();
- await gate.reached;
- await editRequest(harness, world.a.owner.token, world.a.ann.id, message.id, {content: 'final'})
- .expect(200)
- .execute();
- gate.release();
- await draining;
- await world.worker.drain();
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.content).toBe('final');
- });
-
- test('a delete racing the delivery leaves the copy marked as source deleted', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'short lived'});
- const gate = stallNextCopyCreate();
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- const draining = world.worker.drain();
- await gate.reached;
- await deleteMessageRequest(harness, world.a.owner.token, world.a.ann.id, message.id);
- gate.release();
- await draining;
- await world.worker.drain();
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.flags).toBe(MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED);
- expect(copy!.content).toBe(CROSSPOST_SOURCE_DELETED_CONTENT);
- expect(copy!.attachments ?? []).toHaveLength(0);
- });
-
- test('a sync between reserve and create keeps the pending row and the copy converges', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'one'});
- const gate = createStallGate();
- const original = MessagePersistenceService.prototype.createMessage;
- vi.spyOn(MessagePersistenceService.prototype, 'createMessage').mockImplementation(async function (
- this: MessagePersistenceService,
- params,
- ) {
- if (params.webhookId?.toString() === webhookId) {
- await gate.hit();
- }
- return original.call(this, params);
- });
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- const draining = world.worker.drain();
- await gate.reached;
- expect((await mappingRow(message.id, webhookId))?.state).toBe('pending');
- await editRequest(harness, world.a.owner.token, world.a.ann.id, message.id, {content: 'two'}).expect(200).execute();
- const syncCopies = (await import('@app/api/worker/tasks/SyncCrosspostCopies')).default;
- await syncCopies(
- {channelId: world.a.ann.id, messageId: message.id, mode: 'update', webhookIds: [webhookId]},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect((await mappingRow(message.id, webhookId))?.state).toBe('pending');
- gate.release();
- await draining;
- await world.worker.drain();
- let [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.content).toBe('two');
- await editRequest(harness, world.a.owner.token, world.a.ann.id, message.id, {content: 'three'})
- .expect(200)
- .execute();
- await world.worker.drain();
- [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.content).toBe('three');
- await deleteMessageRequest(harness, world.a.owner.token, world.a.ann.id, message.id);
- await world.worker.drain();
- [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.flags & MessageFlags.SOURCE_MESSAGE_DELETED).toBe(MessageFlags.SOURCE_MESSAGE_DELETED);
- });
-
- test('a copy moves the target last message id, is indexed and is dispatched to the target guild', async () => {
- await followInto(harness, world, world.b.t1.id);
- await patchChannelRow(world.b.t1.id, {indexed_at: new Date()});
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const indexSpy = vi.spyOn(MessageSearchService.prototype, 'indexMessage');
- const source = await postAndPublish(harness, world, {content: 'indexed'});
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id);
- const channel = await createBuilder<ChannelResponse>(harness, world.b.owner.token)
- .get(`/channels/${world.b.t1.id}`)
- .execute();
- expect(channel.last_message_id).toBe(copy!.id);
- expect(indexSpy.mock.calls.some(([message]) => message.id.toString() === copy!.id)).toBe(true);
- const created = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'MESSAGE_CREATE' && params.guildId.toString() === world.b.guild.id);
- expect(created.some((params) => (params.data as {id: string}).id === copy!.id)).toBe(true);
- });
-
- test('messages published before a follow are not backfilled', async () => {
- const source = await postAndPublish(harness, world, {content: 'before'});
- await followInto(harness, world, world.b.t1.id);
- await world.worker.drain();
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id)).toHaveLength(0);
- await follow(harness, world.b.owner.token, world.a.ann.id, world.b.t2.id);
- expect(await copiesOf(harness, world.b.owner.token, world.b.t2.id, source.id)).toHaveLength(0);
- });
- async function sendEmbeddedImage(content: string): Promise<{id: string; imageUrl: string}> {
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {
- content,
- embeds: [{title: 'Card', image: {url: 'attachment://yeah.png'}}],
- });
- const row = (await readRow(world.a.ann.id, message.id))!;
- expect(row.attachments).toHaveLength(0);
- return {id: message.id, imageUrl: row.embeds[0]!.toMessageEmbed().image!.url!};
- }
-
- test('a sha blocklisted on embed media after publishing stops the fan-out', async () => {
- await followInto(harness, world, world.b.t1.id);
- const source = await sendEmbeddedImage('blocked card');
- await publish(harness, world.a.owner.token, world.a.ann.id, source.id);
- const blockedSha = 'ef'.repeat(32);
- const row = (await readRow(world.a.ann.id, source.id))!;
- await writeRow(row, {
- embeds: row.embeds.map((embed) => {
- const value = embed.toMessageEmbed();
- return {...value, image: value.image ? {...value.image, content_hash: blockedSha} : value.image};
- }),
- });
- fileShaCache.add(blockedSha);
- try {
- await world.worker.drain();
- } finally {
- fileShaCache.remove(blockedSha);
- }
- await expectNoCopies(world.b.t1.id);
- expect(attachmentObjectCopies()).toEqual([]);
- });
-
- test('the worker blocklist caches load entries added after publishing', async () => {
- await followInto(harness, world, world.b.t1.id);
- const source = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {
- content: 'news with lateblockedphrase inside',
- });
- await publish(harness, world.a.owner.token, world.a.ann.id, source.id);
- await new AdminRepository().banPhrase('lateblockedphrase');
- await stopContentBlocklistCaches();
- await startContentBlocklistCaches({kvClient: getKVClient(), storageService: harness.storageService});
- try {
- await world.worker.drain();
- } finally {
- await stopContentBlocklistCaches();
- }
- await expectNoCopies(world.b.t1.id);
- });
-
- test('removing a copy never deletes target objects that a source embed points at', async () => {
- await followInto(harness, world, world.b.t1.id);
- const victim = await sendWithImage(harness, world.b.owner.token, world.b.t1.id, {content: 'mine'});
- const victimAttachment = (await readRow(world.b.t1.id, victim.id))!.attachments[0]!;
- const victimKey = `attachments/${world.b.t1.id}/${victimAttachment.id}/${victimAttachment.filename}`;
- expect(harness.storageService.hasObject(Config.s3.buckets.cdn, victimKey)).toBe(true);
- const source = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {
- content: 'look',
- embeds: [{title: 'Pointer', image: {url: 'https://example.com/pointer.png'}}],
- });
- const sourceRow = (await readRow(world.a.ann.id, source.id))!;
- const pointerUrl = `${Config.endpoints.media}/attachments/${world.b.t1.id}/${victimAttachment.id}/x.png`;
- await writeRow(sourceRow, {
- embeds: sourceRow.embeds.map((embed) => {
- const value = embed.toMessageEmbed();
- return {...value, image: {...value.image!, url: pointerUrl}};
- }),
- });
- await publishAndDrain(harness, world, source.id);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, source.id);
- expect((await readRow(world.b.t1.id, copy!.id))!.embeds[0]!.toMessageEmbed().image?.url).toBe(pointerUrl);
- await deleteMessageRequest(harness, world.a.owner.token, world.a.ann.id, source.id);
- await world.worker.drain();
- expect((await readRow(world.b.t1.id, copy!.id))!.flags).toBe(
- MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED,
- );
- expect(deletedKeys().some((key) => key.startsWith(`attachments/${world.b.t1.id}/${victimAttachment.id}/`))).toBe(
- false,
- );
- expect(harness.storageService.hasObject(Config.s3.buckets.cdn, victimKey)).toBe(true);
- });
-
- test('a delivered copy whose race check failed catches up on the retry', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'one'});
- const original = MessagePersistenceService.prototype.createMessage;
- vi.spyOn(MessagePersistenceService.prototype, 'createMessage').mockImplementation(async function (
- this: MessagePersistenceService,
- params,
- ) {
- if (params.webhookId?.toString() !== webhookId) {
- return original.call(this, params);
- }
- await writeRow((await readRow(world.a.ann.id, message.id))!, {content: 'two'});
- const created = await original.call(this, params);
- vi.spyOn(MessageWriteLock.prototype, 'withFreshMessage').mockRejectedValueOnce(new Error('lock hiccup'));
- return created;
- });
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- await world.worker.drain();
- expect(world.worker.byTask('crosspostMessageChunk').some((job) => job.payload.attempt === 1)).toBe(true);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.content).toBe('two');
- });
-
- test('an admin takedown racing the delivery deletes the copy instead of marking it', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'illegal'});
- const gate = createStallGate();
- const original = MessagePersistenceService.prototype.createMessage;
- vi.spyOn(MessagePersistenceService.prototype, 'createMessage').mockImplementation(async function (
- this: MessagePersistenceService,
- params,
- ) {
- if (params.webhookId?.toString() === webhookId) {
- await gate.hit();
- }
- return original.call(this, params);
- });
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- const draining = world.worker.drain();
- await gate.reached;
- const admin = await setUserACLs(harness, world.a.member, [AdminACLs.AUTHENTICATE, AdminACLs.MESSAGE_DELETE]);
- await createBuilder(harness, admin.token)
- .delete(`/admin/channels/${world.a.ann.id}/messages/${message.id}`)
- .body({basis: {type: 'housekeeping'}})
- .expect(200)
- .execute();
- gate.release();
- await draining;
- await world.worker.drain();
- await expectNoCopies(world.b.t1.id);
- expect(await mappingRow(message.id, webhookId)).toBeNull();
- });
-
- test('a failed copy create leaves no copy behind and the retry delivers once', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'files'});
- failNextCopyCreate(webhookId);
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- await crosspostMessageChunk(
- {channelId: world.a.ann.id, messageId: message.id, webhookIds: [webhookId], attempt: 0},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id)).toHaveLength(0);
- await world.worker.drain();
- expect(await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id)).toHaveLength(1);
- expect(attachmentObjectCopies()).toEqual([]);
- expect(deletedKeys().filter((key) => key.startsWith('attachments/'))).toEqual([]);
- });
-
- test('two syncs of one edit converge on the source attachments', async () => {
- const webhookId = await followInto(harness, world, world.b.t1.id);
- const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'v1'});
- await publishAndDrain(harness, world, message.id);
- const row = (await readRow(world.a.ann.id, message.id))!;
- const first = row.attachments[0]!;
- const extraId = first.id + 1n;
- await harness.storageService.uploadObject({
- bucket: Config.s3.buckets.cdn,
- key: `attachments/${world.a.ann.id}/${extraId}/extra.png`,
- body: loadFixture('yeah.png'),
- contentType: 'image/png',
- });
- await writeRow(row, {
- content: 'v2',
- attachments: [
- first.toMessageAttachment(),
- {...first.toMessageAttachment(), attachment_id: createAttachmentID(extraId), filename: 'extra.png'},
- ],
- });
- const arrive = createBarrier(2);
- const originalLock = MessageWriteLock.prototype.withFreshMessage;
- vi.spyOn(MessageWriteLock.prototype, 'withFreshMessage').mockImplementation(async function (
- this: MessageWriteLock,
- ...args: Parameters<MessageWriteLock['withFreshMessage']>
- ) {
- await arrive();
- return originalLock.apply(this, args);
- } as MessageWriteLock['withFreshMessage']);
- const payload = {
- channelId: world.a.ann.id,
- messageId: message.id,
- mode: 'update' as const,
- webhookIds: [webhookId],
- };
- const results = await Promise.allSettled([
- syncCrosspostCopies(
- payload,
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- ),
- syncCrosspostCopies(
- payload,
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- ),
- ]);
- vi.restoreAllMocks();
- expect(results.some((result) => result.status === 'fulfilled')).toBe(true);
- const [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.content).toBe('v2');
- const copyRow = (await readRow(world.b.t1.id, copy!.id))!;
- expect(copyRow.attachments.map((attachment) => attachment.id)).toEqual([first.id, extraId]);
- expect(attachmentObjectCopies()).toEqual([]);
- expect(deletedKeys().filter((key) => key.startsWith('attachments/'))).toEqual([]);
- });
-});
diff --git a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts b/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts
deleted file mode 100644
index 3b3675e15..000000000
--- a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts
+++ /dev/null
@@ -1,289 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {acceptInvite, createChannelInvite, createGuild, getChannel} from '@app/api/guild/tests/GuildTestUtils';
-import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {grantPremium} from '@app/api/user/tests/UserTestUtils';
-import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
-import {DEFAULT_DOMAIN_MIGRATION_CONFIG} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
-import {DEFAULT_VOICE_P2P_CONFIG} from '@fluxer/schema/src/domains/admin/VoiceP2pSchemas';
-import type {ExperimentAssignmentsResponse} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';
-import type {GeoipResult} from '@pkgs/geoip/src/GeoipLookup';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const {lookupGeoipMock} = vi.hoisted(() => ({
- lookupGeoipMock: vi.fn(),
-}));
-
-vi.mock('@app/api/utils/IpUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/api/utils/IpUtils')>()),
- lookupGeoip: lookupGeoipMock,
-}));
-
-function geoipCountry(countryCode: string | null): GeoipResult {
- return {
- countryCode,
- normalizedIp: '203.0.113.10',
- city: null,
- region: null,
- countryName: null,
- };
-}
-
-const NOT_MODIFIED = 304;
-const ENDPOINT = '/experiments';
-
-describe('GET /experiments', () => {
- let harness: ApiTestHarness;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- lookupGeoipMock.mockReset();
- lookupGeoipMock.mockResolvedValue(geoipCountry(null));
- });
-
- afterAll(async () => {
- await harness.shutdown();
- });
-
- it('assigns guild visits only to people the switch includes', async () => {
- const included = await createTestAccount(harness);
- const other = await createTestAccount(harness);
- await getInstanceConfigRepository().updateGuildVisitsConfig({
- enabled: true,
- included_user_ids: [included.userId],
- });
- });
-
- it('resolves the domain migration caller through the allowlist', async () => {
- const targeted = await createTestAccount(harness);
- const untargeted = await createTestAccount(harness);
- await getInstanceConfigRepository().setDomainMigrationConfig({
- ...DEFAULT_DOMAIN_MIGRATION_CONFIG,
- enabled: true,
- config_version: 4,
- rollout_basis_points: 0,
- included_user_ids: [targeted.userId],
- });
-
- const targetedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, targeted.token)
- .get(ENDPOINT)
- .execute();
- expect(targetedBody.assignments.domain_migration).toEqual({enabled: true});
-
- const untargetedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, untargeted.token)
- .get(ENDPOINT)
- .execute();
- expect(untargetedBody.assignments.domain_migration).toEqual({enabled: false});
- });
-
- it('keeps the domain migration exclusion ahead of a full rollout', async () => {
- const excluded = await createTestAccount(harness);
- await getInstanceConfigRepository().setDomainMigrationConfig({
- ...DEFAULT_DOMAIN_MIGRATION_CONFIG,
- enabled: true,
- rollout_basis_points: 10000,
- included_user_ids: [excluded.userId],
- excluded_user_ids: [excluded.userId],
- });
-
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, excluded.token).get(ENDPOINT).execute();
-
- expect(body.assignments.domain_migration).toEqual({enabled: false});
- });
-
- it('resolves the voice p2p caller through the allowlist and the exclusion list', async () => {
- const targeted = await createTestAccount(harness);
- const untargeted = await createTestAccount(harness);
- const excluded = await createTestAccount(harness);
- await getInstanceConfigRepository().setVoiceP2pConfig({
- ...DEFAULT_VOICE_P2P_CONFIG,
- enabled: true,
- rollout_basis_points: 0,
- included_user_ids: [targeted.userId, excluded.userId],
- excluded_user_ids: [excluded.userId],
- });
-
- const targetedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, targeted.token)
- .get(ENDPOINT)
- .execute();
- expect(targetedBody.assignments.voice_p2p).toEqual({enabled: true, max_participants: 2});
-
- const untargetedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, untargeted.token)
- .get(ENDPOINT)
- .execute();
- expect(untargetedBody.assignments.voice_p2p).toEqual({enabled: false, max_participants: 2});
-
- const excludedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, excluded.token)
- .get(ENDPOINT)
- .execute();
- expect(excludedBody.assignments.voice_p2p).toEqual({enabled: false, max_participants: 2});
- });
-
- it('limits the percentage rollout of every experiment to the listed request countries', async () => {
- const account = await createTestAccount(harness);
- const included = await createTestAccount(harness);
- const repository = getInstanceConfigRepository();
- const rollout = {enabled: true, rollout_basis_points: 10000, rollout_country_codes: ['SE', 'NO']};
- await repository.setDomainMigrationConfig({...DEFAULT_DOMAIN_MIGRATION_CONFIG, ...rollout});
- await repository.setVoiceP2pConfig({
- ...DEFAULT_VOICE_P2P_CONFIG,
- ...rollout,
- included_user_ids: [included.userId],
- });
-
- for (const [countryCode, expected] of [
- ['SE', true],
- ['BR', false],
- [null, false],
- ] as const) {
- lookupGeoipMock.mockResolvedValue(geoipCountry(countryCode));
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();
- expect(body.assignments.domain_migration).toEqual({enabled: expected});
- expect(body.assignments.voice_p2p).toEqual({enabled: expected, max_participants: 2});
- }
-
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const includedBody = await createBuilder<ExperimentAssignmentsResponse>(harness, included.token)
- .get(ENDPOINT)
- .execute();
- expect(includedBody.assignments.voice_p2p).toEqual({enabled: true, max_participants: 2});
- });
-
- it('enrols members of an included guild in every experiment and leaves everyone else out', async () => {
- const owner = await createTestAccount(harness);
- const member = await createTestAccount(harness);
- const outsider = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Experiment Guild');
- const systemChannel = await getChannel(harness, owner.token, guild.system_channel_id!);
- const invite = await createChannelInvite(harness, owner.token, systemChannel.id);
- await acceptInvite(harness, member.token, invite.code);
- const repository = getInstanceConfigRepository();
- await repository.setDomainMigrationConfig({
- ...DEFAULT_DOMAIN_MIGRATION_CONFIG,
- enabled: true,
- included_guild_ids: [guild.id],
- });
- await repository.setVoiceP2pConfig({
- ...DEFAULT_VOICE_P2P_CONFIG,
- enabled: true,
- included_guild_ids: [guild.id],
- });
-
- const memberBody = await createBuilder<ExperimentAssignmentsResponse>(harness, member.token)
- .get(ENDPOINT)
- .execute();
- expect(memberBody.assignments.domain_migration).toEqual({enabled: true});
- expect(memberBody.assignments.voice_p2p).toEqual({enabled: true, max_participants: 2});
-
- const outsiderBody = await createBuilder<ExperimentAssignmentsResponse>(harness, outsider.token)
- .get(ENDPOINT)
- .execute();
- expect(outsiderBody.assignments.domain_migration).toEqual({enabled: false});
- expect(outsiderBody.assignments.voice_p2p).toEqual({enabled: false, max_participants: 2});
- });
-
- it('enrols premium users, subscription and lifetime alike, when the switch is on', async () => {
- const subscriber = await createTestAccount(harness);
- const visionary = await createTestAccount(harness);
- const free = await createTestAccount(harness);
- await grantPremium(harness, subscriber.userId, UserPremiumTypes.SUBSCRIPTION);
- await grantPremium(harness, visionary.userId, UserPremiumTypes.LIFETIME);
- const repository = getInstanceConfigRepository();
- await repository.setDomainMigrationConfig({
- ...DEFAULT_DOMAIN_MIGRATION_CONFIG,
- enabled: true,
- include_premium_users: true,
- });
- await repository.setVoiceP2pConfig({
- ...DEFAULT_VOICE_P2P_CONFIG,
- enabled: true,
- include_premium_users: true,
- });
- for (const [account, expected] of [
- [subscriber, true],
- [visionary, true],
- [free, false],
- ] as const) {
- const body = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT).execute();
- expect(body.assignments.domain_migration).toEqual({enabled: expected});
- expect(body.assignments.voice_p2p).toEqual({enabled: expected, max_participants: 2});
- }
- });
-
- it('revalidates with a strong etag and answers 304 when nothing changed', async () => {
- const account = await createTestAccount(harness);
-
- const first = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
- .get(ENDPOINT)
- .executeWithResponse();
- const etag = first.response.headers.get('etag');
- expect(etag).toMatch(/^"[0-9a-f]{64}"$/);
- expect(first.response.headers.get('cache-control')).toBe('private, no-cache');
- expect(first.response.headers.get('vary')).toBe('Authorization, Origin');
-
- const revalidated = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
- .get(ENDPOINT)
- .header('If-None-Match', etag as string)
- .expect(NOT_MODIFIED)
- .executeWithResponse();
- expect(revalidated.response.status).toBe(NOT_MODIFIED);
- expect(revalidated.json).toBeUndefined();
- expect(revalidated.response.headers.get('etag')).toBe(etag);
- expect(revalidated.response.headers.get('vary')).toBe('Authorization, Origin');
- });
-
- it('serves a fresh body once the domain migration config changes', async () => {
- const account = await createTestAccount(harness);
-
- const first = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
- .get(ENDPOINT)
- .executeWithResponse();
- const staleEtag = first.response.headers.get('etag') as string;
-
- await getInstanceConfigRepository().setDomainMigrationConfig({
- ...DEFAULT_DOMAIN_MIGRATION_CONFIG,
- enabled: true,
- config_version: 1,
- rollout_basis_points: 10000,
- });
-
- const refreshed = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
- .get(ENDPOINT)
- .header('If-None-Match', staleEtag)
- .executeWithResponse();
- expect(refreshed.response.status).toBe(HTTP_STATUS.OK);
- expect(refreshed.response.headers.get('etag')).not.toBe(staleEtag);
- expect(refreshed.json?.assignments.domain_migration).toEqual({enabled: true});
- });
-
- it('serves a fresh body once the delivery config changes', async () => {
- const account = await createTestAccount(harness);
-
- const first = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
- .get(ENDPOINT)
- .executeWithResponse();
- const staleEtag = first.response.headers.get('etag') as string;
-
- await getInstanceConfigRepository().setExperimentDeliveryConfig({
- poll_interval_seconds: 1800,
- poll_jitter_percent: 5,
- });
-
- const refreshed = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token)
- .get(ENDPOINT)
- .header('If-None-Match', staleEtag)
- .executeWithResponse();
- expect(refreshed.response.status).toBe(HTTP_STATUS.OK);
- expect(refreshed.response.headers.get('etag')).not.toBe(staleEtag);
- expect(refreshed.json?.poll_interval_seconds).toBe(1800);
- expect(refreshed.json?.poll_jitter_percent).toBe(5);
- });
-});
diff --git a/fluxer_api/src/api/search/ThreadSearchScope.test.ts b/fluxer_api/src/api/search/ThreadSearchScope.test.ts
deleted file mode 100644
index ed17f8442..000000000
--- a/fluxer_api/src/api/search/ThreadSearchScope.test.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {type ChannelID, createChannelID, createGuildID, createUserID, type GuildID} from '@app/api/BrandedTypes';
-import {
- type CassandraQueryExecutorForTesting,
- setCassandraQueryExecutorForTesting,
- upsertOne,
-} from '@app/api/database/CassandraQueryExecution';
-import type {CassandraParams, KvQueryMeta, PreparedQuery} from '@app/api/database/CassandraTypes';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import {accessibleThreadIds} from '@app/api/search/ThreadSearchScope';
-import {ThreadsByParent} from '@app/api/Tables';
-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-vi.mock('@fluxer/constants/src/ThreadConstants', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@fluxer/constants/src/ThreadConstants')>()),
- THREAD_SCOPE_MAX: 300,
-}));
-
-const USER_ID = createUserID(1n);
-const GUILD_A = createGuildID(10n);
-const GUILD_B = createGuildID(20n);
-const PARENT_A = createChannelID(100n);
-const PARENT_B = createChannelID(200n);
-
-class CountingExecutor implements CassandraQueryExecutorForTesting {
- readonly inner = new InMemoryCassandraQueryExecutor();
- parentReads = 0;
-
- async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(
- query: PreparedQuery<P>,
- ): Promise<Array<T>> {
- if (query.kvMeta?.action === 'select' && query.kvMeta.table.name === ThreadsByParent.name) this.parentReads++;
- return this.inner.executeQuery<T>(query);
- }
-
- async executeBatch(
- queries: Array<{query: string; params: object; meta?: KvQueryMeta}>,
- atomic?: boolean,
- ): Promise<void> {
- await this.inner.executeBatch(queries, atomic);
- }
-}
-
-async function seedThreads(guildId: GuildID, parentId: ChannelID, from: bigint, count: number, type: number) {
- for (let offset = 0n; offset < BigInt(count); offset++) {
- await upsertOne(
- ThreadsByParent.upsertAll({
- parent_id: parentId,
- thread_id: createChannelID(from + offset),
- guild_id: guildId,
- type,
- }),
- );
- }
-}
-
-describe('accessibleThreadIds', () => {
- let executor: CountingExecutor;
-
- beforeEach(() => {
- executor = new CountingExecutor();
- setCassandraQueryExecutorForTesting(executor);
- });
-
- afterEach(() => {
- executor.inner.reset();
- setCassandraQueryExecutorForTesting(null);
- });
-
- it('merges guilds newest first and stops enumerating at the shared cap', async () => {
- await seedThreads(GUILD_A, PARENT_A, 1_000n, 600, ChannelTypes.PUBLIC_THREAD);
- await seedThreads(GUILD_B, PARENT_B, 2_000n, 600, ChannelTypes.PUBLIC_THREAD);
- await seedThreads(GUILD_B, PARENT_B, 3_000n, 1, ChannelTypes.PRIVATE_THREAD);
- const gatewayService = {getUserPermissions: vi.fn(async () => 0n)} as unknown as IGatewayService;
- executor.parentReads = 0;
-
- const scope = await accessibleThreadIds({
- gatewayService,
- userId: USER_ID,
- groups: [
- {guildId: GUILD_A, parentIds: [PARENT_A]},
- {guildId: GUILD_B, parentIds: [PARENT_B]},
- ],
- });
-
- expect(scope.size).toBe(300);
- expect([...scope.values()].every((parentId) => parentId === PARENT_B)).toBe(true);
- expect(scope.has('2599')).toBe(true);
- expect(scope.has('2299')).toBe(false);
- expect(scope.has('3000')).toBe(false);
- expect(executor.parentReads).toBe(3);
- });
-
- it('keeps the newest threads across many interleaved parents', async () => {
- const parents = Array.from({length: 40}, (_, index) => createChannelID(500n + BigInt(index)));
- for (const [index, parentId] of parents.entries()) {
- for (let step = 0n; step < 10n; step++) {
- await upsertOne(
- ThreadsByParent.upsertAll({
- parent_id: parentId,
- thread_id: createChannelID(10_000n + step * 40n + BigInt(index)),
- guild_id: GUILD_A,
- type: ChannelTypes.PUBLIC_THREAD,
- }),
- );
- }
- }
- const gatewayService = {getUserPermissions: vi.fn(async () => 0n)} as unknown as IGatewayService;
-
- const scope = await accessibleThreadIds({
- gatewayService,
- userId: USER_ID,
- groups: [{guildId: GUILD_A, parentIds: parents}],
- });
-
- expect([...scope.keys()]).toEqual(Array.from({length: 300}, (_, index) => String(10_399 - index)));
- expect(scope.get('10399')).toBe(parents[39]);
- });
-});
diff --git a/fluxer_api/src/api/stripe/tests/StripeCheckoutCountryEnforcement.test.ts b/fluxer_api/src/api/stripe/tests/StripeCheckoutCountryEnforcement.test.ts
deleted file mode 100644
index f21b7d560..000000000
--- a/fluxer_api/src/api/stripe/tests/StripeCheckoutCountryEnforcement.test.ts
+++ /dev/null
@@ -1,203 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {Config} from '@app/api/Config';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createStripeApiHandlers, type StripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';
-import {server} from '@app/api/test/msw/server';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import type {GeoipResult} from '@pkgs/geoip/src/GeoipLookup';
-import {afterAll, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const {lookupGeoipMock} = vi.hoisted(() => ({
- lookupGeoipMock: vi.fn(),
-}));
-
-vi.mock('@app/api/utils/IpUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/api/utils/IpUtils')>()),
- lookupGeoip: lookupGeoipMock,
-}));
-
-const MOCK_PRICES = {
- monthlyUsd: 'price_enforce_monthly_usd',
- yearlyUsd: 'price_enforce_yearly_usd',
- monthlyBrl: 'price_enforce_monthly_brl',
- yearlyBrl: 'price_enforce_yearly_brl',
- gift1MonthUsd: 'price_enforce_gift_1_month_usd',
- gift1YearUsd: 'price_enforce_gift_1_year_usd',
- gift1MonthBrl: 'price_enforce_gift_1_month_brl',
- gift1YearBrl: 'price_enforce_gift_1_year_brl',
-};
-
-const MOCK_PRICE_SEEDS = {
- [MOCK_PRICES.monthlyUsd]: {unit_amount: 499, currency: 'usd', interval: 'month' as const},
- [MOCK_PRICES.yearlyUsd]: {unit_amount: 4999, currency: 'usd', interval: 'year' as const},
- [MOCK_PRICES.monthlyBrl]: {unit_amount: 1890, currency: 'brl', interval: 'month' as const},
- [MOCK_PRICES.yearlyBrl]: {unit_amount: 18900, currency: 'brl', interval: 'year' as const},
-};
-
-function geoipCountry(countryCode: string | null): GeoipResult {
- return {
- countryCode,
- normalizedIp: '203.0.113.10',
- city: null,
- region: null,
- countryName: null,
- };
-}
-
-describe('StripeCheckoutCountryEnforcement', () => {
- let harness: ApiTestHarness;
- let stripeHandlers: StripeApiHandlers;
- let originalPrices: typeof Config.stripe.prices | undefined;
-
- async function createPurchaser(): Promise<string> {
- const account = await createTestAccount(harness);
- await createBuilder(harness, account.token)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: true})
- .execute();
- return account.token;
- }
-
- beforeAll(async () => {
- originalPrices = Config.stripe.prices;
- Config.stripe.prices = MOCK_PRICES;
- harness = await createApiTestHarness();
- });
- afterAll(async () => {
- await harness.shutdown();
- Config.stripe.prices = originalPrices;
- });
- beforeEach(() => {
- Config.stripe.prices = MOCK_PRICES;
- lookupGeoipMock.mockReset();
- lookupGeoipMock.mockResolvedValue(geoipCountry(null));
- stripeHandlers = createStripeApiHandlers({prices: MOCK_PRICE_SEEDS, subscriptionsListEmpty: true});
- server.use(...stripeHandlers.handlers);
- });
-
- test('rejects a base-currency subscription price when the request geolocates to a localized market', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- await createBuilder(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyUsd, country_code: 'US'})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.STRIPE_INVALID_PRODUCT_CONFIGURATION)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
-
- test('rejects a base-currency subscription price when country_code is omitted entirely', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- await createBuilder(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyUsd})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.STRIPE_INVALID_PRODUCT_CONFIGURATION)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
-
- test('rejects a localized gift price when the request geolocates outside that market', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('US'));
- const token = await createPurchaser();
- await createBuilder(harness, token)
- .post('/stripe/checkout/gift')
- .body({price_id: MOCK_PRICES.gift1MonthBrl, country_code: 'BR'})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.STRIPE_INVALID_PRODUCT_CONFIGURATION)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
-
- test('rejects a localized gift price even from inside that market', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- await createBuilder(harness, token)
- .post('/stripe/checkout/gift')
- .body({price_id: MOCK_PRICES.gift1MonthBrl, country_code: 'BR'})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.STRIPE_INVALID_PRODUCT_CONFIGURATION)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
-
- test('accepts the base gift price from inside a localized market', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- const response = await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/gift')
- .body({price_id: MOCK_PRICES.gift1MonthUsd, country_code: 'BR'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.url).toContain('checkout.stripe.com');
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- });
-
- test('accepts the localized price for a request that geolocates to that market', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- const response = await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyBrl, country_code: 'BR'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.url).toContain('checkout.stripe.com');
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- });
-
- test('falls back to the declared country when the request cannot be geolocated', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry(null));
- const token = await createPurchaser();
- const response = await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyBrl, country_code: 'BR'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.url).toContain('checkout.stripe.com');
- });
-
- test('resolves price ids from the request geolocation rather than the query parameter', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const priceIds = await createBuilder<{currency: string; monthly: string | null}>(harness, '')
- .get('/premium/price-ids?country_code=US')
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(priceIds.currency).toBe('BRL');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyBrl);
- });
- test('offers pix and nothing else for a localized BRL subscription', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyBrl, country_code: 'BR'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- expect(stripeHandlers.spies.createdCheckoutSessions[0].payment_method_types).toEqual(['pix']);
- });
-
- test('forces pix even when the caller explicitly asks for card on a BRL subscription', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('BR'));
- const token = await createPurchaser();
- await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyBrl, country_code: 'BR', payment_method: 'card'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions[0].payment_method_types).toEqual(['pix']);
- });
-
- test('leaves payment methods open for a base-currency subscription', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('US'));
- const token = await createPurchaser();
- await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyUsd, country_code: 'US'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions[0].payment_method_types).toBeUndefined();
- });
-});
diff --git a/fluxer_api/src/api/stripe/tests/StripeGiftSubscriptionShift.test.ts b/fluxer_api/src/api/stripe/tests/StripeGiftSubscriptionShift.test.ts
deleted file mode 100644
index 608e1efab..000000000
--- a/fluxer_api/src/api/stripe/tests/StripeGiftSubscriptionShift.test.ts
+++ /dev/null
@@ -1,790 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {randomUUID} from 'node:crypto';
-import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createUserID, type UserID} from '@app/api/BrandedTypes';
-import {Config} from '@app/api/Config';
-import type {UserRow} from '@app/api/database/types/UserTypes';
-import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
-import type {GuildService} from '@app/api/guild/services/GuildService';
-import {getCacheService, getPremiumStateReconciliationQueueService} from '@app/api/middleware/ServiceSingletons';
-import {addGiftCodeDuration} from '@app/api/models/GiftCode';
-import {findUser, uninstallStoreBillingWorker} from '@app/api/store_billing/tests/StoreBillingTestUtils';
-import {getStripeClient} from '@app/api/stripe/StripeClient';
-import {StripeGiftReversalHandler} from '@app/api/stripe/services/StripeGiftReversalHandler';
-import {StripePremiumService} from '@app/api/stripe/services/StripePremiumService';
-import {StripeSubscriptionService} from '@app/api/stripe/services/StripeSubscriptionService';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {
- createStripeApiHandlers,
- createSubscriptionDeletedEvent,
- type StripeApiHandlers,
-} from '@app/api/test/msw/handlers/StripeApiHandlers';
-import {server} from '@app/api/test/msw/server';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
-import type {GeoipResult} from '@pkgs/geoip/src/GeoipLookup';
-import {ms} from 'itty-time';
-import {HttpResponse, http} from 'msw';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const {lookupGeoipMock} = vi.hoisted(() => ({
- lookupGeoipMock: vi.fn(),
-}));
-
-vi.mock('@app/api/utils/IpUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/api/utils/IpUtils')>()),
- lookupGeoip: lookupGeoipMock,
-}));
-
-const MOCK_PRICES = {
- monthlyUsd: 'price_shift_monthly_usd',
- yearlyUsd: 'price_shift_yearly_usd',
- gift1MonthUsd: 'price_shift_gift_1_month_usd',
- gift1YearUsd: 'price_shift_gift_1_year_usd',
-};
-
-const MOCK_PRICE_SEEDS = {
- [MOCK_PRICES.monthlyUsd]: {unit_amount: 499, currency: 'usd', interval: 'month' as const},
- [MOCK_PRICES.yearlyUsd]: {unit_amount: 4999, currency: 'usd', interval: 'year' as const},
-};
-
-const CLOCK_TOLERANCE_MS = ms('10 seconds');
-
-type WriteOrder = 'checkout first' | 'webhook first';
-
-const WRITE_ORDERS: Array<WriteOrder> = ['checkout first', 'webhook first'];
-
-function geoipCountry(countryCode: string | null): GeoipResult {
- return {countryCode, normalizedIp: '203.0.113.10', city: null, region: null, countryName: null};
-}
-
-function giftTrialMetadata(code: string, days: number, paidUntilUnix?: number): Record<string, string> {
- return {
- [`gtrial_${code}`]: String(days * 24 * 60 * 60),
- ...(paidUntilUnix ? {gtrial_paid_until: String(paidUntilUnix)} : {}),
- };
-}
-
-function expectNear(actual: Date | null | undefined, expectedMs: number): void {
- expect(actual).not.toBeNull();
- expect(Math.abs(actual!.getTime() - expectedMs)).toBeLessThanOrEqual(CLOCK_TOLERANCE_MS);
-}
-
-describe('gift time around a Stripe subscription', () => {
- let harness: ApiTestHarness;
- let stripeHandlers: StripeApiHandlers;
- let originalPrices: typeof Config.stripe.prices | undefined;
- const users = new UserRepository();
- const premiumService = new StripePremiumService(
- users,
- new NoopGatewayService(),
- {} as GuildRepository,
- {} as GuildService,
- );
-
- beforeAll(async () => {
- originalPrices = Config.stripe.prices;
- Config.stripe.prices = MOCK_PRICES;
- harness = await createApiTestHarness();
- });
- afterAll(async () => {
- await harness.shutdown();
- Config.stripe.prices = originalPrices;
- });
- beforeEach(async () => {
- await harness.resetData();
- Config.stripe.prices = MOCK_PRICES;
- lookupGeoipMock.mockReset();
- lookupGeoipMock.mockResolvedValue(geoipCountry(null));
- useStripe();
- });
- afterEach(() => {
- server.resetHandlers();
- });
-
- function useStripe(config: Parameters<typeof createStripeApiHandlers>[0] = {}): void {
- stripeHandlers = createStripeApiHandlers({prices: MOCK_PRICE_SEEDS, ...config});
- server.use(...stripeHandlers.handlers);
- }
-
- async function createUser(patch: Partial<UserRow>): Promise<{account: TestAccount; userId: UserID}> {
- const account = await createTestAccount(harness);
- const userId = createUserID(BigInt(account.userId));
- const user = await findUser(account.userId);
- await users.patchUpsert(userId, patch, user.toRow());
- return {account, userId};
- }
-
- async function checkoutWrite(userId: UserID, periodEnd: Date, periodStart: Date | null = null): Promise<void> {
- await premiumService.setPremiumFromSubscriptionPeriod(userId, periodEnd, 'monthly', true, null, periodStart);
- }
-
- async function webhookWrite(userId: UserID, periodEnd: Date, periodStart: Date | null = null): Promise<void> {
- await users.updateSubscriptionStatus(userId, {
- premiumWillCancel: false,
- computedPremiumUntil: periodEnd,
- periodStart,
- });
- }
-
- async function writeBoth(
- order: WriteOrder,
- userId: UserID,
- periodEnd: Date,
- periodStart: Date | null = null,
- ): Promise<void> {
- if (order === 'checkout first') {
- await checkoutWrite(userId, periodEnd, periodStart);
- await webhookWrite(userId, periodEnd, periodStart);
- return;
- }
- await webhookWrite(userId, periodEnd, periodStart);
- await checkoutWrite(userId, periodEnd, periodStart);
- }
-
- function newGiftCode(): string {
- return `giftshift${randomUUID().replaceAll('-', '').slice(0, 20)}`;
- }
-
- async function createRedeemedGift(
- redeemerId: UserID,
- redeemedAt: Date,
- duration: {type: 'days' | 'months'; quantity: number},
- code: string = newGiftCode(),
- ): Promise<string> {
- const gifter = await createTestAccount(harness);
- await users.createGiftCode({
- code,
- duration_months: null,
- duration_type: duration.type,
- duration_quantity: duration.quantity,
- created_at: redeemedAt,
- created_by_user_id: createUserID(BigInt(gifter.userId)),
- redeemed_at: redeemedAt,
- redeemed_by_user_id: redeemerId,
- stripe_payment_intent_id: `pi_${code}`,
- visionary_sequence_number: null,
- checkout_session_id: null,
- version: 1,
- });
- return code;
- }
-
- async function reverseGift(code: string): Promise<void> {
- const handler = new StripeGiftReversalHandler(
- users,
- new NoopGatewayService(),
- getPremiumStateReconciliationQueueService(),
- );
- const gift = await users.findGiftCode(code);
- await handler.handleGiftPremiumReversal(gift!, {reason: 'gift_chargeback'});
- }
-
- describe('subscribing while gift time is left', () => {
- test.each(WRITE_ORDERS)(
- 'moves an active gift past the paid period when premium_until is empty (%s)',
- async (order) => {
- const giftEnd = new Date(Date.now() + ms('10 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: null,
- premium_gift_extension_ends_at: giftEnd,
- });
- const periodEnd = new Date(Date.now() + ms('30 days'));
-
- await writeBoth(order, userId, periodEnd);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(periodEnd.getTime());
- expectNear(after.premiumGiftExtensionEndsAt, periodEnd.getTime() + ms('10 days'));
- },
- );
-
- test.each(WRITE_ORDERS)('anchors at now when premium_until is a stale past date (%s)', async (order) => {
- const giftEnd = new Date(Date.now() + ms('10 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: new Date(Date.now() - ms('60 days')),
- premium_gift_extension_ends_at: giftEnd,
- });
- const periodEnd = new Date(Date.now() + ms('30 days'));
-
- await writeBoth(order, userId, periodEnd);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(periodEnd.getTime());
- expectNear(after.premiumGiftExtensionEndsAt, periodEnd.getTime() + ms('10 days'));
- });
-
- test.each(WRITE_ORDERS)('leaves an expired gift alone when premium_until is stale (%s)', async (order) => {
- const giftEnd = new Date(Date.now() - ms('5 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: new Date(Date.now() - ms('60 days')),
- premium_gift_extension_ends_at: giftEnd,
- });
- const periodEnd = new Date(Date.now() + ms('30 days'));
-
- await writeBoth(order, userId, periodEnd);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(periodEnd.getTime());
- expect(after.premiumGiftExtensionEndsAt?.getTime()).toBe(giftEnd.getTime());
- });
-
- test('shifts the gift once when checkout.session.completed is replayed', async () => {
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_gift_extension_ends_at: new Date(Date.now() + ms('10 days')),
- });
- const periodEnd = new Date(Date.now() + ms('30 days'));
-
- await checkoutWrite(userId, periodEnd);
- const first = await findUser(account.userId);
- await checkoutWrite(userId, periodEnd);
-
- const replayed = await findUser(account.userId);
- expect(replayed.premiumGiftExtensionEndsAt?.getTime()).toBe(first.premiumGiftExtensionEndsAt?.getTime());
- });
-
- test.each(WRITE_ORDERS)('moves a stacked gift along on renewal (%s)', async (order) => {
- const premiumUntil = new Date(Date.now() + ms('1 hour'));
- const giftEnd = new Date(premiumUntil.getTime() + ms('10 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: premiumUntil,
- premium_gift_extension_ends_at: giftEnd,
- });
- const renewedUntil = new Date(premiumUntil.getTime() + ms('30 days'));
-
- await writeBoth(order, userId, renewedUntil);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(renewedUntil.getTime());
- expect(after.premiumGiftExtensionEndsAt?.getTime()).toBe(giftEnd.getTime() + ms('30 days'));
- });
-
- test.each(WRITE_ORDERS)('keeps every gift day when a renewal is paid late (%s)', async (order) => {
- const premiumUntil = new Date(Date.now() - ms('6 days'));
- const giftEnd = new Date(premiumUntil.getTime() + ms('60 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: premiumUntil,
- premium_gift_extension_ends_at: giftEnd,
- premium_grace_ends_at: new Date(premiumUntil.getTime() + ms('14 days')),
- });
- const renewedUntil = new Date(premiumUntil.getTime() + ms('30 days'));
-
- await writeBoth(order, userId, renewedUntil, premiumUntil);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(renewedUntil.getTime());
- expect(after.premiumGiftExtensionEndsAt?.getTime()).toBe(giftEnd.getTime() + ms('30 days'));
- });
-
- test.each(WRITE_ORDERS)(
- 'moves the gift by the whole period when the first payment lands late (%s)',
- async (order) => {
- const periodStart = new Date(Date.now() - ms('2 days'));
- const giftEnd = new Date(Date.now() + ms('10 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: null,
- premium_gift_extension_ends_at: giftEnd,
- });
- const periodEnd = new Date(periodStart.getTime() + ms('30 days'));
-
- await writeBoth(order, userId, periodEnd, periodStart);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(periodEnd.getTime());
- expect(after.premiumGiftExtensionEndsAt?.getTime()).toBe(giftEnd.getTime() + ms('30 days'));
- },
- );
-
- test('lets a user with gift time left start a subscription checkout', async () => {
- const {account} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_until: new Date(Date.now() - ms('60 days')),
- premium_gift_extension_ends_at: new Date(Date.now() + ms('10 days')),
- });
- useStripe({subscriptionsListEmpty: true});
- await createBuilder(harness, account.token)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: true})
- .execute();
-
- await createBuilder(harness, account.token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyUsd})
- .expect(HTTP_STATUS.OK)
- .execute();
-
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- });
-
- test('still refuses a recurring checkout for a Visionary', async () => {
- const {account} = await createUser({premium_type: UserPremiumTypes.LIFETIME, premium_lifetime_sequence: 7});
- await createBuilder(harness, account.token)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: true})
- .execute();
-
- await createBuilder(harness, account.token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyUsd})
- .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.PREMIUM_PURCHASE_BLOCKED)
- .execute();
- });
-
- test('still refuses a recurring checkout while a past_due subscription exists', async () => {
- const {account} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_customer_id: 'cus_shift_past_due',
- premium_gift_extension_ends_at: new Date(Date.now() + ms('10 days')),
- });
- useStripe({subscriptions: {sub_shift_past_due: {customer: 'cus_shift_past_due', status: 'past_due'}}});
- await createBuilder(harness, account.token)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: true})
- .execute();
-
- const error = await createBuilder<{data?: {reason?: string}}>(harness, account.token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyUsd})
- .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.PREMIUM_PURCHASE_BLOCKED)
- .execute();
-
- expect(JSON.stringify(error)).toContain('existing_subscription');
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
- });
-
- describe('refunds', () => {
- test('a refund keeps only the gift part of a gift trial', async () => {
- const subscriptionId = 'sub_shift_refund_trial';
- const paidUntil = Math.floor((Date.now() + ms('28 days')) / 1000);
- const trialEnd = paidUntil + 30 * 24 * 60 * 60;
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- trial_end: trialEnd,
- status: 'trialing',
- metadata: giftTrialMetadata(newGiftCode(), 30, paidUntil),
- },
- },
- });
- const {account} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_billing_cycle: 'monthly',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- const subscriptionService = new StripeSubscriptionService(
- getStripeClient(),
- users,
- {getRecurringSubscriptionPriceId: () => null, getProduct: () => null},
- getCacheService(),
- new NoopGatewayService(),
- );
-
- await subscriptionService.cancelSubscriptionImmediately(
- createUserID(BigInt(account.userId)),
- 'self_serve_refund',
- );
-
- const after = await findUser(account.userId);
- expectNear(after.premiumUntil, Date.now());
- expectNear(after.premiumGiftExtensionEndsAt, Date.now() + ms('30 days'));
- });
-
- test('a refund right after subscribing keeps only the real gift remainder', async () => {
- const subscriptionId = 'sub_shift_refund';
- const premiumUntil = new Date(Date.now() + ms('28 days'));
- const {account} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_billing_cycle: 'monthly',
- premium_until: premiumUntil,
- premium_gift_extension_ends_at: new Date(premiumUntil.getTime() + ms('10 days')),
- });
- const subscriptionService = new StripeSubscriptionService(
- getStripeClient(),
- users,
- {getRecurringSubscriptionPriceId: () => null, getProduct: () => null},
- getCacheService(),
- new NoopGatewayService(),
- );
-
- await subscriptionService.cancelSubscriptionImmediately(
- createUserID(BigInt(account.userId)),
- 'self_serve_refund',
- );
-
- const after = await findUser(account.userId);
- expect(stripeHandlers.spies.cancelledSubscriptions).toContain(subscriptionId);
- expect(after.premiumType).toBe(UserPremiumTypes.SUBSCRIPTION);
- expectNear(after.premiumUntil, Date.now());
- expectNear(after.premiumGiftExtensionEndsAt, Date.now() + ms('10 days'));
- });
- });
-
- describe('gift reversals', () => {
- test('removes a gift that was moved past the paid period', async () => {
- const premiumUntil = new Date(Date.now() + ms('30 days'));
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: 'sub_shift_charge_now',
- stripe_customer_id: 'cus_test_1',
- premium_until: premiumUntil,
- premium_gift_extension_ends_at: new Date(premiumUntil.getTime() + ms('20 days')),
- });
- const code = await createRedeemedGift(userId, new Date(Date.now() - ms('10 days')), {type: 'days', quantity: 30});
-
- await reverseGift(code);
-
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(premiumUntil.getTime());
- expect(after.premiumGiftExtensionEndsAt).toBeNull();
- expect(stripeHandlers.spies.updatedSubscriptions).toHaveLength(0);
- });
-
- test('shortens the Stripe trial by the reversed gift once', async () => {
- const subscriptionId = 'sub_shift_gift_trial';
- const trialEnd = Math.floor((Date.now() + ms('50 days')) / 1000);
- const code = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {trial_end: trialEnd, status: 'trialing', metadata: giftTrialMetadata(code, 30)},
- },
- });
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('1 hour')), {type: 'days', quantity: 30}, code);
-
- await reverseGift(code);
- await reverseGift(code);
-
- const shortenedEnd = trialEnd - 30 * 24 * 60 * 60;
- expect(stripeHandlers.spies.updatedSubscriptions).toHaveLength(1);
- expect(stripeHandlers.spies.updatedSubscriptions[0]?.id).toBe(subscriptionId);
- expect(Number(stripeHandlers.spies.updatedSubscriptions[0]?.params.trial_end)).toBe(shortenedEnd);
- expect(stripeHandlers.spies.updatedSubscriptions[0]?.params.metadata).toEqual({[`gtrial_${code}`]: ''});
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(shortenedEnd * 1000);
- expect(after.premiumGiftExtensionEndsAt).toBeNull();
- const gift = await users.findGiftCode(code);
- expect(gift?.premiumReversedSeconds).toBe(30 * 24 * 60 * 60);
- });
-
- test('ends the trial now when the reversed gift is already being used', async () => {
- const subscriptionId = 'sub_shift_gift_trial_used';
- const trialEnd = Math.floor((Date.now() + ms('10 days')) / 1000);
- const code = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {trial_end: trialEnd, status: 'trialing', metadata: giftTrialMetadata(code, 30)},
- },
- });
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('20 days')), {type: 'days', quantity: 30}, code);
-
- await reverseGift(code);
-
- expect(stripeHandlers.spies.updatedSubscriptions).toHaveLength(1);
- expect(stripeHandlers.spies.updatedSubscriptions[0]?.params.trial_end).toBe('now');
- expect(stripeHandlers.spies.cancelledSubscriptions).toHaveLength(0);
- const after = await findUser(account.userId);
- expectNear(after.premiumUntil, Date.now());
- });
-
- test('cancels a cancelling subscription instead of charging when the gift is already being used', async () => {
- const subscriptionId = 'sub_shift_gift_trial_cancelling';
- const trialEnd = Math.floor((Date.now() + ms('10 days')) / 1000);
- const code = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- trial_end: trialEnd,
- status: 'trialing',
- cancel_at_period_end: true,
- metadata: giftTrialMetadata(code, 30),
- },
- },
- });
- const {userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_will_cancel: true,
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('20 days')), {type: 'days', quantity: 30}, code);
-
- await reverseGift(code);
-
- expect(stripeHandlers.spies.cancelledSubscriptions).toEqual([subscriptionId]);
- expect(stripeHandlers.spies.updatedSubscriptions).toHaveLength(0);
- });
-
- test('releases the reversal claim when Stripe refuses the trial change', async () => {
- const subscriptionId = 'sub_shift_gift_trial_fail';
- const trialEnd = Math.floor((Date.now() + ms('50 days')) / 1000);
- const code = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {trial_end: trialEnd, status: 'trialing', metadata: giftTrialMetadata(code, 30)},
- },
- });
- server.use(
- http.post('https://api.stripe.com/v1/subscriptions/:id', () =>
- HttpResponse.json(
- {error: {type: 'invalid_request_error', message: 'Mock trial update failure'}},
- {status: 400},
- ),
- ),
- );
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('1 hour')), {type: 'days', quantity: 30}, code);
-
- await expect(reverseGift(code)).rejects.toThrow();
-
- expect((await users.findGiftCode(code))?.premiumReversedSeconds).toBeNull();
- expect((await findUser(account.userId)).premiumUntil?.getTime()).toBe(trialEnd * 1000);
- });
-
- test('cuts a month gift back to exactly the paid period end', async () => {
- const subscriptionId = 'sub_shift_gift_trial_month';
- const paidUntil = Math.floor((Date.now() + ms('15 days')) / 1000);
- const trialEnd = paidUntil + 28 * 24 * 60 * 60;
- const code = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- trial_end: trialEnd,
- status: 'trialing',
- metadata: giftTrialMetadata(code, 28, paidUntil),
- },
- },
- });
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('1 hour')), {type: 'months', quantity: 1}, code);
-
- await reverseGift(code);
-
- expect(Number(stripeHandlers.spies.updatedSubscriptions[0]?.params.trial_end)).toBe(paidUntil);
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(paidUntil * 1000);
- expect(after.premiumGiftExtensionEndsAt).toBeNull();
- });
-
- test('never cuts the trial below the paid period end', async () => {
- const subscriptionId = 'sub_shift_gift_trial_floor';
- const paidUntil = Math.floor((Date.now() + ms('15 days')) / 1000);
- const trialEnd = paidUntil + 20 * 24 * 60 * 60;
- const code = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- trial_end: trialEnd,
- status: 'trialing',
- metadata: giftTrialMetadata(code, 30, paidUntil),
- },
- },
- });
- const {userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(trialEnd * 1000),
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('1 hour')), {type: 'days', quantity: 30}, code);
-
- await reverseGift(code);
-
- expect(Number(stripeHandlers.spies.updatedSubscriptions[0]?.params.trial_end)).toBe(paidUntil);
- });
-
- test('leaves the trial alone when the reversed gift was not stacked onto it', async () => {
- const subscriptionId = 'sub_shift_gift_trial_other';
- const paidUntil = Math.floor((Date.now() + ms('10 days')) / 1000);
- const trialEnd = paidUntil + 30 * 24 * 60 * 60;
- const stackedCode = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- trial_end: trialEnd,
- status: 'trialing',
- metadata: giftTrialMetadata(stackedCode, 30, paidUntil),
- },
- },
- });
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(Date.now() + ms('55 days')),
- });
- const plainCode = await createRedeemedGift(userId, new Date(Date.now() - ms('5 days')), {
- type: 'days',
- quantity: 30,
- });
- await createRedeemedGift(userId, new Date(Date.now() - ms('1 hour')), {type: 'days', quantity: 30}, stackedCode);
-
- await reverseGift(plainCode);
-
- expect(stripeHandlers.spies.updatedSubscriptions).toHaveLength(0);
- expect(stripeHandlers.spies.cancelledSubscriptions).toHaveLength(0);
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(trialEnd * 1000);
- expect(after.premiumGiftExtensionEndsAt!.getTime()).toBeLessThanOrEqual(trialEnd * 1000);
- });
-
- test("keeps the paid shift of the user's other gifts", async () => {
- const subscriptionId = 'sub_shift_gift_trial_keep_shift';
- const now = Date.now();
- const paidUntil = Math.floor((now + ms('10 days')) / 1000);
- const trialEnd = paidUntil + 30 * 24 * 60 * 60;
- const stackedCode = newGiftCode();
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- trial_end: trialEnd,
- status: 'trialing',
- metadata: giftTrialMetadata(stackedCode, 30, paidUntil),
- },
- },
- });
- const firstRedeemedAt = new Date(now - ms('150 days'));
- const firstGiftBaseEnd = firstRedeemedAt.getTime() + ms('365 days');
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_until: new Date(trialEnd * 1000),
- premium_gift_extension_ends_at: new Date(firstGiftBaseEnd + ms('120 days') + ms('30 days')),
- });
- await createRedeemedGift(userId, firstRedeemedAt, {type: 'days', quantity: 365});
- await createRedeemedGift(userId, new Date(now - ms('1 hour')), {type: 'days', quantity: 30}, stackedCode);
-
- await reverseGift(stackedCode);
-
- expect(Number(stripeHandlers.spies.updatedSubscriptions[0]?.params.trial_end)).toBe(paidUntil);
- const after = await findUser(account.userId);
- expect(after.premiumUntil?.getTime()).toBe(paidUntil * 1000);
- expect(after.premiumGiftExtensionEndsAt?.getTime()).toBe(firstGiftBaseEnd + ms('120 days'));
- });
- });
-
- describe('redeeming a gift onto a running subscription', () => {
- test('records the stacked trial once whichever write lands first', async () => {
- const subscriptionId = 'sub_shift_stack';
- const periodEnd = Math.floor((Date.now() + ms('20 days')) / 1000);
- useStripe({
- subscriptions: {
- [subscriptionId]: {current_period_start: periodEnd - 30 * 24 * 60 * 60, current_period_end: periodEnd},
- },
- });
- const {account, userId} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_billing_cycle: 'monthly',
- premium_until: new Date(periodEnd * 1000),
- });
- const gifter = await createTestAccount(harness);
- await createBuilder(harness, gifter.token)
- .post('/test/gifts/SHIFTSTACKGIFT')
- .body({duration_type: 'days', duration_quantity: 30, created_by_user_id: gifter.userId})
- .execute();
-
- await createBuilder(harness, account.token).post('/gifts/SHIFTSTACKGIFT/redeem').expect(204).execute();
-
- const trialEnd = new Date((periodEnd + 30 * 24 * 60 * 60) * 1000);
- expect(stripeHandlers.spies.updatedSubscriptions[0]?.params.metadata).toEqual({
- gtrial_SHIFTSTACKGIFT: String(30 * 24 * 60 * 60),
- gtrial_paid_until: String(periodEnd),
- });
- const redeemed = await findUser(account.userId);
- expect(redeemed.premiumUntil?.getTime()).toBe(trialEnd.getTime());
- expect(redeemed.premiumGiftExtensionEndsAt?.getTime()).toBe(trialEnd.getTime());
- await webhookWrite(userId, trialEnd);
- const afterWebhook = await findUser(account.userId);
- expect(afterWebhook.premiumGiftExtensionEndsAt?.getTime()).toBe(trialEnd.getTime());
- });
-
- test('stacks from the paid period end when an earlier gift trial has ended', async () => {
- const subscriptionId = 'sub_shift_stale_trial';
- const periodEnd = Math.floor((Date.now() + ms('20 days')) / 1000);
- const staleTrialEnd = periodEnd - 60 * 24 * 60 * 60;
- useStripe({
- subscriptions: {
- [subscriptionId]: {
- current_period_start: periodEnd - 30 * 24 * 60 * 60,
- current_period_end: periodEnd,
- trial_end: staleTrialEnd,
- metadata: giftTrialMetadata('OLDGIFT', 30, staleTrialEnd - 30 * 24 * 60 * 60),
- },
- },
- });
- const {account} = await createUser({
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- stripe_subscription_id: subscriptionId,
- stripe_customer_id: 'cus_test_1',
- premium_billing_cycle: 'monthly',
- premium_until: new Date(periodEnd * 1000),
- });
- const gifter = await createTestAccount(harness);
- await createBuilder(harness, gifter.token)
- .post('/test/gifts/SHIFTSTALEGIFT')
- .body({duration_type: 'days', duration_quantity: 30, created_by_user_id: gifter.userId})
- .execute();
-
- await createBuilder(harness, account.token).post('/gifts/SHIFTSTALEGIFT/redeem').expect(204).execute();
-
- const update = stripeHandlers.spies.updatedSubscriptions[0]?.params;
- expect(Number(update?.trial_end)).toBe(periodEnd + 30 * 24 * 60 * 60);
- expect(update?.metadata).toEqual({
- gtrial_OLDGIFT: '',
- gtrial_paid_until: String(periodEnd),
- gtrial_SHIFTSTALEGIFT: String(30 * 24 * 60 * 60),
- });
- const redeemed = await findUser(account.userId);
- expect(redeemed.premiumUntil?.getTime()).toBe((periodEnd + 30 * 24 * 60 * 60) * 1000);
- });
- });
-});
diff --git a/fluxer_api/src/api/stripe/tests/StripeNordicCurrencies.test.ts b/fluxer_api/src/api/stripe/tests/StripeNordicCurrencies.test.ts
deleted file mode 100644
index 644a15940..000000000
--- a/fluxer_api/src/api/stripe/tests/StripeNordicCurrencies.test.ts
+++ /dev/null
@@ -1,399 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {Config} from '@app/api/Config';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createStripeApiHandlers, type StripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';
-import {server} from '@app/api/test/msw/server';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import type {
- CurrentSubscriptionPriceResponse,
- PriceIdsResponse,
-} from '@fluxer/schema/src/domains/premium/PremiumSchemas';
-import type {GeoipResult} from '@pkgs/geoip/src/GeoipLookup';
-import {afterAll, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const {lookupGeoipMock} = vi.hoisted(() => ({
- lookupGeoipMock: vi.fn(),
-}));
-
-vi.mock('@app/api/utils/IpUtils', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/api/utils/IpUtils')>()),
- lookupGeoip: lookupGeoipMock,
-}));
-
-const MOCK_PRICES = {
- monthlyUsd: 'price_nordic_monthly_usd',
- yearlyUsd: 'price_nordic_yearly_usd',
- monthlyEur: 'price_nordic_monthly_eur',
- yearlyEur: 'price_nordic_yearly_eur',
- monthlyDkk: 'price_nordic_monthly_dkk',
- yearlyDkk: 'price_nordic_yearly_dkk',
- monthlyNok: 'price_nordic_monthly_nok',
- yearlyNok: 'price_nordic_yearly_nok',
- monthlyPln: 'price_nordic_monthly_pln',
- yearlyPln: 'price_nordic_yearly_pln',
- monthlySek: 'price_nordic_monthly_sek',
- yearlySek: 'price_nordic_yearly_sek',
- monthlyIsk: 'price_nordic_monthly_isk',
- yearlyIsk: 'price_nordic_yearly_isk',
- gift1MonthUsd: 'price_nordic_gift_1_month_usd',
- gift1YearUsd: 'price_nordic_gift_1_year_usd',
- gift1MonthEur: 'price_nordic_gift_1_month_eur',
- gift1YearEur: 'price_nordic_gift_1_year_eur',
- gift1MonthDkk: 'price_nordic_gift_1_month_dkk',
- gift1YearDkk: 'price_nordic_gift_1_year_dkk',
- gift1MonthNok: 'price_nordic_gift_1_month_nok',
- gift1YearNok: 'price_nordic_gift_1_year_nok',
- gift1MonthSek: 'price_nordic_gift_1_month_sek',
- gift1YearSek: 'price_nordic_gift_1_year_sek',
- gift1MonthIsk: 'price_nordic_gift_1_month_isk',
- gift1YearIsk: 'price_nordic_gift_1_year_isk',
-};
-
-const MOCK_PRICE_SEEDS = {
- [MOCK_PRICES.monthlyUsd]: {unit_amount: 499, currency: 'usd', interval: 'month' as const},
- [MOCK_PRICES.yearlyUsd]: {unit_amount: 4999, currency: 'usd', interval: 'year' as const},
- [MOCK_PRICES.monthlyEur]: {unit_amount: 499, currency: 'eur', interval: 'month' as const},
- [MOCK_PRICES.yearlyEur]: {unit_amount: 4999, currency: 'eur', interval: 'year' as const},
- [MOCK_PRICES.monthlyDkk]: {unit_amount: 3500, currency: 'dkk', interval: 'month' as const},
- [MOCK_PRICES.yearlyDkk]: {unit_amount: 35000, currency: 'dkk', interval: 'year' as const},
- [MOCK_PRICES.monthlyNok]: {unit_amount: 4900, currency: 'nok', interval: 'month' as const},
- [MOCK_PRICES.yearlyNok]: {unit_amount: 49000, currency: 'nok', interval: 'year' as const},
- [MOCK_PRICES.monthlyPln]: {unit_amount: 1900, currency: 'pln', interval: 'month' as const},
- [MOCK_PRICES.yearlyPln]: {unit_amount: 19000, currency: 'pln', interval: 'year' as const},
- [MOCK_PRICES.monthlySek]: {unit_amount: 4900, currency: 'sek', interval: 'month' as const},
- [MOCK_PRICES.yearlySek]: {unit_amount: 49000, currency: 'sek', interval: 'year' as const},
- [MOCK_PRICES.monthlyIsk]: {unit_amount: 59000, currency: 'isk', interval: 'month' as const},
- [MOCK_PRICES.yearlyIsk]: {unit_amount: 590000, currency: 'isk', interval: 'year' as const},
- [MOCK_PRICES.gift1MonthDkk]: {unit_amount: 3500, currency: 'dkk'},
- [MOCK_PRICES.gift1YearDkk]: {unit_amount: 35000, currency: 'dkk'},
- [MOCK_PRICES.gift1MonthNok]: {unit_amount: 4900, currency: 'nok'},
- [MOCK_PRICES.gift1YearNok]: {unit_amount: 49000, currency: 'nok'},
- [MOCK_PRICES.gift1MonthSek]: {unit_amount: 4900, currency: 'sek'},
- [MOCK_PRICES.gift1YearSek]: {unit_amount: 49000, currency: 'sek'},
- [MOCK_PRICES.gift1MonthIsk]: {unit_amount: 59000, currency: 'isk'},
- [MOCK_PRICES.gift1YearIsk]: {unit_amount: 590000, currency: 'isk'},
-};
-
-const EUR_SUBSCRIPTION_ID = 'sub_nordic_legacy_eur';
-
-function geoipCountry(countryCode: string | null): GeoipResult {
- return {
- countryCode,
- normalizedIp: '203.0.113.10',
- city: null,
- region: null,
- countryName: null,
- };
-}
-
-describe('Nordic localized currencies', () => {
- let harness: ApiTestHarness;
- let stripeHandlers: StripeApiHandlers;
- let originalPrices: typeof Config.stripe.prices | undefined;
-
- async function createPurchaser(): Promise<string> {
- const account = await createTestAccount(harness);
- await createBuilder(harness, account.token)
- .post(`/test/users/${account.userId}/security-flags`)
- .body({email_verified: true})
- .execute();
- return account.token;
- }
-
- function getPriceIds(countryCode: string | null): Promise<PriceIdsResponse> {
- lookupGeoipMock.mockResolvedValue(geoipCountry(countryCode));
- return createBuilder<PriceIdsResponse>(harness, '').get('/premium/price-ids').expect(HTTP_STATUS.OK).execute();
- }
-
- beforeAll(async () => {
- originalPrices = Config.stripe.prices;
- Config.stripe.prices = MOCK_PRICES;
- harness = await createApiTestHarness();
- });
- afterAll(async () => {
- await harness.shutdown();
- Config.stripe.prices = originalPrices;
- });
- beforeEach(() => {
- Config.stripe.prices = MOCK_PRICES;
- lookupGeoipMock.mockReset();
- lookupGeoipMock.mockResolvedValue(geoipCountry(null));
- stripeHandlers = createStripeApiHandlers({
- prices: MOCK_PRICE_SEEDS,
- subscriptionsListEmpty: true,
- subscriptions: {
- [EUR_SUBSCRIPTION_ID]: {
- customer: `cus_${EUR_SUBSCRIPTION_ID}`,
- price_id: MOCK_PRICES.monthlyEur,
- unit_amount: 499,
- currency: 'eur',
- interval: 'month',
- item_id: `si_${EUR_SUBSCRIPTION_ID}`,
- },
- },
- });
- server.use(...stripeHandlers.handlers);
- });
-
- describe('country routing', () => {
- test('Sweden resolves to the SEK subscription catalog', async () => {
- const priceIds = await getPriceIds('SE');
- expect(priceIds.currency).toBe('SEK');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlySek);
- expect(priceIds.yearly).toBe(MOCK_PRICES.yearlySek);
- expect(priceIds.monthly_amount_minor).toBe(4900);
- expect(priceIds.yearly_amount_minor).toBe(49000);
- });
-
- test.each(['DK', 'FO', 'GL'])('%s resolves to the DKK subscription catalog', async (country) => {
- const priceIds = await getPriceIds(country);
- expect(priceIds.currency).toBe('DKK');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyDkk);
- expect(priceIds.yearly).toBe(MOCK_PRICES.yearlyDkk);
- expect(priceIds.monthly_amount_minor).toBe(3500);
- expect(priceIds.yearly_amount_minor).toBe(35000);
- });
-
- test.each(['NO', 'SJ'])('%s resolves to the NOK subscription catalog', async (country) => {
- const priceIds = await getPriceIds(country);
- expect(priceIds.currency).toBe('NOK');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyNok);
- expect(priceIds.yearly).toBe(MOCK_PRICES.yearlyNok);
- expect(priceIds.monthly_amount_minor).toBe(4900);
- expect(priceIds.yearly_amount_minor).toBe(49000);
- });
-
- test('Iceland resolves to the ISK subscription catalog', async () => {
- const priceIds = await getPriceIds('IS');
- expect(priceIds.currency).toBe('ISK');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyIsk);
- expect(priceIds.yearly).toBe(MOCK_PRICES.yearlyIsk);
- expect(priceIds.monthly_amount_minor).toBe(59000);
- expect(priceIds.yearly_amount_minor).toBe(590000);
- });
-
- test('Poland still resolves to the PLN subscription catalog', async () => {
- const priceIds = await getPriceIds('PL');
- expect(priceIds.currency).toBe('PLN');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyPln);
- });
-
- test.each(['DE', 'NL', 'FI', 'IE', 'AX'])('%s still resolves to the EUR subscription catalog', async (country) => {
- const priceIds = await getPriceIds(country);
- expect(priceIds.currency).toBe('EUR');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyEur);
- expect(priceIds.yearly).toBe(MOCK_PRICES.yearlyEur);
- });
-
- test.each([
- ['SE', 'SEK', MOCK_PRICES.gift1MonthSek, MOCK_PRICES.gift1YearSek, 4900],
- ['DK', 'DKK', MOCK_PRICES.gift1MonthDkk, MOCK_PRICES.gift1YearDkk, 3500],
- ['NO', 'NOK', MOCK_PRICES.gift1MonthNok, MOCK_PRICES.gift1YearNok, 4900],
- ['IS', 'ISK', MOCK_PRICES.gift1MonthIsk, MOCK_PRICES.gift1YearIsk, 59000],
- ])('%s sells gifts in %s at the subscription price', async (country, currency, giftMonth, giftYear, amount) => {
- const priceIds = await getPriceIds(country);
- expect(priceIds.gift_currency).toBe(currency);
- expect(priceIds.gift_1_month).toBe(giftMonth);
- expect(priceIds.gift_1_year).toBe(giftYear);
- expect(priceIds.gift_1_month_amount_minor).toBe(amount);
- expect(priceIds.gift_1_month_amount_minor).toBe(priceIds.monthly_amount_minor);
- expect(priceIds.gift_1_year_amount_minor).toBe(priceIds.yearly_amount_minor);
- });
-
- test('a Nordic gift falls back to EUR while the native gift prices are unconfigured', async () => {
- Config.stripe.prices = {
- ...MOCK_PRICES,
- gift1MonthSek: undefined,
- gift1YearSek: undefined,
- };
- const priceIds = await getPriceIds('SE');
- expect(priceIds.currency).toBe('SEK');
- expect(priceIds.gift_currency).toBe('EUR');
- expect(priceIds.gift_1_month).toBe(MOCK_PRICES.gift1MonthEur);
- });
-
- test('a Nordic gift falls through to USD when no native or EUR gift price is configured', async () => {
- Config.stripe.prices = {
- ...MOCK_PRICES,
- gift1MonthSek: undefined,
- gift1YearSek: undefined,
- gift1MonthEur: undefined,
- gift1YearEur: undefined,
- };
- const priceIds = await getPriceIds('SE');
- expect(priceIds.currency).toBe('SEK');
- expect(priceIds.gift_currency).toBe('USD');
- expect(priceIds.gift_1_month).toBe(MOCK_PRICES.gift1MonthUsd);
- });
-
- test('Sweden falls back to EUR while the SEK prices are still unconfigured', async () => {
- Config.stripe.prices = {
- ...MOCK_PRICES,
- monthlySek: undefined,
- yearlySek: undefined,
- };
- const priceIds = await getPriceIds('SE');
- expect(priceIds.currency).toBe('EUR');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyEur);
- expect(priceIds.gift_currency).toBe('SEK');
- });
-
- test('Iceland falls back to EUR while the ISK prices are still unconfigured', async () => {
- Config.stripe.prices = {
- ...MOCK_PRICES,
- monthlyIsk: undefined,
- yearlyIsk: undefined,
- gift1MonthIsk: undefined,
- gift1YearIsk: undefined,
- };
- const priceIds = await getPriceIds('IS');
- expect(priceIds.currency).toBe('EUR');
- expect(priceIds.monthly).toBe(MOCK_PRICES.monthlyEur);
- expect(priceIds.yearly).toBe(MOCK_PRICES.yearlyEur);
- expect(priceIds.gift_currency).toBe('EUR');
- expect(priceIds.gift_1_month).toBe(MOCK_PRICES.gift1MonthEur);
- });
- });
-
- describe('checkout enforcement', () => {
- test('accepts the SEK subscription price for a purchase that geolocates to Sweden', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('SE'));
- const token = await createPurchaser();
- const response = await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlySek, country_code: 'SE'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.url).toContain('checkout.stripe.com');
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- });
-
- test('accepts the SEK gift price from inside Sweden', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('SE'));
- const token = await createPurchaser();
- const response = await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/gift')
- .body({price_id: MOCK_PRICES.gift1MonthSek, country_code: 'SE'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(response.url).toContain('checkout.stripe.com');
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- });
-
- test('rejects the EUR gift price from inside Sweden once SEK gifts exist', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('SE'));
- const token = await createPurchaser();
- await createBuilder(harness, token)
- .post('/stripe/checkout/gift')
- .body({price_id: MOCK_PRICES.gift1MonthEur, country_code: 'SE'})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.STRIPE_INVALID_PRODUCT_CONFIGURATION)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
-
- test('accepts the ISK subscription price for a purchase that geolocates to Iceland', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('IS'));
- const token = await createPurchaser();
- await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.yearlyIsk, country_code: 'IS'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- expect(stripeHandlers.spies.createdCheckoutSessions[0]?.line_items?.[0]?.price).toBe(MOCK_PRICES.yearlyIsk);
- });
-
- test('marks Åland as EEA so the withdrawal waiver applies', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('AX'));
- const token = await createPurchaser();
- await createBuilder<{url: string}>(harness, token)
- .post('/stripe/checkout/subscription')
- .body({price_id: MOCK_PRICES.monthlyEur, country_code: 'AX'})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions[0]?.metadata?.eu_withdrawal_waiver_required).toBe('true');
- });
-
- test('rejects the SEK subscription price on the gift endpoint', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('SE'));
- const token = await createPurchaser();
- await createBuilder(harness, token)
- .post('/stripe/checkout/gift')
- .body({price_id: MOCK_PRICES.monthlySek, country_code: 'SE'})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.STRIPE_INVALID_PRODUCT_CONFIGURATION)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(0);
- });
- });
-
- describe('adaptive pricing', () => {
- async function checkout(path: 'subscription' | 'gift', priceId: string, country: string) {
- lookupGeoipMock.mockResolvedValue(geoipCountry(country));
- const token = await createPurchaser();
- await createBuilder<{url: string}>(harness, token)
- .post(`/stripe/checkout/${path}`)
- .body({price_id: priceId, country_code: country})
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(stripeHandlers.spies.createdCheckoutSessions).toHaveLength(1);
- return stripeHandlers.spies.createdCheckoutSessions[0];
- }
-
- test.each([
- ['subscription', MOCK_PRICES.monthlySek, 'SE'],
- ['subscription', MOCK_PRICES.yearlySek, 'SE'],
- ['gift', MOCK_PRICES.gift1MonthSek, 'SE'],
- ['subscription', MOCK_PRICES.monthlyNok, 'NO'],
- ['subscription', MOCK_PRICES.monthlyDkk, 'DK'],
- ['subscription', MOCK_PRICES.monthlyIsk, 'IS'],
- ['gift', MOCK_PRICES.gift1YearIsk, 'IS'],
- ] as const)('turns adaptive pricing off for a %s checkout with %s', async (path, priceId, country) => {
- const session = await checkout(path, priceId, country);
- expect(session?.adaptive_pricing).toEqual({enabled: 'false'});
- });
-
- test.each([
- ['subscription', MOCK_PRICES.monthlyEur, 'DE'],
- ['gift', MOCK_PRICES.gift1MonthEur, 'FI'],
- ['subscription', MOCK_PRICES.monthlyUsd, 'US'],
- ['subscription', MOCK_PRICES.monthlyPln, 'PL'],
- ] as const)('leaves adaptive pricing unset for a %s checkout with %s', async (path, priceId, country) => {
- const session = await checkout(path, priceId, country);
- expect(session?.adaptive_pricing).toBeUndefined();
- });
- });
-
- describe('existing subscribers', () => {
- test('a Swedish customer billed in EUR keeps the EUR price and is not repriced to SEK', async () => {
- lookupGeoipMock.mockResolvedValue(geoipCountry('SE'));
- const account = await createTestAccount(harness);
- await createBuilder(harness, account.token)
- .post(`/test/users/${account.userId}/premium`)
- .body({
- stripe_subscription_id: EUR_SUBSCRIPTION_ID,
- premium_type: 1,
- premium_billing_cycle: 'monthly',
- premium_until: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
- premium_will_cancel: false,
- })
- .execute();
- const price = await createBuilder<CurrentSubscriptionPriceResponse>(harness, account.token)
- .get('/premium/current-subscription-price')
- .expect(HTTP_STATUS.OK)
- .execute();
- expect(price).toMatchObject({
- price_id: MOCK_PRICES.monthlyEur,
- currency: 'EUR',
- billing_cycle: 'monthly',
- is_grandfathered: false,
- list_price_id: MOCK_PRICES.monthlyEur,
- });
- expect(stripeHandlers.spies.updatedSubscriptions).toHaveLength(0);
- expect(stripeHandlers.spies.createdSubscriptionSchedules).toHaveLength(0);
- });
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/CrosspostTasks.test.ts b/fluxer_api/src/api/worker/tests/CrosspostTasks.test.ts
deleted file mode 100644
index 7372d2514..000000000
--- a/fluxer_api/src/api/worker/tests/CrosspostTasks.test.ts
+++ /dev/null
@@ -1,209 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createChannelID, createGuildID, createMessageID, createWebhookID} from '@app/api/BrandedTypes';
-import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {CrosspostTaskNames} from '@app/api/channel/services/message/CrosspostPropagation';
-import {disableCrosspostWorker, follow} from '@app/api/channel/tests/AnnouncementTestUtils';
-import {
- type FanoutWorld,
- followInto,
- patchChannelRow,
- postAndPublish,
- setupFanoutWorld,
- sourceIndex,
-} from '@app/api/channel/tests/CrosspostWorkerTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import {WebhookRepository} from '@app/api/webhook/WebhookRepository';
-import crosspostMessage from '@app/api/worker/tasks/CrosspostMessage';
-import removeChannelFollowers from '@app/api/worker/tasks/RemoveChannelFollowers';
-import syncCrosspostedMessage from '@app/api/worker/tasks/SyncCrosspostedMessage';
-import {ChannelTypes, WebhookTypes} from '@fluxer/constants/src/ChannelConstants';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-const pageSizes = vi.hoisted(() => ({chunk: null as number | null, page: null as number | null}));
-
-vi.mock('@fluxer/constants/src/AnnouncementConstants', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@fluxer/constants/src/AnnouncementConstants')>();
- return {
- ...actual,
- get CROSSPOST_FANOUT_CHUNK_SIZE() {
- return pageSizes.chunk ?? actual.CROSSPOST_FANOUT_CHUNK_SIZE;
- },
- get CROSSPOST_FANOUT_PAGE_SIZE() {
- return pageSizes.page ?? actual.CROSSPOST_FANOUT_PAGE_SIZE;
- },
- };
-});
-
-describe('crosspost tasks against storage', () => {
- let harness: ApiTestHarness;
- let world: FanoutWorld;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- world = await setupFanoutWorld(harness);
- });
-
- afterEach(() => {
- pageSizes.chunk = null;
- pageSizes.page = null;
- disableCrosspostWorker();
- vi.restoreAllMocks();
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- async function followerIds(): Promise<Array<string>> {
- const entries = await new WebhookRepository().listIdsBySourceChannel(createChannelID(BigInt(world.a.ann.id)), {
- limit: 100,
- });
- return entries.map((entry) => entry.webhookId.toString());
- }
-
- test('removeChannelFollowers removes every follower once and announces each target', async () => {
- await followInto(harness, world, world.b.t1.id);
- await followInto(harness, world, world.b.t2.id);
- await patchChannelRow(world.a.ann.id, {type: ChannelTypes.GUILD_TEXT});
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const payload = {sourceChannelId: world.a.ann.id, reason: 'converted'};
- await removeChannelFollowers(
- payload,
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(await followerIds()).toHaveLength(0);
- const updates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'WEBHOOKS_UPDATE');
- expect(updates.map((params) => (params.data as {channel_id: string}).channel_id).sort()).toEqual(
- [world.b.t1.id, world.b.t2.id].sort(),
- );
- expect(updates.every((params) => params.guildId.toString() === world.b.guild.id)).toBe(true);
- dispatchSpy.mockClear();
- await removeChannelFollowers(
- payload,
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(dispatchSpy.mock.calls.filter(([params]) => params.event === 'WEBHOOKS_UPDATE')).toHaveLength(0);
- const webhooks = await new WebhookRepository().listByChannel(createChannelID(BigInt(world.b.t1.id)));
- expect(webhooks.filter((webhook) => webhook.type === WebhookTypes.CHANNEL_FOLLOWER)).toHaveLength(0);
- });
-
- test('removeChannelFollowers keeps followers when the channel is an announcement channel again', async () => {
- await followInto(harness, world, world.b.t1.id);
- await removeChannelFollowers(
- {sourceChannelId: world.a.ann.id, reason: 'converted'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(await followerIds()).toHaveLength(1);
- });
-
- test('removeChannelFollowers with a copy mode queues one sync per published message, across pages', async () => {
- await followInto(harness, world, world.b.t1.id);
- const published = [];
- for (const content of ['one', 'two', 'three']) {
- published.push(await postAndPublish(harness, world, {content}));
- }
- expect((await sourceIndex(world.a.ann.id)).sort()).toEqual(published.map((message) => message.id).sort());
- pageSizes.page = 2;
- const before = world.worker.recorded.length;
- await removeChannelFollowers(
- {sourceChannelId: world.a.ann.id, reason: 'deleted', copyMode: 'purge'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- const queued = world.worker.recorded.slice(before);
- expect(queued.every((job) => job.taskType === CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE)).toBe(true);
- expect(queued.map((job) => (job.payload as {messageId: string}).messageId).sort()).toEqual(
- published.map((message) => message.id).sort(),
- );
- expect(queued.map((job) => job.payload.mode)).toEqual(['purge', 'purge', 'purge']);
- expect(queued.map((job) => job.jobKey).sort()).toEqual(
- published.map((message) => `crosspost-sync:${message.id}:purge`).sort(),
- );
- expect(await followerIds()).toHaveLength(0);
- });
-
- test('syncCrosspostedMessage pages through every mapping row', async () => {
- const source = await postAndPublish(harness, world, {content: 'many followers'});
- const repository = new ChannelRepository();
- const webhookIds = [
- '900000000000000001',
- '900000000000000002',
- '900000000000000003',
- '900000000000000004',
- '900000000000000005',
- ];
- for (const webhookId of webhookIds) {
- await repository.crossposts.insertPending({
- source_message_id: createMessageID(BigInt(source.id)),
- webhook_id: createWebhookID(BigInt(webhookId)),
- source_channel_id: createChannelID(BigInt(world.a.ann.id)),
- target_guild_id: createGuildID(BigInt(world.b.guild.id)),
- target_channel_id: createChannelID(BigInt(world.b.t1.id)),
- target_message_id: createMessageID(BigInt(webhookId)),
- state: 'pending',
- reserved_at: new Date(Date.now() - 120_000),
- source_fingerprint: null,
- created_at: new Date(),
- });
- }
- pageSizes.page = 2;
- pageSizes.chunk = 1;
- const before = world.worker.recorded.length;
- await syncCrosspostedMessage(
- {channelId: world.a.ann.id, messageId: source.id, mode: 'source_deleted'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- const chunks = world.worker.recorded.slice(before);
- expect(chunks.map((job) => job.taskType)).toEqual(Array(5).fill(CrosspostTaskNames.SYNC_CROSSPOST_COPIES));
- expect(chunks.map((job) => (job.payload as {webhookIds: Array<string>}).webhookIds)).toEqual(
- webhookIds.map((webhookId) => [webhookId]),
- );
- expect(chunks.map((job) => job.jobKey)).toEqual(
- webhookIds.map((webhookId) => `crosspost-sync-chunk:${source.id}:source_deleted:source_deleted:${webhookId}`),
- );
- expect(await sourceIndex(world.a.ann.id)).not.toContain(source.id);
- await world.worker.drain();
- expect(world.worker.deadLetters).toHaveLength(0);
- const remaining = await repository.crossposts.listBySourceMessage(createMessageID(BigInt(source.id)), {
- limit: 100,
- });
- expect(remaining).toHaveLength(0);
- });
-
- test('crosspostMessage does nothing for a message that is not published', async () => {
- await follow(harness, world.b.owner.token, world.a.ann.id, world.b.t1.id);
- await world.worker.drain();
- const before = world.worker.recorded.length;
- await crosspostMessage(
- {channelId: world.a.ann.id, messageId: '123456789012345678'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(world.worker.recorded.length).toBe(before);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/HandleMentionsThread.test.ts b/fluxer_api/src/api/worker/tests/HandleMentionsThread.test.ts
deleted file mode 100644
index 4af377840..000000000
--- a/fluxer_api/src/api/worker/tests/HandleMentionsThread.test.ts
+++ /dev/null
@@ -1,322 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelID,
- createChannelID,
- createGuildID,
- createMessageID,
- createUserID,
- type UserID,
-} from '@app/api/BrandedTypes';
-import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import type {GatewayMentionSourceEntry, IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import {ThreadState} from '@app/api/models/ThreadState';
-import type {ReadStateMentionUpdate} from '@app/api/read_state/ReadStateRepository';
-import type {ReadStateService} from '@app/api/read_state/ReadStateService';
-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import handleMentionChunk from '@app/api/worker/tasks/HandleMentionChunk';
-import handleMentions from '@app/api/worker/tasks/HandleMentions';
-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
-import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {
- MAX_ROLE_MENTION_THREAD_ADDS,
- MAX_THREAD_MEMBERS,
- ReadStateFlags,
- ServerMessageFlags,
-} from '@fluxer/constants/src/ThreadConstants';
-import {MaxThreadMembersError} from '@fluxer/errors/src/domains/channel/MaxThreadMembersError';
-import type {WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';
-import {afterEach, describe, expect, test, vi} from 'vitest';
-
-vi.mock('@app/api/channel/services/message/MessageGatewayDispatch', () => ({
- buildBroadcastMessageData: async ({message}: {message: {id: bigint; flags: number}}) => ({
- id: message.id.toString(),
- flags: message.flags,
- }),
-}));
-
-vi.mock('@app/api/channel/services/thread/ThreadDispatch', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@app/api/channel/services/thread/ThreadDispatch')>()),
- threadMembersUpdateEvent: (
- view: {state: {appliedTags: Array<bigint>}},
- change: {added?: Array<{userId: UserID}>},
- ) => ({
- event: 'THREAD_MEMBERS_UPDATE',
- data: {
- added: (change.added ?? []).map((member) => member.userId.toString()),
- ...(view.state.appliedTags.length > 0 ? {applied_tags: view.state.appliedTags.map(String)} : {}),
- },
- }),
-}));
-
-const GUILD = createGuildID(4000n);
-const THREAD = createChannelID(5000n);
-const PARENT = createChannelID(4500n);
-const MESSAGE = createMessageID(6000n);
-const AUTHOR = createUserID(1n);
-
-interface EnqueuedChunk {
- thread?: boolean;
- mentions: Array<{userId: string; direct: boolean; role: boolean; everyone: boolean}>;
-}
-
-function createHarness(params: {
- channelType?: number;
- members?: Array<string>;
- isPrivate?: boolean;
- memberCount?: number;
- addRejected?: boolean;
- joinedConcurrently?: Array<string>;
- forumTags?: {applied: Array<bigint>; live: Array<bigint>};
- mentions: Array<GatewayMentionSourceEntry>;
-}) {
- const members = new Set(params.members ?? []);
- const added: Array<string> = [];
- const dispatched: Array<{event: string; data: unknown}> = [];
- const upserts: Array<number> = [];
- const message = {
- id: MESSAGE,
- flags: 0,
- mentionEveryone: true,
- mentionedRoleIds: new Set(),
- mentionedUserIds: new Set(),
- };
- const joinedConcurrently = new Set(params.joinedConcurrently ?? []);
- const state = new ThreadState({
- thread_id: THREAD,
- guild_id: GUILD,
- parent_id: PARENT,
- type: params.isPrivate ? ChannelTypes.PRIVATE_THREAD : ChannelTypes.PUBLIC_THREAD,
- archived: false,
- locked: false,
- invitable: null,
- auto_archive_duration: 1440,
- archive_timestamp: null,
- created_at: new Date(0),
- flags: 0,
- applied_tags: params.forumTags?.applied ?? null,
- member_count: params.memberCount ?? members.size,
- member_ids_preview: null,
- has_starter: false,
- state_version: 1,
- });
- const parentType = params.forumTags ? ChannelTypes.GUILD_FORUM : ChannelTypes.GUILD_TEXT;
- const channel = {
- id: THREAD,
- guildId: GUILD,
- parentId: PARENT,
- type: params.channelType ?? ChannelTypes.PUBLIC_THREAD,
- };
- const channelRepository = {
- threads: {
- getState: async () => state,
- getMembers: async (_threadId: ChannelID, userIds: Array<UserID>) =>
- userIds.filter((userId) => members.has(userId.toString())).map((userId) => ({userId})),
- addMembers: async (_threadId: ChannelID, entries: Array<{userId: UserID}>) => {
- if (params.addRejected) throw new MaxThreadMembersError(MAX_THREAD_MEMBERS);
- for (const userId of joinedConcurrently) members.add(userId);
- const fresh = entries.filter((entry) => !members.has(entry.userId.toString()));
- for (const entry of fresh) added.push(entry.userId.toString());
- return {added: fresh.map((entry) => ({userId: entry.userId})), state};
- },
- getStats: async () => ({}),
- getParentConfig: async () => ({availableTags: (params.forumTags?.live ?? []).map((id) => ({id}))}),
- },
- channelData: {
- findUnique: async (channelId: ChannelID) =>
- channelId === THREAD
- ? channel
- : {id: PARENT, type: parentType, isThreadOnly: () => parentType === ChannelTypes.GUILD_FORUM},
- },
- messages: {
- getMessage: async () => ({...message, toRow: () => ({flags: message.flags})}),
- upsertMessage: async (row: {flags: number}) => {
- upserts.push(row.flags);
- return {...message, flags: row.flags};
- },
- },
- } as unknown as ChannelRepository;
- const gatewayService = {
- resolveMentionSourcesPage: async () => ({mentions: params.mentions, nextCursor: null}),
- dispatchGuild: async ({event, data}: {event: string; data: unknown}) => {
- dispatched.push({event, data});
- },
- dispatchGuildMany: async ({events}: {events: Array<{event: string; data: unknown}>}) => {
- dispatched.push(...events);
- },
- } as unknown as IGatewayService;
- const userRepository = {listUsers: async () => []} as unknown as UserRepository;
- setWorkerDependenciesForTest({channelRepository, gatewayService, userRepository});
- return {added, dispatched, upserts};
-}
-
-async function run(): Promise<Array<EnqueuedChunk>> {
- const chunks: Array<EnqueuedChunk> = [];
- const helpers: WorkerTaskHelpers = createTestWorkerHelpers({
- addJob: async (_name: string, payload: unknown) => {
- chunks.push(payload as EnqueuedChunk);
- return 0n;
- },
- }) as unknown as WorkerTaskHelpers;
- await handleMentions(
- {
- channelId: THREAD.toString(),
- messageId: MESSAGE.toString(),
- authorId: AUTHOR.toString(),
- guildId: GUILD.toString(),
- },
- helpers,
- );
- return chunks;
-}
-
-function entry(userId: number, source: Partial<GatewayMentionSourceEntry>): GatewayMentionSourceEntry {
- return {userId: createUserID(BigInt(userId)), direct: false, role: false, everyone: false, ...source};
-}
-
-describe('thread mentions', () => {
- afterEach(() => {
- clearWorkerDependencies();
- });
-
- test('notifies members for @everyone, keeps direct mentions and adds role members', async () => {
- const harness = createHarness({
- members: ['10'],
- mentions: [
- entry(10, {everyone: true}),
- entry(11, {everyone: true}),
- entry(12, {direct: true}),
- entry(13, {role: true, everyone: true}),
- ],
- });
- const chunks = await run();
- expect(chunks).toHaveLength(1);
- expect(chunks[0]?.thread).toBe(true);
- expect(chunks[0]?.mentions).toEqual([
- {userId: '10', direct: false, role: false, everyone: true},
- {userId: '12', direct: true, role: false, everyone: false},
- {userId: '13', direct: false, role: true, everyone: false},
- ]);
- expect(harness.added).toEqual(['13']);
- expect(harness.dispatched.map((event) => event.event)).toEqual(['THREAD_MEMBERS_UPDATE']);
- expect(harness.upserts).toEqual([]);
- });
-
- test('keeps a role mention for a member who joined during the add', async () => {
- const harness = createHarness({
- joinedConcurrently: ['13'],
- mentions: [entry(13, {role: true}), entry(14, {role: true})],
- });
- const chunks = await run();
- expect(harness.added).toEqual(['14']);
- expect(chunks.flatMap((chunk) => chunk.mentions)).toEqual([
- {userId: '13', direct: false, role: true, everyone: false},
- {userId: '14', direct: false, role: true, everyone: false},
- ]);
- expect(harness.upserts).toEqual([]);
- });
-
- test('drops deleted forum tags from the role add THREAD_MEMBERS_UPDATE', async () => {
- const harness = createHarness({forumTags: {applied: [7n, 8n], live: [7n]}, mentions: [entry(13, {role: true})]});
- await run();
- expect(harness.dispatched).toEqual([{event: 'THREAD_MEMBERS_UPDATE', data: {added: ['13'], applied_tags: ['7']}}]);
- });
-
- test('never adds role members to a private thread', async () => {
- const harness = createHarness({isPrivate: true, mentions: [entry(13, {role: true})]});
- expect(await run()).toEqual([]);
- expect(harness.added).toEqual([]);
- });
-
- test('caps role adds and flags the message once', async () => {
- const mentions = Array.from({length: MAX_ROLE_MENTION_THREAD_ADDS + 5}, (_, index) =>
- entry(100 + index, {role: true}),
- );
- const harness = createHarness({mentions});
- const chunks = await run();
- expect(harness.added).toHaveLength(MAX_ROLE_MENTION_THREAD_ADDS);
- expect(chunks.flatMap((chunk) => chunk.mentions)).toHaveLength(MAX_ROLE_MENTION_THREAD_ADDS);
- expect(harness.upserts).toEqual([ServerMessageFlags.FAILED_TO_MENTION_SOME_ROLES_IN_THREAD]);
- expect(harness.dispatched.at(-1)).toEqual({
- event: 'MESSAGE_UPDATE',
- data: {id: MESSAGE.toString(), flags: ServerMessageFlags.FAILED_TO_MENTION_SOME_ROLES_IN_THREAD},
- });
- });
-
- test('mentions only role members that fit under the thread member cap', async () => {
- const harness = createHarness({
- memberCount: MAX_THREAD_MEMBERS - 1,
- mentions: [entry(13, {role: true}), entry(14, {role: true})],
- });
- const chunks = await run();
- expect(harness.added).toEqual(['13']);
- expect(chunks.flatMap((chunk) => chunk.mentions)).toEqual([
- {userId: '13', direct: false, role: true, everyone: false},
- ]);
- expect(harness.upserts).toEqual([ServerMessageFlags.FAILED_TO_MENTION_SOME_ROLES_IN_THREAD]);
- });
-
- test('mentions no role members when the add hits the member cap', async () => {
- const harness = createHarness({addRejected: true, mentions: [entry(13, {role: true}), entry(12, {direct: true})]});
- const chunks = await run();
- expect(chunks.flatMap((chunk) => chunk.mentions)).toEqual([
- {userId: '12', direct: true, role: false, everyone: false},
- ]);
- expect(harness.upserts).toEqual([ServerMessageFlags.FAILED_TO_MENTION_SOME_ROLES_IN_THREAD]);
- });
-
- test('leaves ordinary channels untouched', async () => {
- createHarness({channelType: ChannelTypes.GUILD_TEXT, mentions: [entry(11, {everyone: true})]});
- const chunks = await run();
- expect(chunks).toHaveLength(1);
- expect(chunks[0]).not.toHaveProperty('thread');
- expect(chunks[0]?.mentions).toEqual([{userId: '11', direct: false, role: false, everyone: true}]);
- });
-});
-
-describe('thread mention chunks', () => {
- afterEach(() => {
- clearWorkerDependencies();
- });
-
- function chunkHarness() {
- const increments: Array<ReadStateMentionUpdate> = [];
- const readStateService = {
- bulkIncrementMentionCounts: async (updates: Array<ReadStateMentionUpdate>) => {
- increments.push(...updates);
- },
- } as unknown as ReadStateService;
- const userRepository = {
- findGuildSettings: async () => null,
- createRecentMentions: async () => {},
- } as unknown as UserRepository;
- setWorkerDependenciesForTest({readStateService, userRepository});
- return increments;
- }
-
- async function runChunk() {
- await handleMentionChunk(
- {
- channelId: THREAD.toString(),
- messageId: MESSAGE.toString(),
- guildId: GUILD.toString(),
- thread: true,
- mentions: [{userId: '12', direct: true}],
- },
- {logger: new NoopLogger()} as unknown as WorkerTaskHelpers,
- );
- }
-
- test('stamps thread read states on increment', async () => {
- const increments = chunkHarness();
- await runChunk();
- expect(increments).toEqual([
- expect.objectContaining({
- userId: createUserID(12n),
- marker: {flags: ReadStateFlags.IS_GUILD_CHANNEL | ReadStateFlags.IS_THREAD, guildId: GUILD},
- }),
- ]);
- });
-});
diff --git a/fluxer_api/vitest.config.ts b/fluxer_api/vitest.config.ts
index 9862a0467..fe4c2dceb 100644
--- a/fluxer_api/vitest.config.ts
+++ b/fluxer_api/vitest.config.ts
@@ -22,16 +22,7 @@ const DEFAULT_PARALLEL_WORKERS = resolveDefaultParallelWorkers();
const configuredMaxWorkers = parseParallelInteger(process.env.API_TEST_MAX_WORKERS, DEFAULT_PARALLEL_WORKERS);
const configuredMaxConcurrency = parseParallelInteger(process.env.API_TEST_MAX_CONCURRENCY, configuredMaxWorkers);
-const MODULE_REGISTRY_TEST_FILES = [
- 'src/api/channel/tests/MessageCrosspostFanout.test.ts',
- 'src/api/experiment/tests/ExperimentController.test.ts',
- 'src/api/stripe/tests/StripeCheckoutCountryEnforcement.test.ts',
- 'src/api/stripe/tests/StripeNordicCurrencies.test.ts',
- 'src/api/worker/tests/CrosspostTasks.test.ts',
- 'src/api/search/ThreadSearchScope.test.ts',
- 'src/api/worker/tests/HandleMentionsThread.test.ts',
- 'src/api/voice/tests/VoiceAvailabilityService.test.ts',
-];
+const MODULE_REGISTRY_TEST_FILES = ['src/api/voice/tests/VoiceAvailabilityService.test.ts'];
const INSTANCE_POLICY_TEST_FILES = ['src/api/admin/tests/InstanceConfigPendingRegistrationApproval.test.ts'];
diff --git a/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts b/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts
deleted file mode 100644
index 80d7285af..000000000
--- a/packages/errors/src/__tests__/AppErrorHandlerLogging.test.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {AppErrorHandler, type BaseHonoEnv} from '@fluxer/errors/src/domains/core/ErrorHandlers';
-import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
-import {Hono} from 'hono';
-import {beforeEach, describe, expect, it, vi} from 'vitest';
-
-type LogCall = [Record<string, unknown>, string | undefined];
-
-const logCalls = vi.hoisted(() => ({
- error: [] as Array<LogCall>,
-}));
-
-vi.mock('@fluxer/logger/src/Logger', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@fluxer/logger/src/Logger')>();
- return {
- ...actual,
- createLogger: () => ({
- trace: () => {},
- debug: () => {},
- info: () => {},
- warn: () => {},
- error: (obj: Record<string, unknown>, msg?: string) => {
- logCalls.error.push([obj, msg]);
- },
- fatal: () => {},
- }),
- };
-});
-
-function createApp(): Hono<BaseHonoEnv> {
- const app = new Hono<BaseHonoEnv>();
- app.onError(AppErrorHandler);
- return app;
-}
-
-describe('AppErrorHandler logging', () => {
- beforeEach(() => {
- logCalls.error.length = 0;
- });
-
- it('logs the matched route pattern instead of the request path', async () => {
- const app = createApp();
- app.get('/reset/:token', () => {
- throw new ServiceUnavailableError({message: 'unavailable'});
- });
- const response = await app.request('/reset/abc123');
- expect(response.status).toBe(503);
- expect(logCalls.error).toHaveLength(1);
- expect(logCalls.error[0]![0].path).toBe('/reset/:token');
- });
-});