Skip to content

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

TypeScript fluxerfluxerapp

test: drop mocks, spies, fake timers and snapshots from tests

Hampusa2c2d8a39099
diff --git a/fluxer_api/package.json b/fluxer_api/package.json
index 8b6577b06..b8e671c75 100644
--- a/fluxer_api/package.json
+++ b/fluxer_api/package.json
@@ -71,7 +71,6 @@
"livekit-server-sdk": "catalog:",
"maxmind": "catalog:",
"mime": "catalog:",
- "nodemailer": "catalog:",
"pdf-lib": "catalog:",
"pg": "catalog:",
"pino": "catalog:",
diff --git a/fluxer_api/pkgs/cache/src/__tests__/CacheGetOrSet.test.ts b/fluxer_api/pkgs/cache/src/__tests__/CacheGetOrSet.test.ts
index cc6ff1eff..77ab31213 100644
--- a/fluxer_api/pkgs/cache/src/__tests__/CacheGetOrSet.test.ts
+++ b/fluxer_api/pkgs/cache/src/__tests__/CacheGetOrSet.test.ts
@@ -2,85 +2,66 @@
import {KVCacheProvider} from '@pkgs/cache/src/providers/KVCacheProvider';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {describe, expect, it, vi} from 'vitest';
-
-function delay(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
+import {describe, expect, it} from 'vitest';
describe('ICacheService.getOrSet', () => {
it('runs the factory once for concurrent callers on the same key', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const factory = vi.fn(async () => {
- await delay(10);
+ let calls = 0;
+ const factory = async () => {
+ calls += 1;
return 7;
- });
+ };
const results = await Promise.all([
cache.getOrSet('key', factory),
cache.getOrSet('key', factory),
cache.getOrSet('key', factory),
]);
expect(results).toEqual([7, 7, 7]);
- expect(factory).toHaveBeenCalledTimes(1);
+ expect(calls).toBe(1);
await expect(cache.get('key')).resolves.toBe(7);
});
- it('does not coalesce concurrent callers on different keys', async () => {
- const cache = new KVCacheProvider({client: new MockKVProvider()});
- const factory = vi.fn(async () => {
- await delay(10);
- return 1;
- });
- await Promise.all([cache.getOrSet('a', factory), cache.getOrSet('b', factory)]);
- expect(factory).toHaveBeenCalledTimes(2);
- });
-
- it('caches a null factory result and serves it as a hit', async () => {
- const cache = new KVCacheProvider({client: new MockKVProvider()});
- const factory = vi.fn(async () => null);
- await expect(cache.getOrSet<number | null>('key', factory, 60)).resolves.toBeNull();
- await expect(cache.getOrSet<number | null>('key', factory, 60)).resolves.toBeNull();
- expect(factory).toHaveBeenCalledTimes(1);
- });
-
it('serves a stored json null from the kv provider as a hit', async () => {
const client = new MockKVProvider();
const provider = new KVCacheProvider({client});
- const factory = vi.fn(async () => null);
+ let calls = 0;
+ const factory = async () => {
+ calls += 1;
+ return null;
+ };
await expect(provider.getOrSet<number | null>('key', factory, 60)).resolves.toBeNull();
expect(await client.get('key')).toBe('null');
await expect(provider.getOrSet<number | null>('key', factory, 60)).resolves.toBeNull();
- expect(factory).toHaveBeenCalledTimes(1);
+ expect(calls).toBe(1);
});
it('treats an unparseable stored value as a miss', async () => {
const client = new MockKVProvider();
const provider = new KVCacheProvider({client});
await client.set('key', '{not json');
- const factory = vi.fn(async () => 3);
- await expect(provider.getOrSet('key', factory, 60)).resolves.toBe(3);
- expect(factory).toHaveBeenCalledTimes(1);
+ await expect(provider.getOrSet('key', async () => 3, 60)).resolves.toBe(3);
+ await expect(provider.get('key')).resolves.toBe(3);
});
- it('resolves the ttl from the produced value', async ({onTestFinished}) => {
- const now = vi.spyOn(Date, 'now').mockReturnValue(1_000);
- onTestFinished(() => now.mockRestore());
+ it('resolves the ttl from the produced value', async () => {
const client = new MockKVProvider();
const provider = new KVCacheProvider({client});
const resolver = (value: number | null) => (value === null ? 5 : 30);
await expect(provider.getOrSet<number | null>('present', async () => 1, resolver)).resolves.toBe(1);
await expect(provider.getOrSet<number | null>('absent', async () => null, resolver)).resolves.toBeNull();
- expect(await client.ttl('present')).toBe(30);
- expect(await client.ttl('absent')).toBe(5);
+ expect(await client.ttl('present')).toBeGreaterThan(5);
+ expect(await client.ttl('absent')).toBeLessThanOrEqual(5);
expect(await client.get('absent')).toBe('null');
});
it('rejects every waiter after a single coalesced retry when the factory keeps failing', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const failing = vi.fn(async () => {
- await delay(10);
+ let calls = 0;
+ const failing = async (): Promise<number> => {
+ calls += 1;
throw new Error('factory failed');
- });
+ };
const settled = await Promise.allSettled([
cache.getOrSet('key', failing),
cache.getOrSet('key', failing),
@@ -88,25 +69,21 @@ describe('ICacheService.getOrSet', () => {
cache.getOrSet('key', failing),
]);
expect(settled.map((result) => result.status)).toEqual(['rejected', 'rejected', 'rejected', 'rejected']);
- expect(failing).toHaveBeenCalledTimes(2);
+ expect(calls).toBe(2);
await expect(cache.exists('key')).resolves.toBe(false);
- const succeeding = vi.fn(async () => 11);
- await expect(cache.getOrSet('key', succeeding)).resolves.toBe(11);
- expect(succeeding).toHaveBeenCalledTimes(1);
+ await expect(cache.getOrSet('key', async () => 11)).resolves.toBe(11);
});
it('does not fan a transient producer failure out to the callers that joined it', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
let calls = 0;
- const factory = vi.fn(async () => {
+ const factory = async () => {
calls += 1;
- const attempt = calls;
- await delay(10);
- if (attempt === 1) {
+ if (calls === 1) {
throw new Error('transient failure');
}
return 11;
- });
+ };
const settled = await Promise.allSettled([
cache.getOrSet('key', factory),
cache.getOrSet('key', factory),
@@ -117,7 +94,7 @@ describe('ICacheService.getOrSet', () => {
expect(settled.filter((result) => result.status === 'fulfilled').map((result) => result.value)).toEqual([
11, 11, 11,
]);
- expect(factory).toHaveBeenCalledTimes(2);
+ expect(calls).toBe(2);
await expect(cache.get('key')).resolves.toBe(11);
});
});
diff --git a/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts b/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts
index 0a0b55d4f..d23fac86d 100644
--- a/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts
+++ b/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts
@@ -3,13 +3,19 @@
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
import {KVCacheProvider} from '@pkgs/cache/src/providers/KVCacheProvider';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
const INFLIGHT_OVERFLOW_ENTRIES = 10000;
const PRODUCE_TIMEOUT_MS = 50;
const PRODUCE_TIMEOUT_MESSAGE = 'Cache produce timed out';
-function deferred<T>(): {promise: Promise<T>; resolve: (value: T) => void; reject: (error: Error) => void} {
+interface Deferred<T> {
+ promise: Promise<T>;
+ resolve: (value: T) => void;
+ reject: (error: Error) => void;
+}
+
+function deferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((res, rej) => {
@@ -19,22 +25,32 @@ function deferred<T>(): {promise: Promise<T>; resolve: (value: T) => void; rejec
return {promise, resolve, reject};
}
-function flush(): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, 0));
+interface GatedProduce {
+ started: Deferred<void>;
+ result: Deferred<string>;
}
-function settleWithin<T>(pending: Promise<T>, ms: number): Promise<T | 'pinned' | 'rejected'> {
- return Promise.race([
- pending.then(
- (value) => value,
- () => 'rejected' as const,
- ),
- new Promise<'pinned'>((resolve) => setTimeout(() => resolve('pinned'), ms)),
- ]);
+function gatedFactory(calls: number): {produces: Array<GatedProduce>; factory: () => Promise<string>} {
+ const produces = Array.from({length: calls}, () => ({started: deferred<void>(), result: deferred<string>()}));
+ let next = 0;
+ const factory = async () => {
+ const produce = produces[next++];
+ produce.started.resolve();
+ return await produce.result.promise;
+ };
+ return {produces, factory};
}
-function trackedProduceKeys(cache: ICacheService): Array<string> {
- return [...(cache as unknown as {produceInvalidations: Map<string, unknown>}).produceInvalidations.keys()];
+async function fillInflight(cache: ICacheService): Promise<() => Promise<void>> {
+ const fillers = Array.from({length: INFLIGHT_OVERFLOW_ENTRIES}, () => gatedFactory(1));
+ const filling = fillers.map((filler, index) => cache.getOrSet(`filler:${index}`, filler.factory, 30));
+ await Promise.all(fillers.map((filler) => filler.produces[0].started.promise));
+ return async () => {
+ for (const filler of fillers) {
+ filler.produces[0].result.resolve('filler');
+ }
+ await Promise.all(filling);
+ };
}
describe('cache invalidation during an in-flight produce', () => {
@@ -59,196 +75,101 @@ describe('cache invalidation during an in-flight produce', () => {
it('does not resurrect a value deleted while a retried produce was running', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const gates: Array<ReturnType<typeof deferred<string>>> = [];
- const factory = async () => {
- const gate = deferred<string>();
- gates.push(gate);
- return await gate.promise;
- };
+ const {produces, factory} = gatedFactory(2);
const producer = cache.getOrSet('session', factory, 30);
const joiner = cache.getOrSet('session', factory, 30);
- await flush();
- gates[0].reject(new Error('produce failed'));
+ await produces[0].started.promise;
+ produces[0].result.reject(new Error('produce failed'));
await expect(producer).rejects.toThrow('produce failed');
- await flush();
- expect(gates).toHaveLength(2);
+ await produces[1].started.promise;
await cache.delete('session');
- gates[1].resolve('fresh-after-delete');
+ produces[1].result.resolve('fresh-after-delete');
await expect(joiner).resolves.toBe('fresh-after-delete');
expect(await cache.get('session')).toBeNull();
});
it('stores the value a retried produce built when no invalidation happens', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const gates: Array<ReturnType<typeof deferred<string>>> = [];
- const factory = async () => {
- const gate = deferred<string>();
- gates.push(gate);
- return await gate.promise;
- };
+ const {produces, factory} = gatedFactory(2);
const producer = cache.getOrSet('session', factory, 30);
const joiner = cache.getOrSet('session', factory, 30);
- await flush();
- gates[0].reject(new Error('produce failed'));
+ await produces[0].started.promise;
+ produces[0].result.reject(new Error('produce failed'));
await expect(producer).rejects.toThrow('produce failed');
- await flush();
- gates[1].resolve('retried-session');
+ await produces[1].started.promise;
+ produces[1].result.resolve('retried-session');
await expect(joiner).resolves.toBe('retried-session');
expect(await cache.get('session')).toBe('retried-session');
});
it('stores the value a retried produce built after the first produce was invalidated', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const gates: Array<ReturnType<typeof deferred<string>>> = [];
- const factory = async () => {
- const gate = deferred<string>();
- gates.push(gate);
- return await gate.promise;
- };
+ const {produces, factory} = gatedFactory(2);
const producer = cache.getOrSet('session', factory, 30);
const joiner = cache.getOrSet('session', factory, 30);
- await flush();
+ await produces[0].started.promise;
await cache.delete('session');
- gates[0].reject(new Error('produce failed'));
+ produces[0].result.reject(new Error('produce failed'));
await expect(producer).rejects.toThrow('produce failed');
- await flush();
- expect(gates).toHaveLength(2);
- gates[1].resolve('retried-session');
+ await produces[1].started.promise;
+ produces[1].result.resolve('retried-session');
await expect(joiner).resolves.toBe('retried-session');
expect(await cache.get('session')).toBe('retried-session');
});
it('does not resurrect a value deleted after a concurrent caller released its produce', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const gate = deferred<string>();
- const pending = cache.getOrSet('session', async () => await gate.promise, 30);
- await flush();
+ const {produces, factory} = gatedFactory(1);
+ const pending = cache.getOrSet('session', factory, 30);
+ await produces[0].started.promise;
await cache.set('session', 'served-from-cache', 30);
await expect(cache.getOrSet('session', async () => 'unused', 30)).resolves.toBe('served-from-cache');
await cache.delete('session');
- gate.resolve('stale-produce');
+ produces[0].result.resolve('stale-produce');
await expect(pending).resolves.toBe('stale-produce');
expect(await cache.get('session')).toBeNull();
});
it('does not resurrect a value deleted while a second overflow produce was running', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const fillers: Array<ReturnType<typeof deferred<string>>> = [];
- const filling: Array<Promise<string>> = [];
- for (let index = 0; index < INFLIGHT_OVERFLOW_ENTRIES; index++) {
- const gate = deferred<string>();
- fillers.push(gate);
- filling.push(cache.getOrSet(`filler:${index}`, async () => await gate.promise, 30));
- }
- await flush();
+ const drain = await fillInflight(cache);
const first = deferred<string>();
const second = deferred<string>();
const firstProduce = cache.getOrSet('session', async () => await first.promise, 30);
const secondProduce = cache.getOrSet('session', async () => await second.promise, 30);
- await flush();
first.resolve('first-produce');
await expect(firstProduce).resolves.toBe('first-produce');
await cache.delete('session');
second.resolve('second-produce');
await expect(secondProduce).resolves.toBe('second-produce');
expect(await cache.get('session')).toBeNull();
- for (const gate of fillers) {
- gate.resolve('filler');
- }
- await Promise.all(filling);
- });
-
- it('drops produce tracking once the last produce for a key settles', async () => {
- const cache = new KVCacheProvider({client: new MockKVProvider()});
- for (let index = 0; index < 50; index++) {
- const gate = deferred<string>();
- const pending = cache.getOrSet(`session:${index}`, async () => await gate.promise, 30);
- await cache.delete(`session:${index}`);
- gate.resolve('value');
- await pending;
- }
- const shared = deferred<string>();
- const producer = cache.getOrSet('shared', async () => await shared.promise, 30);
- const joiner = cache.getOrSet('shared', async () => 'unused', 30);
- await flush();
- await cache.delete('shared');
- shared.resolve('shared-value');
- await Promise.all([producer, joiner]);
- const failing = cache.getOrSet(
- 'failing',
- async () => {
- throw new Error('produce failed');
- },
- 30,
- );
- await expect(failing).rejects.toThrow('produce failed');
- expect(trackedProduceKeys(cache)).toEqual([]);
+ await drain();
});
it('does not pin a key forever when the factory never settles', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
const stuck = deferred<string>();
const pinned = cache.getOrSet('session', async () => await stuck.promise, 30, PRODUCE_TIMEOUT_MS);
- await expect(settleWithin(pinned, 500)).resolves.toBe('rejected');
await expect(pinned).rejects.toThrow(PRODUCE_TIMEOUT_MESSAGE);
- const recovered = cache.getOrSet('session', async () => 'recovered', 30, PRODUCE_TIMEOUT_MS);
- await expect(settleWithin(recovered, 500)).resolves.toBe('recovered');
- stuck.resolve('never-settled');
- await flush();
+ await expect(cache.getOrSet('session', async () => 'recovered', 30, PRODUCE_TIMEOUT_MS)).resolves.toBe('recovered');
expect(await cache.get('session')).toBe('recovered');
});
- it('does not store a value produced by a factory that settled after the timeout', async () => {
- const cache = new KVCacheProvider({client: new MockKVProvider()});
- const stuck = deferred<string>();
- const pending = cache.getOrSet('session', async () => await stuck.promise, 30, PRODUCE_TIMEOUT_MS);
- await expect(pending).rejects.toThrow(PRODUCE_TIMEOUT_MESSAGE);
- stuck.resolve('late-produce');
- await flush();
- expect(await cache.get('session')).toBeNull();
- expect(trackedProduceKeys(cache)).toEqual([]);
- });
-
it('retries once for the joiners when the producer times out', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const gates: Array<ReturnType<typeof deferred<string>>> = [];
- const factory = async () => {
- const gate = deferred<string>();
- gates.push(gate);
- return await gate.promise;
- };
+ const {produces, factory} = gatedFactory(2);
const producer = cache.getOrSet('session', factory, 30, PRODUCE_TIMEOUT_MS);
const joiner = cache.getOrSet('session', factory, 30, PRODUCE_TIMEOUT_MS);
await expect(producer).rejects.toThrow(PRODUCE_TIMEOUT_MESSAGE);
- await flush();
- expect(gates).toHaveLength(2);
- gates[1].resolve('retried-session');
+ await produces[1].started.promise;
+ produces[1].result.resolve('retried-session');
await expect(joiner).resolves.toBe('retried-session');
expect(await cache.get('session')).toBe('retried-session');
- gates[0].resolve('abandoned-produce');
- await flush();
- expect(await cache.get('session')).toBe('retried-session');
- });
-
- it('releases produce tracking when the factory never settles', async () => {
- const cache = new KVCacheProvider({client: new MockKVProvider()});
- const stuck = deferred<string>();
- const pending = cache.getOrSet('session', async () => await stuck.promise, 30, PRODUCE_TIMEOUT_MS);
- await expect(pending).rejects.toThrow(PRODUCE_TIMEOUT_MESSAGE);
- await flush();
- expect(trackedProduceKeys(cache)).toEqual([]);
});
it('stores a sibling produce that succeeded after an overflow produce timed out', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
- const fillers: Array<ReturnType<typeof deferred<string>>> = [];
- const filling: Array<Promise<string>> = [];
- for (let index = 0; index < INFLIGHT_OVERFLOW_ENTRIES; index++) {
- const gate = deferred<string>();
- fillers.push(gate);
- filling.push(cache.getOrSet(`filler:${index}`, async () => await gate.promise, 30));
- }
- await flush();
+ const drain = await fillInflight(cache);
const stuck = deferred<string>();
const sibling = deferred<string>();
const abandoned = cache.getOrSet('session', async () => await stuck.promise, 30, PRODUCE_TIMEOUT_MS);
@@ -257,30 +178,7 @@ describe('cache invalidation during an in-flight produce', () => {
sibling.resolve('sibling-produce');
await expect(succeeding).resolves.toBe('sibling-produce');
expect(await cache.get('session')).toBe('sibling-produce');
- for (const gate of fillers) {
- gate.resolve('filler');
- }
- await Promise.all(filling);
- });
-
- it('does not hold the event loop open while a produce is in flight', async () => {
- const cache = new KVCacheProvider({client: new MockKVProvider()});
- const stuck = deferred<string>();
- const timers: Array<NodeJS.Timeout> = [];
- const scheduled = globalThis.setTimeout;
- const spy = vi.spyOn(globalThis, 'setTimeout').mockImplementation(((handler: () => void, ms?: number) => {
- const timer = scheduled(handler, ms);
- if (ms === PRODUCE_TIMEOUT_MS) {
- timers.push(timer);
- }
- return timer;
- }) as typeof globalThis.setTimeout);
- const pending = cache.getOrSet('session', async () => await stuck.promise, 30, PRODUCE_TIMEOUT_MS);
- await flush();
- spy.mockRestore();
- expect(timers).toHaveLength(1);
- expect(timers[0].hasRef()).toBe(false);
- await expect(pending).rejects.toThrow(PRODUCE_TIMEOUT_MESSAGE);
+ await drain();
});
it('keeps a later produce cacheable after an earlier one was invalidated', async () => {
diff --git a/fluxer_api/pkgs/email/src/DomainRoutedEmailProvider.test.ts b/fluxer_api/pkgs/email/src/DomainRoutedEmailProvider.test.ts
index 18722b375..c30380f4a 100644
--- a/fluxer_api/pkgs/email/src/DomainRoutedEmailProvider.test.ts
+++ b/fluxer_api/pkgs/email/src/DomainRoutedEmailProvider.test.ts
@@ -3,12 +3,29 @@
import {DomainRoutedEmailProvider} from '@pkgs/email/src/DomainRoutedEmailProvider';
import type {EmailMessage} from '@pkgs/email/src/EmailProviderTypes';
import {EmailService} from '@pkgs/email/src/EmailService';
-import {describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
function message(to: string): EmailMessage {
return {to, from: {email: '[email protected]', name: 'Example'}, subject: 'Hello', text: 'Body'};
}
+function recordingProviders(results: {primary: boolean; fallback: boolean}) {
+ const routes: Array<{route: 'primary' | 'fallback'; message: EmailMessage}> = [];
+ const primary = {
+ sendEmail: async (sent: EmailMessage) => {
+ routes.push({route: 'primary', message: sent});
+ return results.primary;
+ },
+ };
+ const fallback = {
+ sendEmail: async (sent: EmailMessage) => {
+ routes.push({route: 'fallback', message: sent});
+ return results.fallback;
+ },
+ };
+ return {routes, primary, fallback};
+}
+
describe('DomainRoutedEmailProvider', () => {
it.each([
{to: '[email protected]', route: 'fallback'},
@@ -19,30 +36,24 @@ describe('DomainRoutedEmailProvider', () => {
{to: '[email protected]', route: 'primary'},
{to: '"[email protected]"@example.com', route: 'primary'},
])('sends $to through the $route provider', async ({to, route}) => {
- const primary = {sendEmail: vi.fn().mockResolvedValue(true)};
- const fallback = {sendEmail: vi.fn().mockResolvedValue(false)};
+ const {routes, primary, fallback} = recordingProviders({primary: true, fallback: false});
const provider = new DomainRoutedEmailProvider(primary, fallback, ['gmail.com', 'googlemail.com']);
const sent = message(to);
const result = await provider.sendEmail(sent);
- const [chosen, other] = route === 'fallback' ? [fallback, primary] : [primary, fallback];
- expect(chosen.sendEmail).toHaveBeenCalledWith(sent);
- expect(other.sendEmail).not.toHaveBeenCalled();
+ expect(routes).toEqual([{route, message: sent}]);
expect(result).toBe(route === 'primary');
});
it('sends every address through the fallback provider when the domains are *', async () => {
- const primary = {sendEmail: vi.fn().mockResolvedValue(true)};
- const fallback = {sendEmail: vi.fn().mockResolvedValue(true)};
+ const {routes, primary, fallback} = recordingProviders({primary: true, fallback: true});
const provider = new DomainRoutedEmailProvider(primary, fallback, ['*']);
await provider.sendEmail(message('[email protected]'));
await provider.sendEmail(message('[email protected]'));
- expect(fallback.sendEmail).toHaveBeenCalledTimes(2);
- expect(primary.sendEmail).not.toHaveBeenCalled();
+ expect(routes.map((entry) => entry.route)).toEqual(['fallback', 'fallback']);
});
it('never reaches either provider for a bounced address', async () => {
- const primary = {sendEmail: vi.fn().mockResolvedValue(true)};
- const fallback = {sendEmail: vi.fn().mockResolvedValue(true)};
+ const {routes, primary, fallback} = recordingProviders({primary: true, fallback: true});
const service = new EmailService(
{
enabled: true,
@@ -64,7 +75,6 @@ describe('DomainRoutedEmailProvider', () => {
{isEmailBounced: async () => true},
);
expect(await service.send('password_reset', '[email protected]', {resetToken: 'token'})).toBe(false);
- expect(primary.sendEmail).not.toHaveBeenCalled();
- expect(fallback.sendEmail).not.toHaveBeenCalled();
+ expect(routes).toEqual([]);
});
});
diff --git a/fluxer_api/pkgs/rate_limit/src/__tests__/RateLimitService.test.ts b/fluxer_api/pkgs/rate_limit/src/__tests__/RateLimitService.test.ts
index 6815b9b66..b39bfc47b 100644
--- a/fluxer_api/pkgs/rate_limit/src/__tests__/RateLimitService.test.ts
+++ b/fluxer_api/pkgs/rate_limit/src/__tests__/RateLimitService.test.ts
@@ -1,74 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {KVRateLimitResult} from '@pkgs/kv_client/src/IKVProvider';
+import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import type {RateLimitConfig, RateLimitResult} from '@pkgs/rate_limit/src/IRateLimitService';
import {RateLimitService} from '@pkgs/rate_limit/src/RateLimitService';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface BucketState {
- level: number;
- updatedAt: number;
-}
-
-class LeakyBucketStore {
- readonly buckets = new Map<string, BucketState>();
-
- async checkLeakyBucketLimit(key: string, limit: number, windowMs: number, cost: number): Promise<KVRateLimitResult> {
- const nowMs = Date.now();
- const capacity = Math.max(1, Math.floor(limit));
- const leakWindowMs = Math.max(1, Math.floor(windowMs));
- const leakPerMs = capacity / leakWindowMs;
- const state = this.buckets.get(key) ?? {level: 0, updatedAt: nowMs};
- const elapsed = nowMs - state.updatedAt;
- let level = state.level;
- if (elapsed > 0) {
- level = Math.max(0, level - elapsed * leakPerMs);
- }
- const resetAfter = (current: number) => (current <= 0 ? 0 : Math.max(0, Math.ceil(current / leakPerMs)));
- const result = (allowed: boolean, remaining: number, resetAfterMs: number, retryAfterMs: number) => ({
- allowed,
- limit: capacity,
- remaining,
- resetAfterMs,
- resetAtMs: nowMs + resetAfterMs,
- retryAfterMs,
- });
- if (cost === 0) {
- this.save(key, level, nowMs);
- return result(true, Math.max(0, Math.floor(capacity - level)), resetAfter(level), 0);
- }
- if (level + cost > capacity) {
- const retryAfterMs = Math.max(1, Math.ceil((level + cost - capacity) / leakPerMs));
- const ttlMs = Math.max(1, resetAfter(level), retryAfterMs);
- this.save(key, level, nowMs);
- return result(false, 0, ttlMs, retryAfterMs);
- }
- level += cost;
- this.save(key, level, nowMs);
- return result(true, Math.max(0, Math.floor(capacity - level)), resetAfter(level), 0);
- }
-
- async del(...keys: Array<string>): Promise<number> {
- let deleted = 0;
- for (const key of keys) {
- if (this.buckets.delete(key)) deleted += 1;
- }
- return deleted;
- }
-
- async scan(pattern: string, _count: number): Promise<Array<string>> {
- const prefix = pattern.replace(/\*$/, '').replace(/\\(.)/g, '$1');
- return [...this.buckets.keys()].filter((key) => key.startsWith(prefix));
- }
-
- private save(key: string, level: number, nowMs: number): void {
- if (level > 0) {
- this.buckets.set(key, {level, updatedAt: nowMs});
- } else {
- this.buckets.delete(key);
- }
- }
-}
+import {describe, expect, it} from 'vitest';
const CONFIG: RateLimitConfig = {identifier: 'report:target:1', maxAttempts: 5, windowMs: 60_000};
@@ -76,44 +11,18 @@ function retryAfterMs(result: RateLimitResult): number {
return Math.round((result.retryAfterDecimal ?? 0) * 1000);
}
-function expectPeekMatchesCheck(peek: RateLimitResult, check: RateLimitResult): void {
- expect(check.allowed).toBe(false);
- expect(peek).toMatchObject({allowed: false, remaining: 0, limit: check.limit});
- expect(peek.retryAfter).toBe(check.retryAfter);
- expect(retryAfterMs(peek) - retryAfterMs(check)).toBeGreaterThanOrEqual(0);
- expect(retryAfterMs(peek) - retryAfterMs(check)).toBeLessThanOrEqual(1);
-}
-
-async function fill(service: RateLimitService, config: RateLimitConfig): Promise<void> {
- for (let attempt = 0; attempt < config.maxAttempts; attempt += 1) {
- expect((await service.checkLimit(config)).allowed).toBe(true);
- }
-}
-
describe('RateLimitService.peekLimit', () => {
- let store: LeakyBucketStore;
- let service: RateLimitService;
-
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-10-04T12:00:00.000Z'));
- store = new LeakyBucketStore();
- service = new RateLimitService(store);
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
it('allows an empty bucket without spending it', async () => {
+ const service = new RateLimitService(new MockKVProvider());
const peek = await service.peekLimit(CONFIG);
expect(peek).toMatchObject({allowed: true, limit: 5, remaining: 5});
expect(peek.retryAfter).toBeUndefined();
expect(peek.retryAfterDecimal).toBeUndefined();
- expect(store.buckets.size).toBe(0);
+ expect(await service.peekLimit(CONFIG)).toMatchObject({allowed: true, remaining: 5});
});
it('allows while capacity remains and reports the remaining count', async () => {
+ const service = new RateLimitService(new MockKVProvider());
await service.checkLimit(CONFIG);
await service.checkLimit(CONFIG);
const peek = await service.peekLimit(CONFIG);
@@ -123,58 +32,18 @@ describe('RateLimitService.peekLimit', () => {
});
it('rejects a full bucket with the retry-after a consuming check would report', async () => {
- await fill(service, CONFIG);
- const peek = await service.peekLimit(CONFIG);
- const check = await service.checkLimit(CONFIG);
- expectPeekMatchesCheck(peek, check);
- expect(retryAfterMs(peek)).toBe(12_000);
- expect(peek.retryAfter).toBe(12);
- });
-
- it('keeps rejecting while less than one slot has leaked', async () => {
- await fill(service, CONFIG);
- vi.advanceTimersByTime(6_000);
+ const service = new RateLimitService(new MockKVProvider());
+ for (let attempt = 0; attempt < CONFIG.maxAttempts; attempt += 1) {
+ expect((await service.checkLimit(CONFIG)).allowed).toBe(true);
+ }
const peek = await service.peekLimit(CONFIG);
const check = await service.checkLimit(CONFIG);
- expectPeekMatchesCheck(peek, check);
- expect(retryAfterMs(peek)).toBe(6_000);
- expect(peek.retryAfter).toBe(6);
- });
-
- it('does not spend budget when it rejects', async () => {
- await fill(service, CONFIG);
- for (let attempt = 0; attempt < 3; attempt += 1) {
- expect((await service.peekLimit(CONFIG)).allowed).toBe(false);
- }
- vi.advanceTimersByTime(12_000);
- expect(await service.peekLimit(CONFIG)).toMatchObject({allowed: true, remaining: 1});
- expect((await service.checkLimit(CONFIG)).allowed).toBe(true);
- expect((await service.peekLimit(CONFIG)).allowed).toBe(false);
- });
-
- it('matches the consuming check on a single-slot bucket', async () => {
- const config: RateLimitConfig = {identifier: 'slowmode:1:2', maxAttempts: 1, windowMs: 10_000};
- await service.checkLimit(config);
- vi.advanceTimersByTime(2_500);
- const peek = await service.peekLimit(config);
- const check = await service.checkLimit(config);
- expectPeekMatchesCheck(peek, check);
- expect(peek.retryAfterDecimal).toBe(7.5);
- expect(peek.retryAfter).toBe(8);
- expect(peek.resetTime.getTime()).toBe(Date.now() + 7_500);
- });
-
- it('agrees with the consuming check at every point of a draining bucket', async () => {
- const config: RateLimitConfig = {identifier: 'crosspost:edit:1', maxAttempts: 3, windowMs: 1_000};
- await fill(service, config);
- for (let step = 0; step < 12; step += 1) {
- vi.advanceTimersByTime(37);
- const peek = await service.peekLimit(config);
- const check = await service.checkLimit(config);
- expect(peek.allowed).toBe(check.allowed);
- if (!check.allowed) {
- expectPeekMatchesCheck(peek, check);
- }
- }
+ expect(check.allowed).toBe(false);
+ expect(peek).toMatchObject({allowed: false, remaining: 0, limit: check.limit, retryAfter: 12});
+ expect(check.retryAfter).toBe(12);
+ expect(retryAfterMs(peek)).toBeGreaterThan(11_900);
+ expect(retryAfterMs(peek)).toBeLessThanOrEqual(12_000);
+ expect(retryAfterMs(check)).toBeGreaterThan(11_900);
+ expect(retryAfterMs(check)).toBeLessThanOrEqual(12_000);
});
});
diff --git a/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts b/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts
index ca9d866f3..2e37565b8 100644
--- a/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminGuildSystemModeration.test.ts
@@ -8,7 +8,7 @@ import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
const SYSTEM_USER_ID = '0';
const STAFF_REASON = 'Staff ticket 4410: member is under 18';
diff --git a/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts b/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
index c9892e584..a98e855b2 100644
--- a/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminImmediateDeletion.test.ts
@@ -8,7 +8,7 @@ import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {triggerDeletionWorker, waitForDeletionCompletion} from '@app/api/user/tests/UserTestUtils';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('immediate account deletion from the admin panel', () => {
let harness: ApiTestHarness;
diff --git a/fluxer_api/src/api/admin/tests/AdminIpBanExpiry.test.ts b/fluxer_api/src/api/admin/tests/AdminIpBanExpiry.test.ts
index df35ec274..de2c95df8 100644
--- a/fluxer_api/src/api/admin/tests/AdminIpBanExpiry.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminIpBanExpiry.test.ts
@@ -1,13 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {type AdminAuditLog, AdminRepository} from '@app/api/admin/AdminRepository';
+import type {AdminAuditLog} from '@app/api/admin/AdminRepository';
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {getAdminRepository} 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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface BlocklistEntryPage {
items: Array<{value: string; reason: string | null; expires_at: string | null; created_at: string | null}>;
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigAdminController.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigAdminController.test.ts
index 9b40b7490..e6e98204c 100644
--- a/fluxer_api/src/api/admin/tests/InstanceConfigAdminController.test.ts
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigAdminController.test.ts
@@ -4,9 +4,8 @@ import type {AdminAuditLog} from '@app/api/admin/AdminRepository';
import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
-import {NatsConfigPublisher} from '@app/api/instance/NatsConfigPublisher';
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
-import {getAdminRepository} from '@app/api/middleware/ServiceSingletons';
+import {getAdminRepository, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
@@ -19,7 +18,7 @@ import {
type LegacyPushServiceDeliveryWire,
toLegacyPushServiceDeliveryWire,
} from '@fluxer/schema/src/domains/admin/PushRelaySchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const PUSH_RELAY_CONFIG_KEY = 'push_service_delivery_config';
@@ -37,10 +36,6 @@ describe('instance config admin PATCH under concurrent writes', () => {
await harness.reset();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
await harness.shutdown();
});
@@ -55,8 +50,6 @@ describe('instance config admin PATCH under concurrent writes', () => {
const patchConfig = (admin: TestAccount, body: Record<string, unknown>) =>
createBuilder<InstanceConfigResponse>(harness, admin.token).patch('/admin/instance/config').body(body);
- const spyOnPushRelayPublishes = () => vi.spyOn(NatsConfigPublisher.prototype, 'publish').mockResolvedValue(undefined);
-
async function readStoredPushRelay(): Promise<LegacyPushServiceDeliveryWire> {
const raw = await executor.readDirectly(PUSH_RELAY_CONFIG_KEY);
if (raw === null) throw new Error('push relay config was never stored');
@@ -83,17 +76,16 @@ describe('instance config admin PATCH under concurrent writes', () => {
});
it('answers with a conflict and neither writes, publishes nor audits once every attempt has lost the race', async () => {
- const publish = spyOnPushRelayPublishes();
const admin = await createAdmin();
- await patchConfig(admin, {push_relay: {relay_consent_accepted: false}}).execute();
- publish.mockClear();
- const auditsBefore = await listConfigUpdateAudits();
- executor.watch(PUSH_RELAY_CONFIG_KEY);
const unaccepted = {
relay_consent_accepted: false,
relay_consent_accepted_at: null,
relay_consent_accepted_by: null,
};
+ await executor.writeDirectly(PUSH_RELAY_CONFIG_KEY, JSON.stringify(toLegacyPushServiceDeliveryWire(unaccepted, 1)));
+ getInstanceConfigRepository().clearCacheForTesting();
+ const auditsBefore = await listConfigUpdateAudits();
+ executor.watch(PUSH_RELAY_CONFIG_KEY);
let competingWrites = 0;
executor.competeBeforeEachWrite(async () => {
competingWrites++;
@@ -109,7 +101,6 @@ describe('instance config admin PATCH under concurrent writes', () => {
expect(executor.events).not.toContain('write');
expect(await readStoredPushRelay()).toEqual(toLegacyPushServiceDeliveryWire(unaccepted, 100 + competingWrites));
- expect(publish).not.toHaveBeenCalled();
expect(await listConfigUpdateAudits()).toHaveLength(auditsBefore.length);
});
});
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts
index 348e37449..4599ef630 100644
--- a/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigBrandingAssetCleanup.test.ts
@@ -5,9 +5,14 @@ import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils'
import {Config, getConfig} from '@app/api/Config';
import {getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
import {NoopPurgeQueue} from '@app/api/infrastructure/CachePurgeQueue';
-import {getAssetDeletionQueue, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import {
+ getAssetDeletionQueue,
+ getGuildRepository,
+ getInstanceConfigRepository,
+ getUserRepository,
+} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import processAssetDeletionQueue from '@app/api/worker/tasks/ProcessAssetDeletionQueue';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
@@ -54,8 +59,8 @@ describe('branding image cleanup', () => {
purgeQueue: new NoopPurgeQueue(),
storageService: harness.storageService,
instanceConfigRepository: getInstanceConfigRepository(),
- userRepository: {findUnique: async () => null} as never,
- guildRepository: {findUnique: async () => null, getMember: async () => null} as never,
+ userRepository: getUserRepository(),
+ guildRepository: getGuildRepository(),
});
});
@@ -83,7 +88,7 @@ describe('branding image cleanup', () => {
}
async function storedAfterCleanup(key: string): Promise<boolean> {
- await processAssetDeletionQueue({}, HELPERS);
+ await processAssetDeletionQueue({}, createTestWorkerHelpers());
return harness.storageService.hasObject(Config.s3.buckets.cdn, key);
}
diff --git a/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts b/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts
index f14d56441..987ae6332 100644
--- a/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts
+++ b/fluxer_api/src/api/admin/tests/InstanceConfigSmtpTest.test.ts
@@ -9,8 +9,7 @@ import type {
InstanceConfigResponse,
InstanceEmailSmtpTestResponse,
} from '@fluxer/schema/src/domains/admin/AdminSchemas';
-import nodemailer, {type Transporter} from 'nodemailer';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('instance SMTP settings', () => {
let harness: ApiTestHarness;
diff --git a/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts b/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts
index c9b156b93..5b75fec66 100644
--- a/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts
+++ b/fluxer_api/src/api/admin/tests/PushRelayConsentAdmin.test.ts
@@ -13,7 +13,7 @@ import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import type {LegacyPushServiceDeliveryWire} from '@fluxer/schema/src/domains/admin/PushRelaySchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const PUSH_RELAY_CONFIG_KEY = 'push_service_delivery_config';
const ACCEPTED_AT = '2026-09-20T08:00:00.000Z';
diff --git a/fluxer_api/src/api/admin/tests/SingleCommunityExistingGuild.test.ts b/fluxer_api/src/api/admin/tests/SingleCommunityExistingGuild.test.ts
index d5a6962ab..b64a39495 100644
--- a/fluxer_api/src/api/admin/tests/SingleCommunityExistingGuild.test.ts
+++ b/fluxer_api/src/api/admin/tests/SingleCommunityExistingGuild.test.ts
@@ -1,16 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuild} from '@app/api/guild/tests/GuildTestUtils';
-import {getKVClient} from '@app/api/middleware/ServiceRegistry';
-import {getInstanceConfigRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import type {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, it} from 'vitest';
describe('single-community mode with an existing community', () => {
let harness: ApiTestHarness;
diff --git a/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts b/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts
deleted file mode 100644
index 47a05d213..000000000
--- a/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {ensureDeletionQueueState} from '@app/api/app/DeletionQueueStartup';
-import {createUserID} from '@app/api/BrandedTypes';
-import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
-import {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
-import {User} from '@app/api/models/User';
-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {describe, expect, it} from 'vitest';
-
-const WORKER_PAGE_COUNT = 2;
-
-class RecordingLogger implements LoggerInterface {
- readonly errors: Array<string> = [];
-
- trace(): void {}
- debug(): void {}
- info(): void {}
- warn(): void {}
- fatal(): void {}
-
- error(obj: object | string, msg?: string): void {
- this.errors.push(typeof obj === 'string' ? obj : (msg ?? ''));
- }
-
- child(): LoggerInterface {
- return this;
- }
-}
-
-function createPendingUser(index: number): User {
- return new User({
- ...EMPTY_USER_ROW,
- user_id: createUserID(BigInt(9100 + index)),
- pending_deletion_at: new Date('2026-06-01T00:00:00.000Z'),
- deletion_reason_code: 0,
- });
-}
-
-function createWorkerRepository(onPageStart: (page: number) => Promise<void>): UserRepository {
- let page = 0;
- return {
- async scanAllUsersPage() {
- page += 1;
- await onPageStart(page);
- return {
- users: [createPendingUser(page)],
- pageState: page < WORKER_PAGE_COUNT ? `page-${page}` : null,
- };
- },
- } as unknown as UserRepository;
-}
-
-describe('ensureDeletionQueueState', () => {
- it('leaves a rebuild owned by another instance alone', async () => {
- const kvClient = new MockKVProvider();
- let apiScans = 0;
- const apiRepository = {
- async scanAllUsersPage() {
- apiScans += 1;
- throw new Error('api pod scan failed');
- },
- } as unknown as UserRepository;
- const apiQueue = new KVAccountDeletionQueueService(kvClient, apiRepository);
- const apiFailures: Array<unknown> = [];
- const workerQueue = new KVAccountDeletionQueueService(
- kvClient,
- createWorkerRepository(async (page) => {
- if (page !== WORKER_PAGE_COUNT) {
- return;
- }
- try {
- await ensureDeletionQueueState(apiQueue, new NoopLogger());
- } catch (error) {
- apiFailures.push(error);
- }
- }),
- );
-
- const workerToken = await workerQueue.acquireRebuildLock();
- expect(workerToken).not.toBeNull();
- await workerQueue.rebuildState(workerToken);
- expect(await workerQueue.releaseRebuildLock(workerToken!)).toBe(true);
-
- const queued = await workerQueue.getReadyDeletions(Date.parse('2026-06-02T00:00:00.000Z'), 10);
- expect(queued.map((deletion) => deletion.userId).sort()).toEqual([9101n, 9102n]);
- expect(apiScans).toBe(0);
- expect(apiFailures).toEqual([]);
- });
-
- it('does not abort startup when the paged user scan fails', async () => {
- const kvClient = new MockKVProvider();
- let scans = 0;
- const repository = {
- async scanAllUsersPage() {
- scans += 1;
- throw new Error('paged user scan failed');
- },
- } as unknown as UserRepository;
- const queue = new KVAccountDeletionQueueService(kvClient, repository);
- const logger = new RecordingLogger();
-
- await expect(ensureDeletionQueueState(queue, logger)).resolves.toBeUndefined();
-
- expect(scans).toBe(1);
- expect(logger.errors).toEqual(['KV deletion queue rebuild failed, leaving the rebuild to the deletion worker']);
- expect(await queue.acquireRebuildLock()).not.toBeNull();
- });
-
- it('rebuilds under the lock when no other instance holds it', async () => {
- const kvClient = new MockKVProvider();
- const queue = new KVAccountDeletionQueueService(
- kvClient,
- createWorkerRepository(async () => {}),
- );
-
- await ensureDeletionQueueState(queue, new NoopLogger());
-
- const queued = await queue.getReadyDeletions(Date.parse('2026-06-02T00:00:00.000Z'), 10);
- expect(queued.map((deletion) => deletion.userId).sort()).toEqual([9101n, 9102n]);
- expect(await queue.acquireRebuildLock()).not.toBeNull();
- });
-});
diff --git a/fluxer_api/src/api/attachment/AttachmentDecayService.test.ts b/fluxer_api/src/api/attachment/AttachmentDecayService.test.ts
index d98d12666..c0e054732 100644
--- a/fluxer_api/src/api/attachment/AttachmentDecayService.test.ts
+++ b/fluxer_api/src/api/attachment/AttachmentDecayService.test.ts
@@ -1,15 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {AttachmentDecayRepository} from '@app/api/attachment/AttachmentDecayRepository';
+import {AttachmentDecayRepository} from '@app/api/attachment/AttachmentDecayRepository';
import {type AttachmentDecayPayload, AttachmentDecayService} from '@app/api/attachment/AttachmentDecayService';
-import type {AttachmentID} from '@app/api/BrandedTypes';
import {createAttachmentID, createChannelID, createMessageID} from '@app/api/BrandedTypes';
+import {resetCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
import type {InstanceAttachmentDecayEffectiveConfig} from '@app/api/instance/InstanceConfigRepository';
-import type {AttachmentDecayRow} from '@app/api/types/AttachmentDecayTypes';
+import {getExpiryBucket} from '@app/api/utils/AttachmentDecay';
import {ms} from 'itty-time';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {beforeEach, describe, expect, it} from 'vitest';
-const NOW = new Date('2026-10-10T00:00:00.000Z');
const ATTACHMENT_ID = createAttachmentID(7001n);
const CONFIG: InstanceAttachmentDecayEffectiveConfig = {
enabled: true,
@@ -23,10 +22,16 @@ const CONFIG: InstanceAttachmentDecayEffectiveConfig = {
renew_window_days: 30,
};
+let NOW = new Date();
+
function daysFromNow(days: number): Date {
return new Date(NOW.getTime() + days * ms('1 day'));
}
+function expectAboutDaysFromRealNow(date: Date | undefined, days: number): void {
+ expect(Math.abs(date!.getTime() - (Date.now() + days * ms('1 day')))).toBeLessThan(ms('1 minute'));
+}
+
function payload(uploadedAt: Date, sizeBytes = 1024n): AttachmentDecayPayload {
return {
attachmentId: ATTACHMENT_ID,
@@ -39,19 +44,12 @@ function payload(uploadedAt: Date, sizeBytes = 1024n): AttachmentDecayPayload {
}
function createService(config: InstanceAttachmentDecayEffectiveConfig = CONFIG) {
- const rows = new Map<AttachmentID, AttachmentDecayRow>();
- const repo = {
- async fetchByIds(ids: Array<AttachmentID>) {
- return new Map(ids.flatMap((id) => (rows.has(id) ? [[id, rows.get(id)!] as const] : [])));
- },
- async upsert(record: AttachmentDecayRow) {
- rows.set(record.attachment_id, record);
- },
- async deleteRecords({attachment_id}: {attachment_id: AttachmentID}) {
- rows.delete(attachment_id);
- },
- } as unknown as AttachmentDecayRepository;
- return {rows, service: new AttachmentDecayService(repo, async () => config)};
+ const repo = new AttachmentDecayRepository();
+ return {repo, service: new AttachmentDecayService(repo, async () => config)};
+}
+
+async function storedExpiry(repo: AttachmentDecayRepository): Promise<Date | undefined> {
+ return (await repo.fetchByIds([ATTACHMENT_ID])).get(ATTACHMENT_ID)?.expires_at;
}
async function fileExists(): Promise<boolean> {
@@ -62,8 +60,8 @@ async function fileMissing(): Promise<boolean> {
return false;
}
-function seed(rows: Map<AttachmentID, AttachmentDecayRow>, uploadedAt: Date, expiresAt: Date): void {
- rows.set(ATTACHMENT_ID, {
+async function seed(repo: AttachmentDecayRepository, uploadedAt: Date, expiresAt: Date): Promise<void> {
+ await repo.upsert({
attachment_id: ATTACHMENT_ID,
channel_id: createChannelID(7002n),
message_id: createMessageID(7003n),
@@ -75,106 +73,103 @@ function seed(rows: Map<AttachmentID, AttachmentDecayRow>, uploadedAt: Date, exp
cost: 1,
lifetime_days: 1,
status: null,
+ expiry_bucket: getExpiryBucket(expiresAt),
});
}
describe('AttachmentDecayService.reconcile', () => {
beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(NOW);
- });
-
- afterEach(() => {
- vi.useRealTimers();
+ resetCassandraQueryExecutorForTesting();
+ NOW = new Date();
});
it('writes nothing while expiry is off', async () => {
- const {rows, service} = createService({...CONFIG, enabled: false});
+ const {repo, service} = createService({...CONFIG, enabled: false});
expect(await service.reconcile([payload(daysFromNow(-10))], fileExists)).toBe(0);
- expect(rows.size).toBe(0);
+ expect(await storedExpiry(repo)).toBeUndefined();
});
it('gives an untracked attachment the expiry its upload date implies', async () => {
- const {rows, service} = createService();
+ const {repo, service} = createService();
expect(await service.reconcile([payload(daysFromNow(-100))], fileExists)).toBe(1);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(265));
+ expect(await storedExpiry(repo)).toEqual(daysFromNow(265));
});
it('gives an untracked attachment that is already overdue the renew window', async () => {
- const {rows, service} = createService();
+ const {repo, service} = createService();
await service.reconcile([payload(daysFromNow(-1000))], fileExists);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(30));
+ expectAboutDaysFromRealNow(await storedExpiry(repo), 30);
});
it('gives an attachment whose expiry passed unnoticed the renew window', async () => {
- const {rows, service} = createService();
- seed(rows, daysFromNow(-1000), daysFromNow(-200));
+ const {repo, service} = createService();
+ await seed(repo, daysFromNow(-1000), daysFromNow(-200));
await service.reconcile([payload(daysFromNow(-1000))], fileExists);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(30));
+ expectAboutDaysFromRealNow(await storedExpiry(repo), 30);
});
it('leaves an untracked attachment alone when its file is gone', async () => {
- const {rows, service} = createService();
+ const {repo, service} = createService();
expect(await service.reconcile([payload(daysFromNow(-100))], fileMissing)).toBe(0);
- expect(rows.size).toBe(0);
+ expect(await storedExpiry(repo)).toBeUndefined();
});
it('keeps a passed expiry when the file is gone', async () => {
- const {rows, service} = createService();
- seed(rows, daysFromNow(-1000), daysFromNow(-200));
+ const {repo, service} = createService();
+ await seed(repo, daysFromNow(-1000), daysFromNow(-200));
expect(await service.reconcile([payload(daysFromNow(-1000))], fileMissing)).toBe(0);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(-200));
+ expect(await storedExpiry(repo)).toEqual(daysFromNow(-200));
});
it('does not look for the file of an attachment that is still pending', async () => {
- const {rows, service} = createService({...CONFIG, max_lifetime_days: 730});
- seed(rows, daysFromNow(-100), daysFromNow(265));
+ const {repo, service} = createService({...CONFIG, max_lifetime_days: 730});
+ await seed(repo, daysFromNow(-100), daysFromNow(265));
await service.reconcile([payload(daysFromNow(-100))], fileMissing);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(630));
+ expect(await storedExpiry(repo)).toEqual(daysFromNow(630));
});
it('extends a tracked attachment when the lifetime grows', async () => {
- const {rows, service} = createService({...CONFIG, max_lifetime_days: 730});
- seed(rows, daysFromNow(-100), daysFromNow(265));
+ const {repo, service} = createService({...CONFIG, max_lifetime_days: 730});
+ await seed(repo, daysFromNow(-100), daysFromNow(265));
await service.reconcile([payload(daysFromNow(-100))], fileExists);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(630));
+ expect(await storedExpiry(repo)).toEqual(daysFromNow(630));
});
it('shortens a tracked attachment no further than the renew window', async () => {
- const {rows, service} = createService({...CONFIG, max_lifetime_days: 60});
- seed(rows, daysFromNow(-100), daysFromNow(265));
+ const {repo, service} = createService({...CONFIG, max_lifetime_days: 60});
+ await seed(repo, daysFromNow(-100), daysFromNow(265));
await service.reconcile([payload(daysFromNow(-100))], fileExists);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(30));
+ expectAboutDaysFromRealNow(await storedExpiry(repo), 30);
});
it('keeps an expiry that already falls inside the renew window', async () => {
- const {rows, service} = createService({...CONFIG, max_lifetime_days: 60});
- seed(rows, daysFromNow(-100), daysFromNow(12));
+ const {repo, service} = createService({...CONFIG, max_lifetime_days: 60});
+ await seed(repo, daysFromNow(-100), daysFromNow(12));
expect(await service.reconcile([payload(daysFromNow(-100))], fileExists)).toBe(0);
- expect(rows.get(ATTACHMENT_ID)?.expires_at).toEqual(daysFromNow(12));
+ expect(await storedExpiry(repo)).toEqual(daysFromNow(12));
});
it('drops the record of an attachment that is no longer eligible', async () => {
- const {rows, service} = createService({...CONFIG, max_eligible_size_mb: 1});
- seed(rows, daysFromNow(-100), daysFromNow(265));
+ const {repo, service} = createService({...CONFIG, max_eligible_size_mb: 1});
+ await seed(repo, daysFromNow(-100), daysFromNow(265));
expect(await service.reconcile([payload(daysFromNow(-100), 2n * 1024n * 1024n)], fileExists)).toBe(1);
- expect(rows.size).toBe(0);
+ expect(await storedExpiry(repo)).toBeUndefined();
});
it('settles after one pass', async () => {
diff --git a/fluxer_api/src/api/auth/tests/AuthSessionReplacement.test.ts b/fluxer_api/src/api/auth/tests/AuthSessionReplacement.test.ts
index 87912e2ec..4f6e2a772 100644
--- a/fluxer_api/src/api/auth/tests/AuthSessionReplacement.test.ts
+++ b/fluxer_api/src/api/auth/tests/AuthSessionReplacement.test.ts
@@ -10,10 +10,9 @@ import {
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {generateUniquePassword, HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface AuthSessionRow {
id_hash: string;
@@ -25,8 +24,6 @@ interface ReplacementResponse {
auth_session_id_hash?: string;
}
-type GatewayCall = {kind: 'terminate'; hashes: Array<string>} | {kind: 'session_change'; data: Record<string, unknown>};
-
async function getCurrentAuthSessionHash(harness: ApiTestHarness, token: string): Promise<string> {
const sessions = await createBuilder<Array<AuthSessionRow>>(harness, token).get('/auth/sessions').execute();
const current = sessions.find((session) => session.current);
@@ -63,52 +60,28 @@ async function completePasswordChange(
describe('Auth session replacement on password change', () => {
let harness: ApiTestHarness;
- let calls: Array<GatewayCall>;
beforeAll(async () => {
harness = await createAuthHarness();
});
beforeEach(async () => {
await harness.reset();
await clearTestEmails(harness);
- calls = [];
- vi.spyOn(NoopGatewayService.prototype, 'terminateSession').mockImplementation(async (params) => {
- calls.push({kind: 'terminate', hashes: [...params.sessionIdHashes]});
- });
- vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence').mockImplementation(async (params) => {
- if (params.event === 'AUTH_SESSION_CHANGE') {
- calls.push({kind: 'session_change', data: params.data as Record<string, unknown>});
- }
- });
- });
- afterEach(() => {
- vi.restoreAllMocks();
});
afterAll(async () => {
await harness?.shutdown();
});
- function expectReplacedSessionClosedBeforeEvent(oldHash: string, newHash: string | undefined): void {
- const eventIndex = calls.findIndex((call) => call.kind === 'session_change');
- const terminateIndex = calls.findIndex((call) => call.kind === 'terminate' && call.hashes.includes(oldHash));
- expect(terminateIndex).toBeGreaterThanOrEqual(0);
- expect(eventIndex).toBeGreaterThan(terminateIndex);
- const event = calls[eventIndex] as Extract<GatewayCall, {kind: 'session_change'}>;
- expect(event.data).toEqual({old_auth_session_id_hash: oldHash, new_auth_session_id_hash: newHash});
- }
-
it('returns the replacement token from PATCH /users/@me', async () => {
const account = await createTestAccount(harness);
const otherSession = await loginAccount(harness, account);
const oldHash = await getCurrentAuthSessionHash(harness, account.token);
- calls = [];
const response = await createBuilder<ReplacementResponse>(harness, account.token)
.patch('/users/@me')
.body({password: account.password, new_password: generateUniquePassword()})
.expect(HTTP_STATUS.OK)
.execute();
expect(typeof response.token).toBe('string');
- expect(typeof response.auth_session_id_hash).toBe('string');
- expectReplacedSessionClosedBeforeEvent(oldHash, response.auth_session_id_hash);
+ expect(response.auth_session_id_hash).not.toBe(oldHash);
await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
await createBuilder(harness, otherSession.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
await createBuilder(harness, response.token!).get('/users/@me').expect(HTTP_STATUS.OK).execute();
@@ -124,15 +97,14 @@ describe('Auth session replacement on password change', () => {
.execute();
expect(response.token).toBeUndefined();
expect(response.auth_session_id_hash).toBeUndefined();
- expect(calls).toEqual([]);
+ await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.OK).execute();
});
- it('closes the replaced session before announcing the change on password-change/complete', async () => {
+ it('returns a working replacement token from password-change/complete', async () => {
const account = await createTestAccount(harness);
- const oldHash = await getCurrentAuthSessionHash(harness, account.token);
- calls = [];
const response = await completePasswordChange(harness, account, generateUniquePassword());
- expectReplacedSessionClosedBeforeEvent(oldHash, response.auth_session_id_hash);
+ await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
await createBuilder(harness, response.token!).get('/users/@me').expect(HTTP_STATUS.OK).execute();
+ expect(await getCurrentAuthSessionHash(harness, response.token!)).toBe(response.auth_session_id_hash);
});
});
diff --git a/fluxer_api/src/api/auth/tests/BouncedEmailRecoveryFlow.test.ts b/fluxer_api/src/api/auth/tests/BouncedEmailRecoveryFlow.test.ts
index 908f52af0..763fd0bbb 100644
--- a/fluxer_api/src/api/auth/tests/BouncedEmailRecoveryFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/BouncedEmailRecoveryFlow.test.ts
@@ -8,10 +8,12 @@ import {
listTestEmails,
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
+import {resetApiServicesForTesting} from '@app/api/CreateApiContext';
+import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
+import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface BouncedEmailRequestNewResponse {
ticket: string;
@@ -52,9 +54,6 @@ describe('Bounced email recovery flow', () => {
await harness.reset();
await clearTestEmails(harness);
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
afterAll(async () => {
await harness?.shutdown();
});
@@ -66,7 +65,9 @@ describe('Bounced email recovery flow', () => {
.body({stripe_customer_id: 'cus_bounced_email_sync'})
.expect(200)
.execute();
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
+ const worker = new RecordingWorkerService();
+ setInjectedWorkerService(worker);
+ resetApiServicesForTesting();
const initialMe = await createBuilder<UserPrivateResponse>(harness, account.token)
.get('/users/@me')
.expect(200)
@@ -104,7 +105,7 @@ describe('Bounced email recovery flow', () => {
const finalMe = await createBuilder<UserPrivateResponse>(harness, account.token).get('/users/@me').execute();
expect(finalMe.email).toBe(replacementEmail);
expect(finalMe.email_bounced).toBe(false);
- expect(addJob).toHaveBeenCalledWith('syncStripeCustomerEmail', {userId: account.userId});
+ expect(worker.byTask('syncStripeCustomerEmail').map((job) => job.payload)).toContainEqual({userId: account.userId});
});
it('rejects bounced-email recovery for accounts that are not marked as bounced', async () => {
const account = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts
index 230f8e4f9..6df2388be 100644
--- a/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailChangeFlow.test.ts
@@ -11,12 +11,14 @@ import {
loginUser,
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
+import {resetApiServicesForTesting} from '@app/api/CreateApiContext';
+import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
+import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface EmailChangeStartResponse {
ticket: string;
@@ -374,7 +376,9 @@ describe('Email change flow', () => {
.body({has_ever_purchased: true, stripe_customer_id: 'cus_email_change_sync'})
.expect(200)
.execute();
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
+ const worker = new RecordingWorkerService();
+ setInjectedWorkerService(worker);
+ resetApiServicesForTesting();
const startResp = await startEmailChange(harness, account, account.password);
let originalProof: string;
if (startResp.require_original) {
@@ -414,7 +418,7 @@ describe('Email change flow', () => {
.execute();
expect(updated.email).toBe(newEmail);
expect(updated.has_ever_purchased).toBe(true);
- expect(addJob).toHaveBeenCalledWith('syncStripeCustomerEmail', {userId: account.userId});
+ expect(worker.byTask('syncStripeCustomerEmail').map((job) => job.payload)).toContainEqual({userId: account.userId});
});
it('requires MFA (not password) for email_token apply when user has TOTP enabled', async () => {
const account = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.ts b/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.ts
index c083e6035..d9b3b0c02 100644
--- a/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailCodeAttemptRace.test.ts
@@ -31,7 +31,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {EmailCodeResendCooldownError} from '@fluxer/errors/src/domains/auth/EmailCodeResendCooldownError';
import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type {IRateLimitService} from '@pkgs/rate_limit/src/IRateLimitService';
+import {RateLimitService} from '@pkgs/rate_limit/src/RateLimitService';
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const GUESSES = 40;
@@ -192,22 +192,28 @@ describe('Email code attempt cap under concurrency', () => {
});
});
-describe('Daily code failure caps', () => {
- const allowAll: IRateLimitService = {
- checkLimit: async () => ({allowed: true, limit: 0, remaining: 0, resetTime: new Date()}),
- } as unknown as IRateLimitService;
+function budgetEnv() {
+ const kv = new MockKVProvider();
+ return {kv, rateLimit: new RateLimitService(kv), enforce: true};
+}
- async function failFrom(env: Parameters<typeof recordAddressCodeFailure>[0], emailKey: string, clientIp: string) {
+describe('Daily code failure caps', () => {
+ async function failFrom(
+ env: Parameters<typeof recordAddressCodeFailure>[0],
+ emailKey: string,
+ ipFor: (failure: number) => string,
+ ) {
for (let failure = 0; failure < CODE_FAILURES_DAILY_CAP; failure++) {
+ const clientIp = ipFor(failure);
await assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp});
await recordAddressCodeFailure(env, {emailKey, network: requesterNetworkKey(clientIp)});
}
}
it('stops unknown requesters on the failing IPv4 /24 only', async () => {
- const env = {kv: new MockKVProvider(), rateLimit: allowAll, enforce: true};
+ const env = budgetEnv();
const emailKey = normalizeEmailKey('[email protected]');
- await failFrom(env, emailKey, '203.0.113.9');
+ await failFrom(env, emailKey, (failure) => `203.0.113.${failure + 1}`);
await expect(
assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '203.0.113.77'}),
).rejects.toBeInstanceOf(EmailCodeResendCooldownError);
@@ -220,9 +226,9 @@ describe('Daily code failure caps', () => {
});
it('stops unknown requesters on the failing IPv6 /48 only', async () => {
- const env = {kv: new MockKVProvider(), rateLimit: allowAll, enforce: true};
+ const env = budgetEnv();
const emailKey = normalizeEmailKey('[email protected]');
- await failFrom(env, emailKey, '2001:db8:1:1::1');
+ await failFrom(env, emailKey, (failure) => `2001:db8:1:${failure + 1}::1`);
await expect(
assertEmailSendAllowed(env, {emailKey, requester: 'unknown', clientIp: '2001:db8:1:ffff::2'}),
).rejects.toBeInstanceOf(EmailCodeResendCooldownError);
@@ -232,11 +238,11 @@ describe('Daily code failure caps', () => {
});
it('stops every code to an account once its own wrong codes reach the account cap', async () => {
- const env = {kv: new MockKVProvider(), rateLimit: allowAll, enforce: true};
+ const env = budgetEnv();
const emailKey = normalizeEmailKey('[email protected]');
const userId = '1234567890';
for (let failure = 0; failure < ACCOUNT_CODE_FAILURES_DAILY_CAP; failure++) {
- await assertEmailSendAllowed(env, {emailKey, requester: 'known', clientIp: '203.0.113.9', userId});
+ await assertEmailSendAllowed(env, {emailKey, requester: 'known', clientIp: `203.0.113.${failure + 1}`, userId});
await recordAccountCodeFailure(env, userId);
}
for (const requester of ['known', 'unknown'] as const) {
@@ -250,7 +256,7 @@ describe('Daily code failure caps', () => {
});
it('caps lookups at 30 per IP and 300 per subnet', async () => {
- const env = {kv: new MockKVProvider(), rateLimit: countingRateLimit(), enforce: true};
+ const env = budgetEnv();
for (let lookup = 0; lookup < 30; lookup++) await enforceLookupHardLimits(env, '203.0.113.1');
await expect(enforceLookupHardLimits(env, '203.0.113.1')).rejects.toBeInstanceOf(RateLimitError);
for (let host = 2; host <= 10; host++) {
diff --git a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
index 88fc5357c..af0ca9893 100644
--- a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
@@ -10,12 +10,14 @@ import {
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
import {createUserID} from '@app/api/BrandedTypes';
+import {resetApiServicesForTesting} from '@app/api/CreateApiContext';
+import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
+import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {UserTraits} from '@app/api/user/UserTraits';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface EmailChangeStartResponse {
ticket: string;
@@ -198,10 +200,12 @@ describe('Email revert flow', () => {
.body({stripe_customer_id: 'cus_email_revert_sync'})
.expect(200)
.execute();
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
+ const worker = new RecordingWorkerService();
+ setInjectedWorkerService(worker);
+ resetApiServicesForTesting();
const revertToken = await changeEmailAndGetRevertToken(harness, account);
const newPassword = uniquePassword();
- addJob.mockClear();
+ worker.jobs.length = 0;
const revertResp = await createBuilderWithoutAuth<EmailRevertResponse>(harness)
.post('/auth/email-revert')
.body({
@@ -210,7 +214,7 @@ describe('Email revert flow', () => {
})
.execute();
expect(revertResp.token.length).toBeGreaterThan(0);
- expect(addJob).toHaveBeenCalledWith('syncStripeCustomerEmail', {userId: account.userId});
+ expect(worker.byTask('syncStripeCustomerEmail').map((job) => job.payload)).toContainEqual({userId: account.userId});
expect(Object.keys(revertResp).sort()).toEqual(['token', 'user', 'user_id']);
await createBuilder(harness, account.token).get('/users/@me').expect(401).execute();
const user = await createBuilder<UserPrivateResponse>(harness, revertResp.token).get('/users/@me').execute();
diff --git a/fluxer_api/src/api/auth/tests/IdentifierFirstSignIn.test.ts b/fluxer_api/src/api/auth/tests/IdentifierFirstSignIn.test.ts
index 470f30cfa..06a1927ba 100644
--- a/fluxer_api/src/api/auth/tests/IdentifierFirstSignIn.test.ts
+++ b/fluxer_api/src/api/auth/tests/IdentifierFirstSignIn.test.ts
@@ -39,7 +39,7 @@ import {
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface IdentifyBody {
ticket: string;
diff --git a/fluxer_api/src/api/auth/tests/PasswordReset.test.ts b/fluxer_api/src/api/auth/tests/PasswordReset.test.ts
index c5e6f175d..951a55422 100644
--- a/fluxer_api/src/api/auth/tests/PasswordReset.test.ts
+++ b/fluxer_api/src/api/auth/tests/PasswordReset.test.ts
@@ -12,8 +12,7 @@ import {
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {generateUniquePassword, HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('Password reset flow', () => {
let harness: ApiTestHarness;
@@ -166,29 +165,23 @@ describe('Password reset flow', () => {
.expect(HTTP_STATUS.FORBIDDEN)
.execute();
const approval = findLastTestEmail(await listTestEmails(harness, {recipient: account.email}), 'ip_authorization');
- vi.useFakeTimers({toFake: ['Date']});
- vi.setSystemTime(new Date(Date.now() + 1000));
- try {
- await createBuilderWithoutAuth(harness)
- .post('/auth/forgot')
- .body({email: account.email})
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- const token = findLastTestEmail(await listTestEmails(harness, {recipient: account.email}), 'password_reset')!
- .metadata!.token!;
- await createBuilderWithoutAuth(harness)
- .post('/auth/reset')
- .body({token, password: generateUniquePassword()})
- .execute();
- await createBuilderWithoutAuth(harness)
- .post('/auth/authorize-ip')
- .header('x-forwarded-for', '192.0.2.88')
- .body({token: approval!.metadata['token']})
- .expect(HTTP_STATUS.BAD_REQUEST)
- .execute();
- } finally {
- vi.useRealTimers();
- }
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/forgot')
+ .body({email: account.email})
+ .expect(HTTP_STATUS.NO_CONTENT)
+ .execute();
+ const token = findLastTestEmail(await listTestEmails(harness, {recipient: account.email}), 'password_reset')!
+ .metadata!.token!;
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/reset')
+ .body({token, password: generateUniquePassword()})
+ .execute();
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/authorize-ip')
+ .header('x-forwarded-for', '192.0.2.88')
+ .body({token: approval!.metadata['token']})
+ .expect(HTTP_STATUS.BAD_REQUEST)
+ .execute();
});
it('rejects invalid reset token', async () => {
await createTestAccount(harness);
diff --git a/fluxer_api/src/api/auth/tests/PwnedPasswordCheck.test.ts b/fluxer_api/src/api/auth/tests/PwnedPasswordCheck.test.ts
index b244f1a43..2c708732d 100644
--- a/fluxer_api/src/api/auth/tests/PwnedPasswordCheck.test.ts
+++ b/fluxer_api/src/api/auth/tests/PwnedPasswordCheck.test.ts
@@ -4,15 +4,14 @@ import crypto from 'node:crypto';
import type {ApiContext} from '@app/api/ApiContext';
import {isPasswordPwned, resetPwnedPasswordCacheForTesting} from '@app/api/auth/AuthPassword';
import {getConfig} from '@app/api/Config';
+import {createApiContext} from '@app/api/CreateApiContext';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {server} from '@app/api/test/msw/server';
-import {delay, HttpResponse, http} from 'msw';
-import {beforeEach, describe, expect, test} from 'vitest';
+import {HttpResponse, http} from 'msw';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
const PWNED_PASSWORD = 'fluxer-prefix-592';
const SAFE_PASSWORD_SAME_PREFIX = 'fluxer-prefix-837';
-const HANGING_RESPONSE_MS = 8000;
-
-const ctx = {} as unknown as ApiContext;
function sha1(password: string): string {
return crypto.createHash('sha1').update(password).digest('hex').toUpperCase();
@@ -41,14 +40,16 @@ function rangeHandler(requestedPrefixes: Array<string>, pwnedSuffixes: Array<str
});
}
-function hangingRangeHandler() {
- return http.get('https://api.pwnedpasswords.com/range/:prefix', async () => {
- await delay(HANGING_RESPONSE_MS);
- return HttpResponse.text('');
- });
-}
-
describe('isPasswordPwned', () => {
+ let harness: ApiTestHarness;
+ let ctx: ApiContext;
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ ctx = createApiContext();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
beforeEach(() => {
resetPwnedPasswordCacheForTesting();
});
@@ -82,12 +83,4 @@ describe('isPasswordPwned', () => {
server.use(http.get('https://api.pwnedpasswords.com/range/:prefix', () => HttpResponse.text('', {status: 503})));
await expect(isPasswordPwned(ctx, PWNED_PASSWORD)).resolves.toBe(false);
});
- test('fails open the same way when the lookup times out, without caching the prefix', async () => {
- server.use(hangingRangeHandler());
- await expect(isPasswordPwned(ctx, PWNED_PASSWORD)).resolves.toBe(false);
- const requestedPrefixes: Array<string> = [];
- server.use(rangeHandler(requestedPrefixes, [suffixOf(PWNED_PASSWORD)]));
- await expect(isPasswordPwned(ctx, PWNED_PASSWORD)).resolves.toBe(true);
- expect(requestedPrefixes).toHaveLength(1);
- });
});
diff --git a/fluxer_api/src/api/auth/tests/RecoveryKit.test.ts b/fluxer_api/src/api/auth/tests/RecoveryKit.test.ts
index 77b01de04..17d92d4bd 100644
--- a/fluxer_api/src/api/auth/tests/RecoveryKit.test.ts
+++ b/fluxer_api/src/api/auth/tests/RecoveryKit.test.ts
@@ -30,7 +30,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {HttpResponse, http} from 'msw';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const NEW_PASSWORD = 'recovered-strong-password-123';
const RECOVERY_KEY_PATTERN = /^[0-9A-HJKMNP-TV-Z]{4}(-[0-9A-HJKMNP-TV-Z]{4}){7}$/;
diff --git a/fluxer_api/src/api/auth/tests/Registration.test.ts b/fluxer_api/src/api/auth/tests/Registration.test.ts
index 8ed13dace..4d83f3c1a 100644
--- a/fluxer_api/src/api/auth/tests/Registration.test.ts
+++ b/fluxer_api/src/api/auth/tests/Registration.test.ts
@@ -29,7 +29,7 @@ import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';
import {ms} from 'itty-time';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
function bootstrapRegistrationBody(prefix: string): Record<string, unknown> {
return {
diff --git a/fluxer_api/src/api/auth/tests/ResetPasswordRequiresMfa.test.ts b/fluxer_api/src/api/auth/tests/ResetPasswordRequiresMfa.test.ts
index ea0bf8a36..672b604f6 100644
--- a/fluxer_api/src/api/auth/tests/ResetPasswordRequiresMfa.test.ts
+++ b/fluxer_api/src/api/auth/tests/ResetPasswordRequiresMfa.test.ts
@@ -35,6 +35,12 @@ interface MfaRequiredResponse {
backup_codes: boolean;
}
+async function lastEmail(harness: ApiTestHarness, type: string, recipient: string): Promise<TestEmailRecord> {
+ const email = findLastTestEmail(await listTestEmails(harness, {recipient}), type);
+ expect(email).not.toBeNull();
+ return email!;
+}
+
async function claimEmailWithoutPassword(harness: ApiTestHarness, account: TestAccount): Promise<TestAccount> {
await unclaimAccount(harness, account.userId);
const start = await createBuilder<{ticket: string; original_proof?: string}>(harness, account.token)
@@ -46,7 +52,7 @@ async function claimEmailWithoutPassword(harness: ApiTestHarness, account: TestA
.post('/users/@me/email-change/request-new')
.body({ticket: start.ticket, new_email: email, original_proof: start.original_proof})
.execute();
- const newEmail = await waitForEmail(harness, 'email_change_new', email);
+ const newEmail = await lastEmail(harness, 'email_change_new', email);
const verify = await createBuilder<{email_token: string}>(harness, account.token)
.post('/users/@me/email-change/verify-new')
.body({ticket: start.ticket, code: newEmail.metadata['code'], original_proof: start.original_proof})
@@ -58,7 +64,7 @@ async function claimEmailWithoutPassword(harness: ApiTestHarness, account: TestA
async function requestPasswordReset(harness: ApiTestHarness, email: string): Promise<string> {
await clearTestEmails(harness);
await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email}).expect(204).execute();
- const mail = await waitForEmail(harness, 'password_reset', email);
+ const mail = await lastEmail(harness, 'password_reset', email);
const token = mail.metadata['token'];
expect(token).toBeDefined();
return token!;
@@ -83,7 +89,7 @@ describe('Auth reset password requires MFA', () => {
.body({secret, code: totpCodeNow(secret), password: account.password})
.execute();
await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- const email = await waitForEmail(harness, 'password_reset', account.email);
+ const email = await lastEmail(harness, 'password_reset', account.email);
const token = email.metadata['token'];
expect(token).toBeDefined();
const newPassword = 'new-strong-password-123';
@@ -122,7 +128,7 @@ describe('Auth reset password requires MFA', () => {
await registerWebAuthnCredential(harness, account.token, device, () => ({password: account.password}));
await clearTestEmails(harness);
await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- const email = await waitForEmail(harness, 'password_reset', account.email);
+ const email = await lastEmail(harness, 'password_reset', account.email);
const token = email.metadata['token'];
expect(token).toBeDefined();
const resetResp = await createBuilderWithoutAuth<LoginSuccessResponse | MfaRequiredResponse>(harness)
@@ -139,7 +145,7 @@ describe('Auth reset password requires MFA', () => {
await setWebAuthnTwoFactor(harness, account.token, true, {password: account.password});
await clearTestEmails(harness);
await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- const email = await waitForEmail(harness, 'password_reset', account.email);
+ const email = await lastEmail(harness, 'password_reset', account.email);
const token = email.metadata['token'];
expect(token).toBeDefined();
const resetResp = await createBuilderWithoutAuth<MfaRequiredResponse>(harness)
@@ -246,7 +252,7 @@ describe('Auth reset password requires MFA', () => {
.execute();
await clearTestEmails(harness);
await createBuilderWithoutAuth(harness).post('/auth/forgot').body({email: account.email}).expect(204).execute();
- const token = (await waitForEmail(harness, 'password_reset', account.email)).metadata['token'];
+ const token = (await lastEmail(harness, 'password_reset', account.email)).metadata['token'];
const reset = await createBuilderWithoutAuth<MfaRequiredResponse>(harness)
.post('/auth/reset')
.body({token, password: 'new-strong-password-123'})
diff --git a/fluxer_api/src/api/channel/repositories/ThreadRepository.test.ts b/fluxer_api/src/api/channel/repositories/ThreadRepository.test.ts
index eba0d777c..6ad8bbc94 100644
--- a/fluxer_api/src/api/channel/repositories/ThreadRepository.test.ts
+++ b/fluxer_api/src/api/channel/repositories/ThreadRepository.test.ts
@@ -47,7 +47,7 @@ import {ChannelFlags, MAX_THREAD_MEMBERS} from '@fluxer/constants/src/ThreadCons
import {MaxThreadMembersError} from '@fluxer/errors/src/domains/channel/MaxThreadMembersError';
import {ThreadAlreadyCreatedForMessageError} from '@fluxer/errors/src/domains/channel/ThreadAlreadyCreatedForMessageError';
import {createSnowflakeFromTimestamp} from '@fluxer/snowflake/src/Snowflake';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
const GUILD_ID = createGuildID(1_900_000_000_000_000_000n);
const PARENT_ID = createChannelID(1_900_000_000_000_000_100n);
@@ -359,8 +359,10 @@ function describeThreadRepository(backend: string, makeExecutor: () => Promise<C
});
it('drops and reports stale index rows, and repairs missing ones', async () => {
- const drift = vi.fn();
- const threads = new ThreadRepository(repositories.channelData, repositories.messages, drift);
+ const drifted: Array<Array<ChannelID>> = [];
+ const threads = new ThreadRepository(repositories.channelData, repositories.messages, (threadIds) => {
+ drifted.push(threadIds);
+ });
const threadId = freshThreadId();
await threads.create(createParams(threadId));
await threads.updateState(threadId, () => ({archived: true}));
@@ -373,7 +375,7 @@ function describeThreadRepository(backend: string, makeExecutor: () => Promise<C
}),
);
expect(await threads.listActiveThreads(GUILD_ID)).toEqual([]);
- expect(drift).toHaveBeenCalledWith([threadId]);
+ expect(drifted).toContainEqual([threadId]);
expect(
await fetchMany(ActiveThreadsByGuild.selectCql({where: ActiveThreadsByGuild.where.eq('guild_id')}), {
guild_id: GUILD_ID,
diff --git a/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts b/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts
deleted file mode 100644
index 2270ebcc1..000000000
--- a/fluxer_api/src/api/channel/services/interaction/MessagePinService.test.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ChannelID, MessageID} from '@app/api/BrandedTypes';
-import {createChannelID, createGuildID, createMessageID, createUserID} from '@app/api/BrandedTypes';
-import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import type {AuthenticatedChannel} from '@app/api/channel/services/AuthenticatedChannel';
-import {MessagePinService} from '@app/api/channel/services/interaction/MessagePinService';
-import type {MessagePersistenceService} from '@app/api/channel/services/message/MessagePersistenceService';
-import type {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
-import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
-import {Message} from '@app/api/models/Message';
-import {ChannelTypes, MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import {createSnowflakeFromTimestamp} from '@fluxer/snowflake/src/Snowflake';
-import {describe, expect, it} from 'vitest';
-
-const CHANNEL_ID = createChannelID(10n);
-const GUILD_ID = createGuildID(20n);
-const VIEWER_ID = createUserID(7n);
-const CUTOFF = new Date('2026-01-10T00:00:00.000Z');
-const CUTOFF_ISO: string | null = CUTOFF.toISOString();
-const HIDDEN_CREATED_AT = new Date('2026-01-01T00:00:00.000Z');
-const VISIBLE_CREATED_AT = new Date('2026-01-20T00:00:00.000Z');
-const PIN_EPOCH = new Date('2026-02-01T00:00:00.000Z');
-
-function makeMessageId(timestamp: Date, sequence: number): MessageID {
- return createMessageID(createSnowflakeFromTimestamp(timestamp.getTime()) + BigInt(sequence));
-}
-
-function makePin(createdAt: Date, sequence: number, pinnedAtOffsetMs: number): Message {
- return new Message({
- channel_id: CHANNEL_ID,
- bucket: 0,
- message_id: makeMessageId(createdAt, sequence),
- author_id: null,
- type: MessageTypes.DEFAULT,
- webhook_id: null,
- webhook_name: null,
- webhook_avatar_hash: null,
- content: '',
- edited_timestamp: null,
- pinned_timestamp: new Date(PIN_EPOCH.getTime() + pinnedAtOffsetMs),
- flags: 0,
- mention_everyone: false,
- mention_users: null,
- mention_roles: null,
- mention_channels: null,
- attachments: null,
- embeds: null,
- sticker_items: null,
- message_reference: null,
- message_snapshots: null,
- call: null,
- has_reaction: null,
- version: 1,
- });
-}
-
-function createPinService({canReadHistory, pins}: {canReadHistory: boolean; pins: Array<Message>}) {
- const calls: Array<{before: Date; limit: number}> = [];
- const channelRepository = {
- messageInteractions: {
- listChannelPins: async (_channelId: ChannelID, before: Date, limit: number) => {
- calls.push({before, limit});
- return pins
- .filter((pin) => pin.pinnedTimestamp!.getTime() < before.getTime())
- .sort((a, b) => b.pinnedTimestamp!.getTime() - a.pinnedTimestamp!.getTime())
- .slice(0, limit);
- },
- },
- } as unknown as ChannelRepository;
- const channel = {id: CHANNEL_ID, type: ChannelTypes.GUILD_TEXT, guildId: GUILD_ID};
- const authChannel: AuthenticatedChannel = {
- channel: channel as AuthenticatedChannel['channel'],
- guild: {message_history_cutoff: CUTOFF_ISO} as AuthenticatedChannel['guild'],
- member: null,
- hasPermission: async () => canReadHistory,
- checkPermission: async () => {},
- };
- const service = new MessagePinService(
- {} as unknown as IGatewayService,
- channelRepository,
- {} as unknown as ISnowflakeService,
- {} as unknown as MessagePersistenceService,
- {} as unknown as GuildAuditLogService,
- );
- return {
- authChannel,
- calls,
- listPins: (limit: number) =>
- service.getChannelPins({
- authChannel,
- userId: VIEWER_ID,
- requestCache: {} as unknown as RequestCache,
- limit,
- }),
- };
-}
-
-describe('MessagePinService.getChannelPins', () => {
- it('walks past a full page of pins hidden by the history cutoff', async () => {
- const hidden = Array.from({length: 12}, (_value, index) => makePin(HIDDEN_CREATED_AT, index, 1_000 + index));
- const visible = Array.from({length: 5}, (_value, index) => makePin(VISIBLE_CREATED_AT, index, index));
- const {calls, listPins} = createPinService({canReadHistory: false, pins: [...hidden, ...visible]});
-
- const page = await listPins(10);
-
- expect(page.items.map((item) => item.message.id)).toEqual(
- [...visible].reverse().map((message) => message.id.toString()),
- );
- expect(page.has_more).toBe(false);
- expect(calls).toHaveLength(2);
- });
-
- it('reports has_more when visible pins behind the hidden run outnumber the page', async () => {
- const hidden = Array.from({length: 12}, (_value, index) => makePin(HIDDEN_CREATED_AT, index, 1_000 + index));
- const visible = Array.from({length: 11}, (_value, index) => makePin(VISIBLE_CREATED_AT, index, index));
- const {listPins} = createPinService({canReadHistory: false, pins: [...hidden, ...visible]});
-
- const page = await listPins(10);
-
- expect(page.items).toHaveLength(10);
- expect(page.has_more).toBe(true);
- expect(page.items.map((item) => item.message.id)).toEqual(
- [...visible]
- .reverse()
- .slice(0, 10)
- .map((message) => message.id.toString()),
- );
- });
-});
diff --git a/fluxer_api/src/api/channel/services/message/CrosspostPropagation.ts b/fluxer_api/src/api/channel/services/message/CrosspostPropagation.ts
index e1c8206ee..db86f0b31 100644
--- a/fluxer_api/src/api/channel/services/message/CrosspostPropagation.ts
+++ b/fluxer_api/src/api/channel/services/message/CrosspostPropagation.ts
@@ -104,7 +104,7 @@ export function crosspostSyncChunkJobKey(params: {
return `crosspost-sync-chunk:${params.messageId}:${params.mode}:${params.bucketOrMode}:${params.firstWebhookId}`;
}
-export function publishedEditRateLimitIdentifier(messageId: MessageID): string {
+function publishedEditRateLimitIdentifier(messageId: MessageID): string {
return `crosspost:edit:${messageId}`;
}
diff --git a/fluxer_api/src/api/channel/services/message/MessageHelpers.test.ts b/fluxer_api/src/api/channel/services/message/MessageHelpers.test.ts
index b4ef2a17b..3b79b2737 100644
--- a/fluxer_api/src/api/channel/services/message/MessageHelpers.test.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageHelpers.test.ts
@@ -8,8 +8,8 @@ import {
} from '@app/api/channel/services/message/MessageHelpers';
import type {MessageEmbed} from '@app/api/database/types/MessageTypes';
import type {IPurgeQueue} from '@app/api/infrastructure/CachePurgeQueue';
-import type {IStorageService} from '@app/api/infrastructure/IStorageService';
import {Message} from '@app/api/models/Message';
+import {MockStorageService} from '@app/api/test/mocks/MockStorageService';
import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';
import {describe, expect, it} from 'vitest';
@@ -96,13 +96,8 @@ function makeMessageWithMedia(
describe('purgeMessageAttachments', () => {
it('queues each stored media URL of a deleted message once and leaves media of other messages alone', async () => {
- const deletedObjects: Array<string> = [];
const queuedUrls: Array<string> = [];
- const storageService = {
- deleteObject: async (bucket: string, key: string) => {
- deletedObjects.push(`${bucket}/${key}`);
- },
- } as unknown as IStorageService;
+ const storageService = new MockStorageService();
const purgeQueue: IPurgeQueue = {
addUrls: async (urls) => {
queuedUrls.push(...urls);
@@ -111,17 +106,12 @@ describe('purgeMessageAttachments', () => {
await purgeMessageAttachments(makeMessageWithMedia(), storageService, purgeQueue);
- expect(deletedObjects).toEqual([`${Config.s3.buckets.cdn}/${ATTACHMENT_KEY}`]);
+ expect(storageService.getDeletedObjects()).toEqual([{bucket: Config.s3.buckets.cdn, key: ATTACHMENT_KEY}]);
expect(queuedUrls).toEqual([`${Config.endpoints.media}/${ATTACHMENT_KEY}`]);
});
it('purges embed files the message owns and leaves marked files under other channels alone', async () => {
- const deletedObjects: Array<string> = [];
- const storageService = {
- deleteObject: async (_bucket: string, key: string) => {
- deletedObjects.push(key);
- },
- } as unknown as IStorageService;
+ const storageService = new MockStorageService();
const purgeQueue: IPurgeQueue = {addUrls: async () => {}};
const ownedEmbedKey = 'attachments/10/201/embed.png';
@@ -135,6 +125,6 @@ describe('purgeMessageAttachments', () => {
purgeQueue,
);
- expect(deletedObjects).toEqual([ATTACHMENT_KEY, ownedEmbedKey]);
+ expect(storageService.getDeletedObjects().map((object) => object.key)).toEqual([ATTACHMENT_KEY, ownedEmbedKey]);
});
});
diff --git a/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts b/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts
index 55435ffe2..42a307ef8 100644
--- a/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts
+++ b/fluxer_api/src/api/channel/tests/AnnouncementChannelConversion.test.ts
@@ -32,7 +32,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
import {ChannelTypes, WebhookTypes} from '@fluxer/constants/src/ChannelConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
interface AuditLogResponse {
audit_log_entries: Array<{
diff --git a/fluxer_api/src/api/channel/tests/AnnouncementThreadRaces.test.ts b/fluxer_api/src/api/channel/tests/AnnouncementThreadRaces.test.ts
deleted file mode 100644
index e5958f3c6..000000000
--- a/fluxer_api/src/api/channel/tests/AnnouncementThreadRaces.test.ts
+++ /dev/null
@@ -1,256 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createChannelID, createGuildID, createMessageID} from '@app/api/BrandedTypes';
-import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {ChannelDataRepository} from '@app/api/channel/repositories/ChannelDataRepository';
-import {MessageInteractionRepository} from '@app/api/channel/repositories/MessageInteractionRepository';
-import {MessageRepository} from '@app/api/channel/repositories/MessageRepository';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
-import {ChannelOperationsService} from '@app/api/channel/services/channel_data/ChannelOperationsService';
-import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
-import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
-import {BatchBuilder} from '@app/api/database/CassandraQueryExecution';
-import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
-import {sendMessage} from '@app/api/message/tests/MessageTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {ChannelTypes, MessageFlags} from '@fluxer/constants/src/ChannelConstants';
-import {ServerMessageFlags} from '@fluxer/constants/src/ThreadConstants';
-import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-interface Setup {
- owner: TestAccount;
- guildId: string;
- textId: string;
- announcementId: string;
-}
-
-const repository = new ChannelRepository();
-
-describe('announcement thread races', () => {
- let harness: ApiTestHarness;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- clearChannelThreadsTaintCacheForTesting();
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- afterAll(async () => {
- clearChannelThreadsTaintCacheForTesting();
- await harness.shutdown();
- });
-
- async function setup(): Promise<Setup> {
- const owner = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'news races');
- const text = await createChannel(harness, owner.token, guild.id, 'general');
- const announcement = await createChannel(harness, owner.token, guild.id, 'news', ChannelTypes.GUILD_ANNOUNCEMENT);
- return {owner, guildId: guild.id, textId: text.id, announcementId: announcement.id};
- }
-
- async function startThread(token: string, channelId: string): Promise<ThreadChannelResponse> {
- return threadsRequest<ThreadChannelResponse>(harness, token)
- .post(`/channels/${channelId}/threads`)
- .body({name: 'topic', type: ChannelTypes.PUBLIC_THREAD})
- .expect(201)
- .execute();
- }
-
- it('keeps a thread archived during a retype out of the active index', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.textId);
- const threadId = createChannelID(BigInt(thread.id));
- const execute = BatchBuilder.prototype.execute;
- let armed = true;
- vi.spyOn(BatchBuilder.prototype, 'execute').mockImplementation(async function (
- this: BatchBuilder,
- ...args: Parameters<BatchBuilder['execute']>
- ) {
- if (armed) {
- armed = false;
- await repository.threads.updateState(threadId, () => ({archived: true}));
- }
- return execute.apply(this, args);
- });
- await repository.threads.setThreadType(threadId, ChannelTypes.ANNOUNCEMENT_THREAD);
- vi.restoreAllMocks();
- expect((await repository.threads.getState(threadId))?.archived).toBe(true);
- expect(await repository.threads.countActiveThreads(createGuildID(BigInt(s.guildId)))).toBe(0);
- });
-
- it('leaves no rows behind for a thread deleted during a retype', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.textId);
- const threadId = createChannelID(BigInt(thread.id));
- const execute = BatchBuilder.prototype.execute;
- let armed = true;
- vi.spyOn(BatchBuilder.prototype, 'execute').mockImplementation(async function (
- this: BatchBuilder,
- ...args: Parameters<BatchBuilder['execute']>
- ) {
- if (armed) {
- armed = false;
- await repository.threads.purgeThread(threadId);
- }
- return execute.apply(this, args);
- });
- expect(await repository.threads.setThreadType(threadId, ChannelTypes.ANNOUNCEMENT_THREAD)).toBeNull();
- vi.restoreAllMocks();
- expect(await repository.channelData.findUnique(threadId)).toBeNull();
- expect(await repository.threads.getState(threadId)).toBeNull();
- expect(await repository.threads.listParentThreads(createChannelID(BigInt(s.textId)))).toEqual([]);
- expect(await repository.threads.countActiveThreads(createGuildID(BigInt(s.guildId)))).toBe(0);
- });
-
- it('does not revert a retyped thread when a rename read the old row', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.textId);
- const threadId = createChannelID(BigInt(thread.id));
- const updateState = ThreadRepository.prototype.updateState;
- vi.spyOn(ThreadRepository.prototype, 'updateState').mockImplementationOnce(async function (
- this: ThreadRepository,
- ...args: Parameters<ThreadRepository['updateState']>
- ) {
- const result = await updateState.apply(this, args);
- await repository.threads.setThreadType(threadId, ChannelTypes.ANNOUNCEMENT_THREAD);
- return result;
- });
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${thread.id}`)
- .body({name: 'renamed'})
- .expect(200)
- .execute();
- vi.restoreAllMocks();
- const stored = await repository.channelData.findUnique(threadId);
- expect(stored?.name).toBe('renamed');
- expect(stored?.type).toBe(ChannelTypes.ANNOUNCEMENT_THREAD);
- expect((await repository.threads.getState(threadId))?.type).toBe(ChannelTypes.ANNOUNCEMENT_THREAD);
- });
-
- it('does not revert a retyped thread when a pin read the old row', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.textId);
- const threadId = createChannelID(BigInt(thread.id));
- const message = await threadsRequest<MessageResponse>(harness, s.owner.token)
- .post(`/channels/${thread.id}/messages`)
- .body({content: 'pin me'})
- .expect(200)
- .execute();
- const addChannelPin = MessageInteractionRepository.prototype.addChannelPin;
- vi.spyOn(MessageInteractionRepository.prototype, 'addChannelPin').mockImplementationOnce(async function (
- this: MessageInteractionRepository,
- ...args: Parameters<MessageInteractionRepository['addChannelPin']>
- ) {
- await addChannelPin.apply(this, args);
- await repository.threads.setThreadType(threadId, ChannelTypes.ANNOUNCEMENT_THREAD);
- });
- await threadsRequest(harness, s.owner.token).put(`/channels/${thread.id}/pins/${message.id}`).expect(204).execute();
- vi.restoreAllMocks();
- const stored = await repository.channelData.findUnique(threadId);
- expect(stored?.lastPinTimestamp).not.toBeNull();
- expect(stored?.type).toBe(ChannelTypes.ANNOUNCEMENT_THREAD);
- expect((await repository.threads.getState(threadId))?.type).toBe(ChannelTypes.ANNOUNCEMENT_THREAD);
- });
-
- it('does not revert a converted parent when an overwrite edit read the old row', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.textId);
- const operations = ChannelOperationsService.prototype as unknown as {checkOverwritePermission: () => Promise<void>};
- vi.spyOn(operations, 'checkOverwritePermission').mockImplementationOnce(async () => {
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.textId}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(200)
- .execute();
- });
- await threadsRequest(harness, s.owner.token)
- .put(`/channels/${s.textId}/permissions/${s.owner.userId}`)
- .body({type: 1, allow: '0', deny: '0'})
- .expect(204)
- .execute();
- vi.restoreAllMocks();
- const parent = await repository.channelData.findUnique(createChannelID(BigInt(s.textId)));
- expect(parent?.type).toBe(ChannelTypes.GUILD_ANNOUNCEMENT);
- expect(parent?.permissionOverwrites?.size ?? 0).toBeGreaterThan(0);
- expect((await repository.threads.getState(createChannelID(BigInt(thread.id))))?.type).toBe(
- ChannelTypes.ANNOUNCEMENT_THREAD,
- );
- });
-
- it('restores retyped threads when the parent write fails', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.textId);
- const threadId = createChannelID(BigInt(thread.id));
- const upsert = ChannelDataRepository.prototype.upsert;
- vi.spyOn(ChannelDataRepository.prototype, 'upsert').mockImplementation(async function (
- this: ChannelDataRepository,
- ...args: Parameters<ChannelDataRepository['upsert']>
- ) {
- if (
- args[0].channel_id === createChannelID(BigInt(s.textId)) &&
- args[0].type === ChannelTypes.GUILD_ANNOUNCEMENT
- ) {
- throw new Error('write timeout');
- }
- return upsert.apply(this, args);
- });
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.textId}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(500)
- .execute();
- vi.restoreAllMocks();
- expect((await repository.channelData.findUnique(createChannelID(BigInt(s.textId))))?.type).toBe(
- ChannelTypes.GUILD_TEXT,
- );
- expect((await repository.channelData.findUnique(threadId))?.type).toBe(ChannelTypes.PUBLIC_THREAD);
- expect((await repository.threads.getState(threadId))?.type).toBe(ChannelTypes.PUBLIC_THREAD);
- });
-
- it('keeps both flags when a publish races a thread start on the same message', async () => {
- const s = await setup();
- const message = await sendMessage(harness, s.owner.token, s.announcementId, 'headline');
- const channelId = createChannelID(BigInt(s.announcementId));
- const messageId = createMessageID(BigInt(message.id));
- const getMessage = MessageRepository.prototype.getMessage;
- let publish: Promise<unknown> | null = null;
- vi.spyOn(MessageRepository.prototype, 'getMessage').mockImplementation(async function (
- this: MessageRepository,
- ...args: Parameters<MessageRepository['getMessage']>
- ) {
- if (
- publish === null &&
- args[1] === messageId &&
- (await repository.threads.getState(createChannelID(BigInt(message.id)))) !== null
- ) {
- publish = threadsRequest(harness, s.owner.token)
- .post(`/channels/${s.announcementId}/messages/${message.id}/crosspost`)
- .expect(200)
- .execute();
- await Promise.race([publish, new Promise((resolve) => setTimeout(resolve, 200))]);
- }
- return getMessage.apply(this, args);
- });
- await threadsRequest(harness, s.owner.token)
- .post(`/channels/${s.announcementId}/messages/${message.id}/threads`)
- .body({name: 'Discussion'})
- .expect(201)
- .execute();
- expect(publish).not.toBeNull();
- await publish;
- vi.restoreAllMocks();
- const stored = await repository.messages.getMessage(channelId, messageId);
- expect(stored!.flags & ServerMessageFlags.HAS_THREAD).toBe(ServerMessageFlags.HAS_THREAD);
- expect(stored!.flags & MessageFlags.CROSSPOSTED).toBe(MessageFlags.CROSSPOSTED);
- });
-});
diff --git a/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts b/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts
index 8c2b14ca5..6a6e99f62 100644
--- a/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts
+++ b/fluxer_api/src/api/channel/tests/AnnouncementThreads.test.ts
@@ -24,7 +24,7 @@ import type {
ThreadChannelResponse,
} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
diff --git a/fluxer_api/src/api/channel/tests/AttachmentDecay.test.ts b/fluxer_api/src/api/channel/tests/AttachmentDecay.test.ts
index bf12f57d1..c0dab0222 100644
--- a/fluxer_api/src/api/channel/tests/AttachmentDecay.test.ts
+++ b/fluxer_api/src/api/channel/tests/AttachmentDecay.test.ts
@@ -10,6 +10,7 @@ import {
loadFixture,
sendMessageWithAttachments,
} from '@app/api/channel/tests/AttachmentTestUtils';
+import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {
getAssetDeletionQueue,
getChannelRepository,
@@ -17,6 +18,8 @@ import {
} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
+import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {getExpiryBucket} from '@app/api/utils/AttachmentDecay';
@@ -28,8 +31,7 @@ import reconcileAttachmentDecay, {
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {MessageReferenceTypes} from '@fluxer/constants/src/ChannelConstants';
-import type {WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface AttachmentDecayRow {
attachment_id: string;
@@ -49,14 +51,17 @@ interface ListedMessage {
describe('Attachment Decay', () => {
let harness: ApiTestHarness;
+ let worker: RecordingWorkerService;
const originalSelfHosted = getConfig().instance.selfHosted;
beforeEach(async () => {
getConfig().instance.selfHosted = true;
harness = await createApiTestHarness();
+ worker = new RecordingWorkerService();
+ setInjectedWorkerService(worker);
});
afterEach(async () => {
getConfig().instance.selfHosted = originalSelfHosted;
- vi.restoreAllMocks();
+ setInjectedWorkerService(new NoopWorkerService());
clearWorkerDependencies();
await harness?.shutdown();
});
@@ -102,19 +107,14 @@ describe('Attachment Decay', () => {
}
async function enableExpiryAndTakeReconcile(admin: TestAccount): Promise<ReconcileAttachmentDecayPayload> {
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
+ const before = worker.byTask('reconcileAttachmentDecay').length;
await setAttachmentExpiry(admin, {enabled: true});
- expect(addJob).toHaveBeenCalledTimes(1);
- const [task, payload, options] = addJob.mock.calls[0] as unknown as [
- string,
- ReconcileAttachmentDecayPayload,
- {jobKey: string},
- ];
- expect(task).toBe('reconcileAttachmentDecay');
+ const jobs = worker.byTask('reconcileAttachmentDecay');
+ expect(jobs).toHaveLength(before + 1);
+ const {payload, options} = jobs[jobs.length - 1]!;
expect(payload).toEqual({runId: expect.any(String), chunk: 0});
expect(options).toEqual({jobKey: `${payload.runId}:0`});
- addJob.mockRestore();
- return payload;
+ return payload as ReconcileAttachmentDecayPayload;
}
async function runReconcile(
@@ -188,27 +188,28 @@ describe('Attachment Decay', () => {
test('should only queue a reconcile when the expiry rules change', async () => {
const admin = await createInstanceAdmin();
await setAttachmentExpiry(admin, {enabled: true, max_lifetime_days: 400});
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
+ const queued = () => worker.byTask('reconcileAttachmentDecay').length;
+ const before = queued();
await setAttachmentExpiry(admin, {enabled: true, max_lifetime_days: 400, renew_window_days: 10});
- expect(addJob).not.toHaveBeenCalled();
+ expect(queued()).toBe(before);
await setAttachmentExpiry(admin, {max_lifetime_days: 200});
- expect(addJob).toHaveBeenCalledTimes(1);
+ expect(queued()).toBe(before + 1);
await setAttachmentExpiry(admin, {enabled: false});
- expect(addJob).toHaveBeenCalledTimes(1);
+ expect(queued()).toBe(before + 1);
});
test('should not queue a reconcile on the hosted instance', async () => {
const admin = await createInstanceAdmin();
await setAttachmentExpiry(admin, {enabled: false});
getConfig().instance.selfHosted = false;
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
+ const before = worker.byTask('reconcileAttachmentDecay').length;
await setAttachmentExpiry(admin, {enabled: true});
await setAttachmentExpiry(admin, {max_lifetime_days: 200});
- expect(addJob).not.toHaveBeenCalled();
+ expect(worker.byTask('reconcileAttachmentDecay')).toHaveLength(before);
expect(await harness.kvProvider.exists('attachment_decay:reconcile_run')).toBe(0);
});
test('should not run a queued reconcile job on the hosted instance', async () => {
@@ -219,11 +220,17 @@ describe('Attachment Decay', () => {
const reconcile = await enableExpiryAndTakeReconcile(admin);
installWorkerDependencies();
getConfig().instance.selfHosted = false;
- const addJob = vi.fn();
+ const queued: Array<string> = [];
+ const helpers = createTestWorkerHelpers({
+ addJob: async (taskType: string) => {
+ queued.push(taskType);
+ return 1n;
+ },
+ });
- await reconcileAttachmentDecay({...reconcile, __jobId: '1'}, {addJob} as unknown as WorkerTaskHelpers);
+ await reconcileAttachmentDecay({...reconcile, __jobId: '1'}, helpers);
- expect(addJob).not.toHaveBeenCalled();
+ expect(queued).toEqual([]);
expect(await fetchDecayRow(upload.attachmentId)).toBeNull();
getConfig().instance.selfHosted = true;
expect(await runReconcile(reconcile)).toBe(1);
@@ -261,11 +268,17 @@ describe('Attachment Decay', () => {
const upload = await uploadWhileExpiryIsOff(admin.token, guild.system_channel_id!, 'queued.png');
const reconcile = await enableExpiryAndTakeReconcile(admin);
installWorkerDependencies();
- const addJob = vi.fn();
+ const queued: Array<string> = [];
+ const helpers = createTestWorkerHelpers({
+ addJob: async (taskType: string) => {
+ queued.push(taskType);
+ return 1n;
+ },
+ });
- await reconcileAttachmentDecay({...reconcile, __jobId: '1'}, {addJob} as unknown as WorkerTaskHelpers);
+ await reconcileAttachmentDecay({...reconcile, __jobId: '1'}, helpers);
- expect(addJob).not.toHaveBeenCalled();
+ expect(queued).toEqual([]);
expect(await fetchDecayRow(upload.attachmentId)).not.toBeNull();
expect(await harness.kvProvider.exists('attachment_decay:reconcile_run')).toBe(0);
});
@@ -275,32 +288,14 @@ describe('Attachment Decay', () => {
await setAttachmentExpiry(admin, {enabled: false});
const upload = await uploadWhileExpiryIsOff(admin.token, guild.system_channel_id!, 'old.png');
const first = await enableExpiryAndTakeReconcile(admin);
- const addJob = vi.spyOn(NoopWorkerService.prototype, 'addJob');
await setAttachmentExpiry(admin, {max_lifetime_days: 200});
- expect(addJob).toHaveBeenCalledTimes(1);
+ expect(worker.byTask('reconcileAttachmentDecay')).toHaveLength(2);
installWorkerDependencies();
expect(await reconcileAttachmentDecayChunk(first)).toBeNull();
expect(await fetchDecayRow(upload.attachmentId)).toBeNull();
});
- test('should read the stored settings instead of a stale cache', async () => {
- const admin = await createInstanceAdmin();
- const guild = await createGuild(harness, admin.token, 'Stale Cache Guild');
- await setAttachmentExpiry(admin, {enabled: false});
- const upload = await uploadWhileExpiryIsOff(admin.token, guild.system_channel_id!, 'stale.png');
- const reconcile = await enableExpiryAndTakeReconcile(admin);
- installWorkerDependencies();
- const current = await getInstanceConfigRepository().getEffectiveAttachmentDecayConfig();
- vi.spyOn(getInstanceConfigRepository(), 'getEffectiveAttachmentDecayConfig').mockResolvedValue({
- ...current,
- enabled: false,
- });
-
- await runReconcile(reconcile);
-
- expect(await fetchDecayRow(upload.attachmentId)).not.toBeNull();
- });
test('should not give a new expiry to an attachment whose file is gone', async () => {
const admin = await createInstanceAdmin();
const guild = await createGuild(harness, admin.token, 'Purged Guild');
diff --git a/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts b/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts
index 698872903..2410a90db 100644
--- a/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts
+++ b/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts
@@ -13,8 +13,7 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {TestMediaService} from '@app/api/test/TestMediaService';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
-import {Logger} from '@fluxer/logger/src/Logger';
-import {beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {beforeAll, beforeEach, describe, expect, it} from 'vitest';
class NullUploadMetadataService extends TestMediaService {
override async getMetadata(request: MediaProxyMetadataRequest) {
@@ -77,7 +76,6 @@ describe('Attachment Upload Validation', () => {
const guild = await createGuild(harness, account.token, 'Storage Unavailable Test Guild');
const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
const channelId = guild.system_channel_id ?? channel.id;
- const errorLoggerSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
harness.storageService.configure({shouldFailUpload: true});
try {
const payload = {
@@ -90,25 +88,8 @@ describe('Attachment Upload Validation', () => {
const body = JSON.parse(text) as {code?: string};
expect(response.status).toBe(HTTP_STATUS.SERVICE_UNAVAILABLE);
expect(body.code).toBe(APIErrorCodes.SERVICE_UNAVAILABLE);
- expect(errorLoggerSpy).toHaveBeenCalledTimes(1);
- expect(errorLoggerSpy).toHaveBeenCalledWith(
- {
- err: expect.objectContaining({
- cause: expect.objectContaining({message: 'Mock storage upload failure'}),
- code: APIErrorCodes.SERVICE_UNAVAILABLE,
- message: 'Attachment storage is temporarily unavailable',
- status: HTTP_STATUS.SERVICE_UNAVAILABLE,
- }),
- method: 'POST',
- path: '/channels/:channel_id/messages',
- requestId: expect.any(String),
- status: HTTP_STATUS.SERVICE_UNAVAILABLE,
- },
- 'Request failed',
- );
} finally {
harness.storageService.configure({shouldFailUpload: false});
- errorLoggerSpy.mockRestore();
}
});
});
diff --git a/fluxer_api/src/api/channel/tests/ChannelCreateCategoryScope.test.ts b/fluxer_api/src/api/channel/tests/ChannelCreateCategoryScope.test.ts
index f839445b0..96aca65cb 100644
--- a/fluxer_api/src/api/channel/tests/ChannelCreateCategoryScope.test.ts
+++ b/fluxer_api/src/api/channel/tests/ChannelCreateCategoryScope.test.ts
@@ -9,13 +9,12 @@ import {
} from '@app/api/channel/tests/ChannelTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {setLimitOverride} from '@app/api/test/LimitTestUtils';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import {afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('Channel create in a category', () => {
let harness: ApiTestHarness;
@@ -25,9 +24,6 @@ describe('Channel create in a category', () => {
beforeEach(async () => {
await harness.reset();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
async function setupCategoryManager(extraAllow = 0n) {
const {owner, members, guild} = await setupTestGuildWithMembers(harness, 1);
@@ -151,43 +147,6 @@ describe('Channel create in a category', () => {
}
});
- it('lets a raised max_channels_per_category admit a channel past the default', async () => {
- const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
- const category = await createChannel(harness, owner.token, guild.id, 'busy', ChannelTypes.GUILD_CATEGORY);
- vi.spyOn(NoopGatewayService.prototype, 'getCategoryChannelCount').mockResolvedValue(50);
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guild.id}/channels`)
- .body({name: 'fifty-first', type: ChannelTypes.GUILD_TEXT, parent_id: category.id})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_CATEGORY_CHANNELS)
- .execute();
- const restore = await setLimitOverride(harness, {max_channels_per_category: 500});
- try {
- const created = await createBuilder<ChannelResponse>(harness, owner.token)
- .post(`/guilds/${guild.id}/channels`)
- .body({name: 'fifty-first', type: ChannelTypes.GUILD_TEXT, parent_id: category.id})
- .execute();
- expect(created.parent_id).toBe(category.id);
- } finally {
- await restore();
- }
- });
-
- it('lets a raised max_guild_channels admit a channel past the default', async () => {
- const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
- vi.spyOn(NoopGatewayService.prototype, 'getChannelCount').mockResolvedValue(500);
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guild.id}/channels`)
- .body({name: 'one-more', type: ChannelTypes.GUILD_TEXT})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_GUILD_CHANNELS)
- .execute();
- const restore = await setLimitOverride(harness, {max_guild_channels: 1000});
- try {
- await createChannel(harness, owner.token, guild.id, 'one-more');
- } finally {
- await restore();
- }
- });
-
it('applies a configured max_channels_per_category when a channel is moved into a category', async () => {
const {owner, guild} = await setupTestGuildWithMembers(harness, 0);
const category = await createChannel(harness, owner.token, guild.id, 'target', ChannelTypes.GUILD_CATEGORY);
@@ -196,20 +155,13 @@ describe('Channel create in a category', () => {
createBuilder(harness, owner.token)
.patch(`/guilds/${guild.id}/channels`)
.body([{id: channel.id, parent_id: category.id}]);
- const restoreLowered = await setLimitOverride(harness, {max_channels_per_category: 0});
+ const restore = await setLimitOverride(harness, {max_channels_per_category: 0});
try {
await move().expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_CATEGORY_CHANNELS).execute();
} finally {
- await restoreLowered();
- }
- vi.spyOn(NoopGatewayService.prototype, 'getCategoryChannelCount').mockResolvedValue(50);
- await move().expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_CATEGORY_CHANNELS).execute();
- const restoreRaised = await setLimitOverride(harness, {max_channels_per_category: 500});
- try {
- await move().expect(HTTP_STATUS.NO_CONTENT).execute();
- } finally {
- await restoreRaised();
+ await restore();
}
+ await move().expect(HTTP_STATUS.NO_CONTENT).execute();
const moved = await createBuilder<ChannelResponse>(harness, owner.token).get(`/channels/${channel.id}`).execute();
expect(moved.parent_id).toBe(category.id);
});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostConcurrency.test.ts b/fluxer_api/src/api/channel/tests/CrosspostConcurrency.test.ts
index 30a91cc35..b2b315b50 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostConcurrency.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostConcurrency.test.ts
@@ -1,74 +1,22 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {MessageRepository} from '@app/api/channel/repositories/MessageRepository';
-import {disableCrosspostWorker} from '@app/api/channel/tests/AnnouncementTestUtils';
import {pinMessage} from '@app/api/channel/tests/ChannelTestUtils';
import {
type AnnouncementWorld,
createAnnouncementWorld,
- createStallGate,
- editMessage,
postMessage,
publish,
- publishedEditBudgetRemaining,
- type RecordedJob,
RecordingWorkerService,
readMessageRow,
} from '@app/api/channel/tests/CrosspostTestUtils';
-import {
- copiesOf,
- deleteMessageRequest,
- editRequest,
- type FanoutWorld,
- followInto,
- sendMessage,
- setupFanoutWorld,
-} from '@app/api/channel/tests/CrosspostWorkerTestUtils';
import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {createWebhook} from '@app/api/webhook/tests/WebhookTestUtils';
-import {
- CROSSPOST_SOURCE_DELETED_CONTENT,
- CROSSPOST_SYNC_COALESCE_MS,
-} from '@fluxer/constants/src/AnnouncementConstants';
import {MessageFlags} from '@fluxer/constants/src/ChannelConstants';
-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-function stallFirstReadOf(messageId: string) {
- const gate = createStallGate();
- const original = MessageRepository.prototype.getMessage;
- let armed = true;
- vi.spyOn(MessageRepository.prototype, 'getMessage').mockImplementation(async function (
- this: MessageRepository,
- channelId,
- id,
- ) {
- const result = await original.call(this, channelId, id);
- if (armed && id.toString() === messageId) {
- armed = false;
- await gate.hit();
- }
- return result;
- });
- return gate;
-}
-
-function expectUpdateSyncJob(job: RecordedJob | undefined, channelId: string, messageId: string): void {
- expect(job?.payload).toEqual({channelId, messageId, mode: 'update'});
- const runAt = job?.options?.runAt;
- expect(runAt).toBeInstanceOf(Date);
- const bucket = Math.floor((runAt!.getTime() - 1000) / CROSSPOST_SYNC_COALESCE_MS) - 1;
- expect(runAt!.getTime()).toBe((bucket + 1) * CROSSPOST_SYNC_COALESCE_MS + 1000);
- expect(job?.options?.jobKey).toBe(`crosspost-sync:${messageId}:update:${bucket}`);
- expect(job?.options?.skipLedger).toBe(true);
-}
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
describe('Publishing races with other message writers', () => {
let harness: ApiTestHarness;
- let worker: RecordingWorkerService;
let world: AnnouncementWorld;
beforeAll(async () => {
@@ -77,106 +25,18 @@ describe('Publishing races with other message writers', () => {
beforeEach(async () => {
await harness.reset();
- worker = new RecordingWorkerService();
- setInjectedWorkerService(worker);
+ setInjectedWorkerService(new RecordingWorkerService());
world = await createAnnouncementWorld(harness);
});
afterEach(() => {
setInjectedWorkerService(new NoopWorkerService());
- vi.restoreAllMocks();
});
afterAll(async () => {
await harness?.shutdown();
});
- test('a stale author edit that sets flags keeps the published flag, counts toward the cap and propagates', async () => {
- const message = await postMessage(harness, world.author.token, world.announcement.id, 'Draft');
- const gate = stallFirstReadOf(message.id);
- const pendingEdit = editMessage(harness, world.author.token, world.announcement.id, message.id, {
- content: 'Edited while publishing',
- flags: MessageFlags.SUPPRESS_EMBEDS,
- })
- .expect(200)
- .execute();
- await gate.reached;
- await publish(harness, world.author.token, world.announcement.id, message.id);
- gate.release();
- const edited = await pendingEdit;
- expect(edited.flags).toBe(MessageFlags.CROSSPOSTED | MessageFlags.SUPPRESS_EMBEDS);
- const row = await readMessageRow(world.announcement.id, message.id);
- expect(row?.flags).toBe(MessageFlags.CROSSPOSTED | MessageFlags.SUPPRESS_EMBEDS);
- expect(row?.content).toBe('Edited while publishing');
- expect(await publishedEditBudgetRemaining(message.id)).toBe(2);
- const syncs = worker.syncJobsFor(message.id);
- expect(syncs).toHaveLength(1);
- expectUpdateSyncJob(syncs[0], world.announcement.id, message.id);
- await editMessage(harness, world.author.token, world.announcement.id, message.id, {content: 'Second edit'})
- .expect(200)
- .execute();
- expect(await publishedEditBudgetRemaining(message.id)).toBe(1);
- expect(worker.syncJobsFor(message.id)).toHaveLength(2);
- await createBuilder(harness, world.author.token)
- .delete(`/channels/${world.announcement.id}/messages/${message.id}`)
- .expect(204)
- .execute();
- const removal = worker.syncJobsFor(message.id).find((job) => job.payload.mode === 'source_deleted');
- expect(removal?.payload).toEqual({
- channelId: world.announcement.id,
- messageId: message.id,
- mode: 'source_deleted',
- });
- expect(removal?.options?.jobKey).toBe(`crosspost-sync:${message.id}:source_deleted`);
- expect(removal?.options?.runAt).toBeUndefined();
- });
-
- test('a stale moderator suppress-embeds edit keeps the published flag without using the cap', async () => {
- const message = await postMessage(harness, world.author.token, world.announcement.id, 'See https://example.com');
- const gate = stallFirstReadOf(message.id);
- const pendingEdit = editMessage(harness, world.mod.token, world.announcement.id, message.id, {
- flags: MessageFlags.SUPPRESS_EMBEDS,
- })
- .expect(200)
- .execute();
- await gate.reached;
- await publish(harness, world.author.token, world.announcement.id, message.id);
- gate.release();
- const edited = await pendingEdit;
- expect(edited.flags).toBe(MessageFlags.CROSSPOSTED | MessageFlags.SUPPRESS_EMBEDS);
- expect((await readMessageRow(world.announcement.id, message.id))?.flags).toBe(
- MessageFlags.CROSSPOSTED | MessageFlags.SUPPRESS_EMBEDS,
- );
- expect(await publishedEditBudgetRemaining(message.id)).toBe(3);
- const syncs = worker.syncJobsFor(message.id);
- expect(syncs).toHaveLength(1);
- expectUpdateSyncJob(syncs[0], world.announcement.id, message.id);
- });
-
- test('a stale webhook token edit keeps the published flag and counts toward the cap', async () => {
- const webhook = await createWebhook(harness, world.announcement.id, world.owner.token, 'Release Bot');
- const executed = await createBuilderWithoutAuth<MessageResponse>(harness)
- .post(`/webhooks/${webhook.id}/${webhook.token}?wait=true`)
- .body({content: 'Build 42 shipped'})
- .expect(200)
- .execute();
- const gate = stallFirstReadOf(executed.id);
- const pendingEdit = createBuilderWithoutAuth<MessageResponse>(harness)
- .patch(`/webhooks/${webhook.id}/${webhook.token}/messages/${executed.id}`)
- .body({content: 'Build 42 shipped (edited)', flags: MessageFlags.SUPPRESS_EMBEDS})
- .expect(200)
- .execute();
- await gate.reached;
- await publish(harness, world.mod.token, world.announcement.id, executed.id);
- gate.release();
- await pendingEdit;
- const row = await readMessageRow(world.announcement.id, executed.id);
- expect(row?.flags).toBe(MessageFlags.CROSSPOSTED | MessageFlags.SUPPRESS_EMBEDS);
- expect(row?.content).toBe('Build 42 shipped (edited)');
- expect(await publishedEditBudgetRemaining(executed.id)).toBe(2);
- expect(worker.syncJobsFor(executed.id)).toHaveLength(1);
- });
-
test('a pin concurrent with a publish keeps both', async () => {
const message = await postMessage(harness, world.author.token, world.announcement.id, 'Pin and publish');
await Promise.all([
@@ -188,58 +48,3 @@ describe('Publishing races with other message writers', () => {
expect(row?.pinnedTimestamp).not.toBeNull();
});
});
-
-describe('Publishing races with a follower attached', () => {
- let harness: ApiTestHarness;
- let world: FanoutWorld;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- world = await setupFanoutWorld(harness);
- });
-
- afterEach(() => {
- disableCrosspostWorker();
- vi.restoreAllMocks();
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- test('a stale flag edit during a publish reaches the copy and a later delete marks it', async () => {
- await followInto(harness, world, world.b.t1.id);
- const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'Draft'});
- const gate = stallFirstReadOf(message.id);
- const pendingEdit = editRequest(harness, world.a.owner.token, world.a.ann.id, message.id, {
- content: 'Edited while publishing',
- flags: MessageFlags.SUPPRESS_EMBEDS,
- })
- .expect(200)
- .execute();
- await gate.reached;
- await publish(harness, world.a.owner.token, world.a.ann.id, message.id);
- gate.release();
- await pendingEdit;
- await world.worker.drain();
- let [copy] = await copiesOf(harness, world.b.owner.token, world.b.t1.id, message.id);
- expect(copy!.content).toBe('Edited while publishing');
- expect(copy!.flags).toBe(MessageFlags.IS_CROSSPOST | MessageFlags.SUPPRESS_EMBEDS);
- await editRequest(harness, world.a.owner.token, world.a.ann.id, message.id, {content: 'Second edit'})
- .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('Second edit');
- 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).toBe(MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED);
- expect(copy!.content).toBe(CROSSPOST_SOURCE_DELETED_CONTENT);
- expect(world.worker.deadLetters).toHaveLength(0);
- });
-});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts b/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts
index cdbba6925..a5ee348dd 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts
@@ -18,28 +18,19 @@ import {
import {loadFixture, sendMessageWithAttachments} from '@app/api/channel/tests/AttachmentTestUtils';
import {sendChannelMessage} from '@app/api/channel/tests/ChannelTestUtils';
import {readMessageRow, writeMessageRow} from '@app/api/channel/tests/CrosspostTestUtils';
-import type {MessageEmbed} from '@app/api/database/types/MessageTypes';
-import type {EmbedService} from '@app/api/infrastructure/EmbedService';
import {
getGatewayService,
getKVClient,
getSnowflakeService,
setInjectedWorkerService,
} from '@app/api/middleware/ServiceRegistry';
-import {
- getCacheService,
- getChannelRepository,
- getPurgeQueue,
- getStorageService,
-} from '@app/api/middleware/ServiceSingletons';
-import {urlBlocklistCache} from '@app/api/middleware/UrlBlocklistCache';
+import {getChannelRepository, getPurgeQueue, getStorageService} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {createTestWorkerHelpers, SyncTaskWorkerService} from '@app/api/test/SyncTaskWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {createWebhook, executeWebhook} from '@app/api/webhook/tests/WebhookTestUtils';
-import extractEmbeds from '@app/api/worker/tasks/ExtractEmbeds';
import messageShred from '@app/api/worker/tasks/MessageShred';
import {
clearWorkerDependencies,
@@ -54,7 +45,6 @@ import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageRe
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
const SERVER_BITS = MessageFlags.CROSSPOSTED | MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED;
-const BLOCKED_DOMAIN = 'crosspost-blocked.example';
async function fabricateCopy(params: {
harness: ApiTestHarness;
@@ -102,14 +92,6 @@ async function adminDeleteMessage(harness: ApiTestHarness, admin: TestAccount, c
.execute();
}
-function blockedEmbedService(): EmbedService {
- return {
- processUrlWithCachePolicy: async (url: string) => ({
- embeds: [{toMessageEmbed: (): MessageEmbed => ({type: 'link', url}) as MessageEmbed}],
- }),
- } as unknown as EmbedService;
-}
-
async function listCopies(channelId: string, sourceId: string): Promise<Array<string>> {
const messages = await new ChannelRepository().messages.listMessages(
createChannelID(BigInt(channelId)),
@@ -144,7 +126,6 @@ describe('Crosspost moderation', () => {
afterEach(() => {
clearWorkerDependencies();
- urlBlocklistCache.removeDomain(BLOCKED_DOMAIN);
});
afterAll(async () => {
@@ -157,30 +138,6 @@ describe('Crosspost moderation', () => {
}
describe('takedown hooks', () => {
- test('an admin delete of a copy enqueues a purge of the whole family', async () => {
- const source = await sendChannelMessage(harness, world.a.member.token, world.a.ann.id, 'update');
- const {copyId} = await fabricateCopy({
- harness,
- owner: world.b.owner,
- target: world.b.t1.id,
- world,
- sourceId: source.id,
- });
- const admin = await createAdmin(harness);
- await adminDeleteMessage(harness, admin, world.b.t1.id, copyId);
- expect(await readMessageRow(world.b.t1.id, copyId)).toBeNull();
- const jobs = worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE);
- expect(jobs).toHaveLength(1);
- expect(jobs[0]!.payload).toEqual({
- channelId: world.a.ann.id,
- messageId: source.id,
- mode: 'purge',
- deleteSource: true,
- });
- expect(jobs[0]!.options?.jobKey).toBe(`crosspost-sync:${source.id}:purge`);
- expect(jobs[0]!.options?.skipLedger).toBe(true);
- });
-
test('an admin delete of a published source purges its copies and leaves others alone', async () => {
const source = await sendChannelMessage(harness, world.a.member.token, world.a.ann.id, 'update');
await publish(harness, world.a.member.token, world.a.ann.id, source.id);
@@ -227,36 +184,6 @@ describe('Crosspost moderation', () => {
expect(jobs).toHaveLength(1);
expect(jobs[0]!.payload).toEqual({channelId: world.a.ann.id, messageId: source.id, mode: 'purge'});
});
-
- test('a blocked unfurl on a published source deletes it and purges its copies', async () => {
- const source = await sendChannelMessage(
- harness,
- world.a.member.token,
- world.a.ann.id,
- `see https://${BLOCKED_DOMAIN}/page`,
- );
- await publish(harness, world.a.member.token, world.a.ann.id, source.id);
- urlBlocklistCache.addDomain(BLOCKED_DOMAIN);
- worker.clear();
- setWorkerDependenciesForTest({
- channelRepository: getChannelRepository(),
- gatewayService: getGatewayService(),
- embedService: blockedEmbedService(),
- cacheService: getCacheService(),
- workerService: worker,
- });
- await extractEmbeds(
- {channelId: world.a.ann.id, messageId: source.id, guildId: world.a.guild.id, nsfwMode: 'allow'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => worker.addJob(taskType, payload, options),
- }),
- );
- expect(await readMessageRow(world.a.ann.id, source.id)).toBeNull();
- const jobs = worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE);
- expect(jobs).toHaveLength(1);
- expect(jobs[0]!.payload).toEqual({channelId: world.a.ann.id, messageId: source.id, mode: 'purge'});
- });
});
describe('forwarding', () => {
@@ -388,25 +315,5 @@ describe('Crosspost moderation', () => {
expect(harness.storageService.hasObject(Config.s3.buckets.cdn, sourceKey)).toBe(false);
expectNoTargetObjectsDeleted();
});
-
- test('a blocked unfurl of a published source deletes every copy', async () => {
- const sourceId = await publishAndDeliver(`see https://${BLOCKED_DOMAIN}/page`);
- expect(await listCopies(c.t1.id, sourceId)).toHaveLength(1);
- urlBlocklistCache.addDomain(BLOCKED_DOMAIN);
- const deps = await initializeWorkerDependencies(getSnowflakeService());
- deps.workerService = worker;
- deps.embedService = blockedEmbedService();
- setWorkerDependencies(deps);
- await extractEmbeds(
- {channelId: world.a.ann.id, messageId: sourceId, guildId: world.a.guild.id, nsfwMode: 'allow'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => worker.addJob(taskType, payload, options),
- }),
- );
- expect(await worker.drain()).toMatchObject({remaining: 0});
- expect(worker.deadLetters).toEqual([]);
- await expectFamilyGone(sourceId);
- });
});
});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostPropagation.test.ts b/fluxer_api/src/api/channel/tests/CrosspostPropagation.test.ts
index ce65fffef..73f942e6f 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostPropagation.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostPropagation.test.ts
@@ -1,6 +1,5 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {AttachmentDecayRepository} from '@app/api/attachment/AttachmentDecayRepository';
import {setUserACLs} from '@app/api/auth/tests/AuthTestUtils';
import {createChannelID, createMessageID, createUserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
@@ -33,20 +32,12 @@ import {
} from '@app/api/channel/tests/CrosspostWorkerTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
-import type {EmbedService} from '@app/api/infrastructure/EmbedService';
-import type {IAssetDeletionQueue} from '@app/api/infrastructure/IAssetDeletionQueue';
-import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
import {getKVClient} from '@app/api/middleware/ServiceRegistry';
-import type {Embed} from '@app/api/models/Embed';
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, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
-import {getExpiryBucket} from '@app/api/utils/AttachmentDecay';
import {createWebhook, executeWebhook} from '@app/api/webhook/tests/WebhookTestUtils';
import deleteUserMessagesInGuildByTime from '@app/api/worker/tasks/DeleteUserMessagesInGuildByTime';
-import {processExpiredAttachments} from '@app/api/worker/tasks/ExpireAttachments';
-import extractEmbeds from '@app/api/worker/tasks/ExtractEmbeds';
import messageShred from '@app/api/worker/tasks/MessageShred';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {
@@ -62,17 +53,10 @@ import {
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import {ServerMessageFlags} from '@fluxer/constants/src/ThreadConstants';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
const DELETED_COPY_FLAGS = MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED;
-async function awaitFreshBucket(): Promise<void> {
- const intoBucket = Date.now() % CROSSPOST_SYNC_COALESCE_MS;
- if (intoBucket > CROSSPOST_SYNC_COALESCE_MS - 2000) {
- await new Promise((resolve) => setTimeout(resolve, CROSSPOST_SYNC_COALESCE_MS - intoBucket + 50));
- }
-}
-
describe('Crosspost propagation', () => {
let harness: ApiTestHarness;
let world: FanoutWorld;
@@ -90,7 +74,6 @@ describe('Crosspost propagation', () => {
afterEach(() => {
disableCrosspostWorker();
clearChannelThreadsTaintCacheForTesting();
- vi.restoreAllMocks();
});
afterAll(async () => {
@@ -123,7 +106,6 @@ describe('Crosspost propagation', () => {
const source = await postAndPublish(harness, world, {content: 'draft'});
const copyT1 = await onlyCopy(world.b.t1.id, source.id);
const copyT2 = await onlyCopy(world.b.t2.id, source.id);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
const before = crosspostSyncBucket(Date.now());
await edit(source.id, {content: 'final'});
const after = crosspostSyncBucket(Date.now());
@@ -142,35 +124,12 @@ describe('Crosspost propagation', () => {
[world.b.t2.id, copyT2.id],
] as const) {
const updated = await onlyCopy(channelId, source.id);
+ expect(updated.id).toBe(copyId);
expect(updated.content).toBe('final');
expect(updated.edited_timestamp).toBeTruthy();
- const updates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter(
- (params) =>
- params.event === 'MESSAGE_UPDATE' &&
- params.guildId.toString() === world.b.guild.id &&
- (params.data as {id: string}).id === copyId,
- );
- expect(updates).toHaveLength(1);
}
});
- test('two edits in one bucket run a single sync and the copy ends with the second', async () => {
- await followInto(harness, world, world.b.t1.id);
- const source = await postAndPublish(harness, world, {content: 'first'});
- await awaitFreshBucket();
- await edit(source.id, {content: 'second'});
- await edit(source.id, {content: 'third'});
- const syncJobs = world.worker
- .byTask('syncCrosspostedMessage')
- .filter((entry) => (entry.payload as {messageId: string}).messageId === source.id);
- expect(syncJobs).toHaveLength(1);
- expect(world.worker.deduped.filter((entry) => entry.taskType === 'syncCrosspostedMessage')).toHaveLength(1);
- await world.worker.drain();
- expect((await onlyCopy(world.b.t1.id, source.id)).content).toBe('third');
- });
-
test('embed edits and suppress-embeds toggles propagate, including flag-only edits', async () => {
await followInto(harness, world, world.b.t1.id);
const embedded = await postAndPublish(harness, world, {content: 'card', embeds: [{title: 'Old title'}]});
@@ -187,7 +146,6 @@ describe('Crosspost propagation', () => {
copyRow = (await readRow(world.b.t1.id, copyRow.id.toString()))!;
expect(copyRow.flags).toBe(MessageFlags.IS_CROSSPOST);
const plain = await postAndPublish(harness, world, {content: 'plain'});
- await awaitFreshBucket();
await edit(plain.id, {content: 'plain edited'});
await world.worker.drain();
const plainCopy = await onlyCopy(world.b.t1.id, plain.id);
@@ -292,54 +250,11 @@ describe('Crosspost propagation', () => {
expect(harness.storageService.getCopiedObjects()).toHaveLength(copiedBefore);
});
- test('a late unfurl on a published source propagates its embeds', async () => {
- await followInto(harness, world, world.b.t1.id);
- const source = await postAndPublish(harness, world, {content: 'read https://example.com/post'});
- const embedService = {
- processUrlWithCachePolicy: async (url: string) => ({
- embeds: [
- {
- toMessageEmbed: () => ({
- type: 'link',
- url,
- title: 'Example post',
- description: null,
- timestamp: null,
- color: null,
- author: null,
- provider: null,
- thumbnail: null,
- image: null,
- video: null,
- footer: null,
- fields: null,
- nsfw: null,
- }),
- } as unknown as Embed,
- ],
- }),
- } as unknown as EmbedService;
- disableCrosspostWorker();
- world.worker = enableCrosspostWorker({}, {embedService});
- await extractEmbeds(
- {channelId: world.a.ann.id, messageId: source.id, guildId: world.a.guild.id, nsfwMode: 'allow'},
- createTestWorkerHelpers({
- jobId: 0n,
- addJob: (taskType, payload, options) => world.worker.addJob(taskType, payload, options),
- }),
- );
- expect(world.worker.byTask('syncCrosspostedMessage')).toHaveLength(1);
- await world.worker.drain();
- const copyRow = (await readRow(world.b.t1.id, (await onlyCopy(world.b.t1.id, source.id)).id))!;
- expect(copyRow.embeds.map((embed) => embed.title)).toEqual(['Example post']);
- });
-
test('a sync with nothing new writes nothing', async () => {
await followInto(harness, world, world.b.t1.id);
const source = await postAndPublish(harness, world, {content: 'steady'});
const copy = await onlyCopy(world.b.t1.id, source.id);
const before = await readRow(world.b.t1.id, copy.id);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await enqueueCrosspostSync(world.worker, {
channelId: createChannelID(BigInt(world.a.ann.id)),
messageId: createMessageID(BigInt(source.id)),
@@ -347,7 +262,6 @@ describe('Crosspost propagation', () => {
});
await world.worker.drain();
expect((await readRow(world.b.t1.id, copy.id))?.version).toBe(before?.version);
- expect(dispatchSpy.mock.calls.filter(([params]) => params.event === 'MESSAGE_UPDATE')).toHaveLength(0);
});
test('deleting the source marks every copy and cleans up the mapping and index rows', async () => {
@@ -475,7 +389,6 @@ describe('Crosspost propagation', () => {
await followInto(harness, world, world.b.t1.id);
const source = await postAndPublish(harness, world, {content: 'illegal'});
const copy = await onlyCopy(world.b.t1.id, source.id);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
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/${source.id}`)
@@ -485,14 +398,6 @@ describe('Crosspost propagation', () => {
await world.worker.drain();
expect(await readRow(world.b.t1.id, copy.id)).toBeNull();
expect(await listCopies(harness, world.b.owner.token, world.b.t1.id)).toHaveLength(0);
- expect(
- dispatchSpy.mock.calls.some(
- ([params]) =>
- params.event === 'MESSAGE_DELETE' &&
- params.guildId.toString() === world.b.guild.id &&
- (params.data as {id: string}).id === copy.id,
- ),
- ).toBe(true);
expect(await mappingRows(source.id)).toHaveLength(0);
});
@@ -702,43 +607,6 @@ describe('Crosspost propagation', () => {
expect(harness.storageService.hasObject(Config.s3.buckets.cdn, droppedKey)).toBe(false);
});
- test('a copy owns no decay record and its expiry purges only the source file', async () => {
- const queued: Array<{s3Key: string}> = [];
- disableCrosspostWorker();
- world.worker = enableCrosspostWorker(
- {},
- {
- assetDeletionQueue: {
- async queueDeletion(item: {s3Key: string}) {
- queued.push(item);
- },
- } as unknown as IAssetDeletionQueue,
- kvClient: harness.kvProvider,
- instanceConfigRepository: {
- async getEffectiveAttachmentDecayConfig() {
- return {enabled: true};
- },
- } as unknown as InstanceConfigRepository,
- },
- );
- await followInto(harness, world, world.b.t1.id);
- const source = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'decaying'});
- await publishAndDrain(harness, world, source.id);
- const [attachment] = (await readRow(world.a.ann.id, source.id))!.attachments;
- const copy = await onlyCopy(world.b.t1.id, source.id);
- await createBuilder(harness, world.b.owner.token).get(`/channels/${world.b.t1.id}/messages/${copy.id}`).execute();
- const repository = new AttachmentDecayRepository();
- const record = await repository.fetchById(attachment!.id);
- expect(record?.channel_id.toString()).toBe(world.a.ann.id);
- expect(record?.message_id.toString()).toBe(source.id);
- const expiresAt = new Date(Date.now() - 60_000);
- await repository.upsert({...record!, expires_at: expiresAt, expiry_bucket: getExpiryBucket(expiresAt)});
- await processExpiredAttachments();
- expect(queued.map((item) => item.s3Key)).toEqual([
- `attachments/${world.a.ann.id}/${attachment!.id}/${attachment!.filename}`,
- ]);
- });
-
test('a copy deleted in the target is cleaned up lazily on the next edit', async () => {
const webhookId = await followInto(harness, world, world.b.t1.id);
const source = await postAndPublish(harness, world, {content: 'moderated'});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts b/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts
index 9a3ece5f5..3a3ffdd4e 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostSource.test.ts
@@ -15,7 +15,6 @@ import {
import {ensureSessionStarted, getMessages} from '@app/api/message/tests/MessageTestUtils';
import {getGuildDiscoveryRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
@@ -24,7 +23,7 @@ import {DiscoveryApplicationStatus, DiscoveryCategories} from '@fluxer/constants
import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
import type {CrosspostSourceResponse} from '@fluxer/schema/src/domains/message/CrosspostSourceSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
describe('Crosspost source', () => {
let harness: ApiTestHarness;
@@ -45,7 +44,6 @@ describe('Crosspost source', () => {
afterEach(() => {
disableCrosspostWorker();
- vi.restoreAllMocks();
});
afterAll(async () => {
@@ -77,10 +75,6 @@ describe('Crosspost source', () => {
test('returns the source community card to a viewer who is not a member of it', async () => {
const copy = await publishedCopy();
- vi.spyOn(NoopGatewayService.prototype, 'getGuildCounts').mockResolvedValue({
- memberCount: 1234,
- presenceCount: 56,
- });
const response = await getSource(outsider.token, world.b.t1.id, copy.id).execute();
expect(response).toEqual({
guild: {
@@ -90,8 +84,8 @@ describe('Crosspost source', () => {
banner: null,
description: null,
features: [],
- approximate_member_count: 1234,
- approximate_presence_count: 56,
+ approximate_member_count: 5,
+ approximate_presence_count: 0,
discoverable: false,
},
});
@@ -153,15 +147,6 @@ describe('Crosspost source', () => {
expect([...response.guild.features].sort()).toEqual([GuildFeatures.PARTNERED, GuildFeatures.VERIFIED].sort());
});
- test('returns null counts when the gateway cannot provide them', async () => {
- const copy = await publishedCopy();
- vi.spyOn(NoopGatewayService.prototype, 'getGuildCounts').mockRejectedValue(new Error('gateway down'));
- const response = await getSource(outsider.token, world.b.t1.id, copy.id).execute();
- expect(response.guild.approximate_member_count).toBeNull();
- expect(response.guild.approximate_presence_count).toBeNull();
- expect(response.guild.name).toBe(world.a.guild.name);
- });
-
test('accepts the follow system message', async () => {
await followInto(harness, world, world.b.t1.id);
const notice = await followNotice();
diff --git a/fluxer_api/src/api/channel/tests/CrosspostTestUtils.ts b/fluxer_api/src/api/channel/tests/CrosspostTestUtils.ts
index 91a61c05f..615df6335 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostTestUtils.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostTestUtils.ts
@@ -1,13 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-export {type RecordedJob, RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
+export {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createChannelID, createGuildID, createMessageID} from '@app/api/BrandedTypes';
import {createApiContext} from '@app/api/CreateApiContext';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
import type {ChannelService} from '@app/api/channel/services/ChannelService';
-import {publishedEditRateLimitIdentifier} from '@app/api/channel/services/message/CrosspostPropagation';
import {crosspostChannelRateLimitIdentifier} from '@app/api/channel/services/message/MessageCrosspostService';
import {
acceptInvite,
@@ -48,10 +47,7 @@ import {
import type {Message} from '@app/api/models/Message';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {
- CROSSPOST_CHANNEL_RATE_LIMIT,
- PUBLISHED_MESSAGE_EDIT_RATE_LIMIT,
-} from '@fluxer/constants/src/AnnouncementConstants';
+import {CROSSPOST_CHANNEL_RATE_LIMIT} from '@fluxer/constants/src/AnnouncementConstants';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
@@ -158,38 +154,6 @@ export async function channelBudgetRemaining(channelId: string): Promise<number>
return result.remaining;
}
-export async function publishedEditBudgetRemaining(messageId: string): Promise<number> {
- const result = await getRateLimitService().peekLimit({
- identifier: publishedEditRateLimitIdentifier(createMessageID(BigInt(messageId))),
- ...PUBLISHED_MESSAGE_EDIT_RATE_LIMIT,
- });
- return result.remaining;
-}
-
-export interface StallGate {
- reached: Promise<void>;
- release: () => void;
-}
-
-export function createStallGate(): StallGate & {hit: () => Promise<void>} {
- let markReached: () => void = () => {};
- let release: () => void = () => {};
- const reached = new Promise<void>((resolve) => {
- markReached = resolve;
- });
- const released = new Promise<void>((resolve) => {
- release = resolve;
- });
- return {
- reached,
- release,
- hit: async () => {
- markReached();
- await released;
- },
- };
-}
-
export function createTestGuildStack(): GuildStackServices {
return createGuildStackServices({
apiContext: createApiContext(),
diff --git a/fluxer_api/src/api/channel/tests/ForumChannels.test.ts b/fluxer_api/src/api/channel/tests/ForumChannels.test.ts
index 8a9d9c64b..5d88a3f9c 100644
--- a/fluxer_api/src/api/channel/tests/ForumChannels.test.ts
+++ b/fluxer_api/src/api/channel/tests/ForumChannels.test.ts
@@ -18,7 +18,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
import type {StartForumThreadResponse} from '@fluxer/schema/src/domains/channel/ForumRequestSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
diff --git a/fluxer_api/src/api/channel/tests/GroupDmMatureContent.test.ts b/fluxer_api/src/api/channel/tests/GroupDmMatureContent.test.ts
index 215674a26..d5703e9a4 100644
--- a/fluxer_api/src/api/channel/tests/GroupDmMatureContent.test.ts
+++ b/fluxer_api/src/api/channel/tests/GroupDmMatureContent.test.ts
@@ -1,15 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {MessageContentService} from '@app/api/channel/services/message/MessageContentService';
import {createChannelInvite, createFriendship, createGroupDmChannel} from '@app/api/channel/tests/ChannelTestUtils';
-import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
+import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('group dm mature content', () => {
let harness: ApiTestHarness;
@@ -22,10 +21,6 @@ describe('group dm mature content', () => {
await harness.reset();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
await harness.shutdown();
});
@@ -55,15 +50,10 @@ describe('group dm mature content', () => {
.execute();
}
- it('lets the owner mark the group and allows mature media once marked', async () => {
+ it('lets the owner mark and clear the group', async () => {
const s = await setup();
- const scope = vi.spyOn(MessageContentService.prototype, 'isNSFWContentAllowed');
- await sendMessage(harness, s.owner.token, s.groupId, 'before');
- expect(scope.mock.results.at(-1)?.value).toBe(false);
const updated = await setNsfw(s.owner, s.groupId, true);
expect(updated.nsfw).toBe(true);
- await sendMessage(harness, s.owner.token, s.groupId, 'after');
- expect(scope.mock.results.at(-1)?.value).toBe(true);
const cleared = await setNsfw(s.owner, s.groupId, false);
expect(cleared.nsfw).toBe(false);
});
diff --git a/fluxer_api/src/api/channel/tests/GroupDmRecipientRemoveCall.test.ts b/fluxer_api/src/api/channel/tests/GroupDmRecipientRemoveCall.test.ts
deleted file mode 100644
index 987b4e8d3..000000000
--- a/fluxer_api/src/api/channel/tests/GroupDmRecipientRemoveCall.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {
- createFriendship,
- createGroupDmChannel,
- getChannel,
- removeRecipientFromGroupDm,
-} from '@app/api/channel/tests/ChannelTestUtils';
-import {DisabledLiveKitService} from '@app/api/infrastructure/DisabledLiveKitService';
-import {InMemoryVoiceRoomStore} from '@app/api/infrastructure/InMemoryVoiceRoomStore';
-import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-describe('Group DM recipient removal call teardown', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterEach(() => {
- vi.restoreAllMocks();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- async function setupGroupDm() {
- const owner = await createTestAccount(harness);
- const member = await createTestAccount(harness);
- const other = await createTestAccount(harness);
- await ensureSessionStarted(harness, owner.token);
- await ensureSessionStarted(harness, member.token);
- await ensureSessionStarted(harness, other.token);
- await createFriendship(harness, owner, member);
- await createFriendship(harness, owner, other);
- const groupDm = await createGroupDmChannel(harness, owner.token, [member.userId, other.userId]);
- return {owner, member, other, groupDm};
- }
-
- it('disconnects the removed recipient from the call and the voice room', async () => {
- const {owner, member, other, groupDm} = await setupGroupDm();
- vi.spyOn(NoopGatewayService.prototype, 'getVoiceStatesForChannel').mockResolvedValue({
- voiceStates: [
- {connectionId: 'member-conn', userId: member.userId, channelId: groupDm.id},
- {connectionId: 'other-conn', userId: other.userId, channelId: groupDm.id},
- ],
- });
- vi.spyOn(InMemoryVoiceRoomStore.prototype, 'getPinnedRoomServer').mockResolvedValue({
- regionId: 'region-a',
- serverId: 'server-a',
- endpoint: 'wss://voice.invalid',
- });
- const disconnectFromCall = vi.spyOn(NoopGatewayService.prototype, 'disconnectVoiceUserIfInChannel');
- const disconnectParticipant = vi.spyOn(DisabledLiveKitService.prototype, 'disconnectParticipant');
-
- await removeRecipientFromGroupDm(harness, owner.token, groupDm.id, member.userId);
-
- expect(disconnectFromCall).toHaveBeenCalledTimes(1);
- const callParams = disconnectFromCall.mock.calls[0]![0];
- expect(callParams.guildId).toBeUndefined();
- expect(callParams.channelId.toString()).toBe(groupDm.id);
- expect(callParams.userId.toString()).toBe(member.userId);
- expect(disconnectParticipant).toHaveBeenCalledTimes(1);
- const participantParams = disconnectParticipant.mock.calls[0]![0];
- expect(participantParams.userId.toString()).toBe(member.userId);
- expect(participantParams.channelId.toString()).toBe(groupDm.id);
- expect(participantParams.connectionId).toBe('member-conn');
- expect(participantParams.regionId).toBe('region-a');
- expect(participantParams.serverId).toBe('server-a');
- });
-
- it('disconnects a recipient who leaves the group DM themselves', async () => {
- const {member, groupDm} = await setupGroupDm();
- const disconnectFromCall = vi.spyOn(NoopGatewayService.prototype, 'disconnectVoiceUserIfInChannel');
-
- await removeRecipientFromGroupDm(harness, member.token, groupDm.id, member.userId);
-
- expect(disconnectFromCall).toHaveBeenCalledTimes(1);
- expect(disconnectFromCall.mock.calls[0]![0].userId.toString()).toBe(member.userId);
- });
-
- it('still removes the recipient when the call teardown fails', async () => {
- const {owner, member, groupDm} = await setupGroupDm();
- vi.spyOn(NoopGatewayService.prototype, 'disconnectVoiceUserIfInChannel').mockRejectedValue(
- new Error('gateway unavailable'),
- );
-
- await removeRecipientFromGroupDm(harness, owner.token, groupDm.id, member.userId);
-
- const channel = await getChannel(harness, owner.token, groupDm.id);
- expect(channel.recipients?.map((recipient) => recipient.id)).not.toContain(member.userId);
- });
-});
diff --git a/fluxer_api/src/api/channel/tests/HiddenAuthorMessageDelivery.test.ts b/fluxer_api/src/api/channel/tests/HiddenAuthorMessageDelivery.test.ts
deleted file mode 100644
index a73881611..000000000
--- a/fluxer_api/src/api/channel/tests/HiddenAuthorMessageDelivery.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createUserID} from '@app/api/BrandedTypes';
-import {setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
-import {sendMessage} from '@app/api/message/tests/MessageTestUtils';
-import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
-
-describe('messages from an author inside a hide window', () => {
- let harness: ApiTestHarness;
- let author: TestAccount;
- let channelId: string;
-
- beforeEach(async () => {
- harness = await createApiTestHarness();
- const setup = await setupTestGuildWithMembers(harness, 1);
- author = setup.members[0]!;
- channelId = setup.channels[0]!.id;
- vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
- });
-
- afterEach(async () => {
- vi.restoreAllMocks();
- await harness?.shutdown();
- });
-
- async function setHiddenSince(since: Date | null): Promise<void> {
- await getUserRepository().patchUpsert(createUserID(BigInt(author.userId)), {content_hidden_since: since});
- }
-
- function createEvents(messageId: string) {
- const guild = vi
- .mocked(NoopGatewayService.prototype.dispatchGuild)
- .mock.calls.filter(([call]) => call.event === 'MESSAGE_CREATE' && (call.data as {id: string}).id === messageId);
- const presence = vi
- .mocked(NoopGatewayService.prototype.dispatchPresence)
- .mock.calls.filter(([call]) => call.event === 'MESSAGE_CREATE' && (call.data as {id: string}).id === messageId);
- return {guild, presence: presence.map(([call]) => call.userId.toString())};
- }
-
- test('reach only the author and fan out again once the window is cleared', async () => {
- await setHiddenSince(new Date(Date.now() - 60_000));
- const hidden = await sendMessage(harness, author.token, channelId, 'inside the window');
- expect(hidden.content).toBe('inside the window');
- expect(createEvents(hidden.id)).toEqual({guild: [], presence: [author.userId]});
-
- await setHiddenSince(null);
- const shown = await sendMessage(harness, author.token, channelId, 'after restore');
- const events = createEvents(shown.id);
- expect(events.guild).toHaveLength(1);
- expect(events.presence).toEqual([]);
- });
-
- test('a window that starts later leaves current messages alone', async () => {
- await setHiddenSince(new Date(Date.now() + 3_600_000));
- const message = await sendMessage(harness, author.token, channelId, 'before the window');
- expect(createEvents(message.id).guild).toHaveLength(1);
- });
-});
diff --git a/fluxer_api/src/api/channel/tests/MessageCrosspost.test.ts b/fluxer_api/src/api/channel/tests/MessageCrosspost.test.ts
index c1f541ac9..fed958844 100644
--- a/fluxer_api/src/api/channel/tests/MessageCrosspost.test.ts
+++ b/fluxer_api/src/api/channel/tests/MessageCrosspost.test.ts
@@ -24,14 +24,12 @@ import {
readMessageRow,
writeMessageRow,
} from '@app/api/channel/tests/CrosspostTestUtils';
-import {Logger} from '@app/api/Logger';
import {getMessages} from '@app/api/message/tests/MessageTestUtils';
import {fileShaCache} from '@app/api/middleware/FileShaCache';
import {phraseBlocklistCache} from '@app/api/middleware/PhraseBlocklistCache';
import {getSnowflakeService, setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import type {MockSnowflakeService} from '@app/api/test/mocks/MockSnowflakeService';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {createWebhook} from '@app/api/webhook/tests/WebhookTestUtils';
@@ -42,7 +40,7 @@ import {ChannelTypes, MessageFlags, MessageTypes, Permissions} from '@fluxer/con
import {GuildFeatures, GuildOperations} from '@fluxer/constants/src/GuildConstants';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
const SERVER_BITS = MessageFlags.CROSSPOSTED | MessageFlags.IS_CROSSPOST | MessageFlags.SOURCE_MESSAGE_DELETED;
@@ -65,7 +63,6 @@ describe('Publishing messages in announcement channels', () => {
afterEach(() => {
setInjectedWorkerService(new NoopWorkerService());
phraseBlocklistCache.remove('forbiddenword');
- vi.restoreAllMocks();
});
afterAll(async () => {
@@ -74,8 +71,6 @@ describe('Publishing messages in announcement channels', () => {
test('the author publishes their own message', async () => {
const message = await postMessage(harness, world.author.token, world.announcement.id, 'Release 1.0 is out');
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const infoSpy = vi.spyOn(Logger.child({}), 'info');
const published = await publish(harness, world.author.token, world.announcement.id, message.id);
expect(published.id).toBe(message.id);
expect(published.flags & MessageFlags.CROSSPOSTED).toBe(MessageFlags.CROSSPOSTED);
@@ -83,20 +78,6 @@ describe('Publishing messages in announcement channels', () => {
const row = await readMessageRow(world.announcement.id, message.id);
expect(row?.flags).toBe(MessageFlags.CROSSPOSTED);
expect(row?.editedTimestamp).toBeNull();
- const updates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'MESSAGE_UPDATE');
- expect(updates).toHaveLength(1);
- expect(updates[0]?.data).toMatchObject({id: message.id, flags: MessageFlags.CROSSPOSTED});
- expect(infoSpy).toHaveBeenCalledWith(
- {
- actorId: world.author.userId,
- guildId: world.guild.id,
- channelId: world.announcement.id,
- messageId: message.id,
- },
- 'message published',
- );
});
test('publishing another member message needs Manage Messages and Send Messages', async () => {
@@ -291,16 +272,11 @@ describe('Publishing messages in announcement channels', () => {
const message = await postMessage(harness, world.author.token, world.announcement.id, 'Overflow');
worker.failure = (taskType) =>
taskType === 'crosspostMessage' ? new WorkerQueueOverflowError(taskType, 'stream full') : null;
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await crosspostRequest(harness, world.author.token, world.announcement.id, message.id)
.expect(503, APIErrorCodes.SERVICE_UNAVAILABLE)
.execute();
expect((await readMessageRow(world.announcement.id, message.id))?.flags).toBe(0);
expect(await listCrosspostSources(world.announcement.id)).toEqual([]);
- const updates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'MESSAGE_UPDATE');
- expect(updates.map((update) => (update.data as {flags: number}).flags)).toEqual([MessageFlags.CROSSPOSTED, 0]);
expect(await channelBudgetRemaining(world.announcement.id)).toBe(CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
worker.failure = null;
const published = await publish(harness, world.author.token, world.announcement.id, message.id);
diff --git a/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts b/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts
index a315a77d8..5774cb08f 100644
--- a/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts
+++ b/fluxer_api/src/api/channel/tests/MessageSendPermissions.test.ts
@@ -3,11 +3,11 @@
import {createPermissionOverwrite, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS, TEST_TIMEOUTS, wait} from '@app/api/test/TestConstants';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('Message send permissions', () => {
let harness: ApiTestHarness;
diff --git a/fluxer_api/src/api/channel/tests/ThreadLimitsAndTimeouts.test.ts b/fluxer_api/src/api/channel/tests/ThreadLimitsAndTimeouts.test.ts
index 0d1d9aa87..51b10c94b 100644
--- a/fluxer_api/src/api/channel/tests/ThreadLimitsAndTimeouts.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadLimitsAndTimeouts.test.ts
@@ -1,9 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createChannelID, createGuildID, createUserID} from '@app/api/BrandedTypes';
+import {createChannelID} from '@app/api/BrandedTypes';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
import {
acceptInvite,
addMemberRole,
@@ -13,16 +12,16 @@ import {
} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
-import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
+import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, MessageFlags, Permissions} from '@fluxer/constants/src/ChannelConstants';
-import {MAX_ACTIVE_THREADS_PER_GUILD, ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';
+import {ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';
import {ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {GuildRoleResponse} from '@fluxer/schema/src/domains/guild/GuildRoleSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
@@ -49,10 +48,6 @@ describe('thread limits and timeouts', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -95,66 +90,6 @@ describe('thread limits and timeouts', () => {
.execute();
}
- function capActiveThreads() {
- return vi.spyOn(ThreadRepository.prototype, 'countActiveThreads').mockResolvedValue(MAX_ACTIVE_THREADS_PER_GUILD);
- }
-
- describe('active thread cap', () => {
- it('refuses new threads at the cap without writing a thread, a member or a slowmode charge', async () => {
- const s = await setup();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.channelId}`)
- .body({rate_limit_per_user: 60})
- .expect(200)
- .execute();
- const message = await sendMessage(harness, s.owner.token, s.channelId, 'x');
- const cap = capActiveThreads();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.channelId}/threads`)
- .body({name: 'capped', type: ChannelTypes.PUBLIC_THREAD})
- .expect(400, APIErrorCodes.MAX_ACTIVE_THREADS)
- .execute();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.channelId}/messages/${message.id}/threads`)
- .body({name: 'capped'})
- .expect(400, APIErrorCodes.MAX_ACTIVE_THREADS)
- .execute();
- cap.mockRestore();
- expect(await repository.threads.listActiveThreads(createGuildID(BigInt(s.guildId)))).toEqual([]);
- expect(await repository.threads.getState(threadId(message.id))).toBeNull();
- expect(await repository.threads.listMembers(threadId(message.id), {limit: 10})).toEqual([]);
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.channelId}/messages/${message.id}/threads`)
- .body({name: 'allowed'})
- .expect(201)
- .execute();
- });
-
- it('refuses unarchiving by PATCH and by send at the cap', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.channelId);
- await repository.threads.updateState(threadId(thread.id), () => ({archived: true}));
- const cap = capActiveThreads();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${thread.id}`)
- .body({archived: false})
- .expect(400, APIErrorCodes.MAX_ACTIVE_THREADS)
- .execute();
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${thread.id}/messages`)
- .body({content: 'wake up'})
- .expect(400, APIErrorCodes.MAX_ACTIVE_THREADS)
- .execute();
- cap.mockRestore();
- expect((await repository.threads.getState(threadId(thread.id)))?.archived).toBe(true);
- expect(await repository.threads.getMember(threadId(thread.id), createUserID(BigInt(s.member.userId)))).toBeNull();
- const messages = await threadsRequest<Array<MessageResponse>>(harness, s.owner.token)
- .get(`/channels/${thread.id}/messages`)
- .execute();
- expect(messages.map((m) => m.content)).not.toContain('wake up');
- });
- });
-
describe('timeouts', () => {
it('blocks thread writes for a timed-out member but still lets them join, leave, change settings and read', async () => {
const s = await setup();
@@ -272,20 +207,6 @@ describe('thread limits and timeouts', () => {
expect(privatePatched.thread_metadata?.locked).toBe(false);
});
- it('leaves the channel row untouched when the thread state vanishes mid patch', async () => {
- const s = await setup();
- const thread = await startThread(s.member.token, s.channelId);
- vi.spyOn(ThreadRepository.prototype, 'updateState').mockResolvedValueOnce(null);
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${thread.id}`)
- .body({name: 'renamed', rate_limit_per_user: 30})
- .expect(404, APIErrorCodes.UNKNOWN_CHANNEL)
- .execute();
- const stored = await repository.channelData.findUnique(threadId(thread.id));
- expect(stored?.name).toBe('topic');
- expect(stored?.rateLimitPerUser ?? 0).toBe(thread.rate_limit_per_user ?? 0);
- });
-
it('clears slowmode on null rate_limit_per_user for moderators only', async () => {
const s = await setup();
const thread = await startThread(s.member.token, s.channelId);
diff --git a/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts b/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts
index ddf31fc08..97f366822 100644
--- a/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadMemberSettings.test.ts
@@ -15,7 +15,7 @@ import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import {ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {ThreadMemberResponse} from '@fluxer/schema/src/domains/channel/ThreadSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const repository = new ChannelRepository();
diff --git a/fluxer_api/src/api/channel/tests/ThreadMessageLifecycle.test.ts b/fluxer_api/src/api/channel/tests/ThreadMessageLifecycle.test.ts
index ace1519eb..344f76b8b 100644
--- a/fluxer_api/src/api/channel/tests/ThreadMessageLifecycle.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadMessageLifecycle.test.ts
@@ -1,22 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createChannelID, createMessageID, createUserID} from '@app/api/BrandedTypes';
+import {createChannelID, createMessageID} from '@app/api/BrandedTypes';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {MessageTypes} from '@fluxer/constants/src/ChannelConstants';
-import {ServerMessageFlags, ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';
+import {ServerMessageFlags} from '@fluxer/constants/src/ThreadConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
@@ -39,10 +37,6 @@ describe('thread message lifecycle', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -108,36 +102,11 @@ describe('thread message lifecycle', () => {
expect(latest.at(-1)?.type).toBe(MessageTypes.THREAD_STARTER_MESSAGE);
});
- it('sends one member update with current flags when a send unarchives the thread', async () => {
- const s = await setup();
- const source = await sendMessage(harness, s.owner.token, s.channelId, 'source');
- const thread = await threadFromMessage(s, source.id);
- await threadsRequest(harness, s.member.token)
- .put(`/channels/${thread.id}/thread-members/@me`)
- .expect(204)
- .execute();
- await repository.threads.updateState(createChannelID(BigInt(thread.id)), () => ({archived: true}));
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- await send(s.member.token, thread.id, 'back again');
- const events = dispatch.mock.calls.map(([params]) => params);
- expect(events.filter((event) => event.event === 'THREAD_MEMBER_UPDATE')).toEqual([]);
- const update = events.find((event) => event.event === 'THREAD_UPDATE')?.data as {
- _fluxer_members?: Array<{user_id: string; flags: number}>;
- };
- expect(update._fluxer_members?.find((member) => member.user_id === s.member.userId)?.flags).toBe(
- ThreadMemberFlags.HAS_INTERACTED,
- );
- });
-
it('clears HAS_THREAD on the source when the thread is deleted and allows a new thread', async () => {
const s = await setup();
const source = await sendMessage(harness, s.member.token, s.channelId, 'source');
const thread = await threadFromMessage(s, source.id);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await threadsRequest(harness, s.owner.token).delete(`/channels/${thread.id}`).expect(204).execute();
- const events = dispatch.mock.calls.map(([params]) => params);
- expect(events.map((event) => event.event).slice(0, 2)).toEqual(['THREAD_DELETE', 'MESSAGE_UPDATE']);
- expect(events[1]?.data).toMatchObject({id: source.id, __thread_only_update: true});
const stored = await repository.messages.getMessage(
createChannelID(BigInt(s.channelId)),
createMessageID(BigInt(source.id)),
@@ -146,23 +115,6 @@ describe('thread message lifecycle', () => {
await threadFromMessage(s, source.id);
});
- it('leaves a source deleted during thread creation deleted', async () => {
- const s = await setup();
- const source = await sendMessage(harness, s.member.token, s.channelId, 'source');
- const channelId = createChannelID(BigInt(s.channelId));
- const messageId = createMessageID(BigInt(source.id));
- const create = ThreadRepository.prototype.create;
- vi.spyOn(ThreadRepository.prototype, 'create').mockImplementation(async function (this: ThreadRepository, params) {
- await repository.messages.deleteMessage(channelId, messageId, createUserID(BigInt(s.member.userId)));
- return create.call(this, params);
- });
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- await threadFromMessage(s, source.id);
- expect(await repository.messages.getMessage(channelId, messageId)).toBeNull();
- const events = dispatch.mock.calls.map(([params]) => params);
- expect(events.some((event) => event.event === 'MESSAGE_UPDATE')).toBe(false);
- });
-
it('keeps the thread message count in step with admin and bulk deletes', async () => {
const s = await setup();
const source = await sendMessage(harness, s.owner.token, s.channelId, 'source');
@@ -177,7 +129,6 @@ describe('thread message lifecycle', () => {
.expect(200)
.execute();
expect(await messageCount(s.member.token, thread.id)).toBe(1);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
const unknownId = (BigInt(second.id) + 1n).toString();
await threadsRequest(harness, s.owner.token)
.post(`/channels/${thread.id}/messages/bulk-delete`)
@@ -185,7 +136,5 @@ describe('thread message lifecycle', () => {
.expect(204)
.execute();
expect(await messageCount(s.member.token, thread.id)).toBe(0);
- const bulk = dispatch.mock.calls.find(([params]) => params.event === 'MESSAGE_DELETE_BULK')?.[0].data;
- expect(bulk).toMatchObject({ids: [second.id]});
});
});
diff --git a/fluxer_api/src/api/channel/tests/ThreadMessagePath.test.ts b/fluxer_api/src/api/channel/tests/ThreadMessagePath.test.ts
index 7458d3918..b18e927b6 100644
--- a/fluxer_api/src/api/channel/tests/ThreadMessagePath.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadMessagePath.test.ts
@@ -1,10 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createChannelID, createGuildID, createMessageID, createUserID} from '@app/api/BrandedTypes';
+import {createChannelID, createGuildID, createUserID} from '@app/api/BrandedTypes';
import {authorizeBot, createTestBotAccount} from '@app/api/bot/tests/BotTestUtils';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {MessageSearchService} from '@app/api/channel/services/message/MessageSearchService';
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {upsertOne} from '@app/api/database/CassandraQueryExecution';
@@ -24,7 +23,7 @@ import {ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {GuildAuditLogListResponse} from '@fluxer/schema/src/domains/guild/GuildAuditLogSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
@@ -403,7 +402,7 @@ describe('thread message path', () => {
await threadsRequest(harness, s.owner.token).get(`/guilds/${s.guildId}/audit-logs?action_type=110`).execute();
});
- it('tags batched thread message deletes and never merges parent deletes across hidden entries', async () => {
+ it('never merges parent message deletes across hidden thread entries', async () => {
const s = await setup();
const thread = await startThread(s.owner.token, s.channelId);
const remove = (channelId: string, messageId: string) =>
diff --git a/fluxer_api/src/api/channel/tests/ThreadNsfw.test.ts b/fluxer_api/src/api/channel/tests/ThreadNsfw.test.ts
index a14308e2f..544556925 100644
--- a/fluxer_api/src/api/channel/tests/ThreadNsfw.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadNsfw.test.ts
@@ -2,9 +2,6 @@
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createReportID} from '@app/api/BrandedTypes';
-import {MessageContentService} from '@app/api/channel/services/message/MessageContentService';
-import {MessagePersistenceService} from '@app/api/channel/services/message/MessagePersistenceService';
-import {MessageSendService} from '@app/api/channel/services/message/MessageSendService';
import {
acceptInvite,
createChannel,
@@ -14,8 +11,7 @@ import {
} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
-import {EmbedService} from '@app/api/infrastructure/EmbedService';
-import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
+import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {ReportRepository} from '@app/api/report/ReportRepository';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
@@ -24,7 +20,7 @@ import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSc
import type {StartForumThreadResponse} from '@fluxer/schema/src/domains/channel/ForumRequestSchemas';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
@@ -46,10 +42,6 @@ describe('thread nsfw scope', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -77,54 +69,14 @@ describe('thread nsfw scope', () => {
.execute();
}
- function post(token: string, channelId: string, body: Record<string, unknown>, status = 200, code?: string) {
+ function post(token: string, channelId: string, body: Record<string, unknown>) {
return threadsRequest<MessageResponse>(harness, token)
.post(`/channels/${channelId}/messages`)
.body(body)
- .expect(status, code)
+ .expect(200)
.execute();
}
- it('allows nsfw attachments and unfurls in a thread under an nsfw parent', async () => {
- const s = await setup();
- const nsfwThread = await startThread(s.owner.token, s.nsfwChannelId);
- const sfwThread = await startThread(s.owner.token, s.sfwChannelId);
- const attachments = vi.spyOn(
- MessagePersistenceService.prototype as unknown as {processAttachments: (...args: Array<unknown>) => unknown},
- 'processAttachments',
- );
- const embeds = vi.spyOn(EmbedService.prototype, 'getInitialEmbeds');
- const scope = vi.spyOn(MessageContentService.prototype, 'isNSFWContentAllowed');
- await post(s.owner.token, nsfwThread.id, {content: 'see https://example.com/a'});
- expect(scope.mock.calls.at(-1)?.[0].channel?.id.toString()).toBe(s.nsfwChannelId);
- expect(scope.mock.results.at(-1)?.value).toBe(true);
- expect(attachments.mock.calls.at(-1)?.[1]).toBe('allow');
- expect(embeds.mock.calls.at(-1)?.[0].nsfwMode).toBe('allow');
- await post(s.owner.token, sfwThread.id, {content: 'see https://example.com/b'});
- expect(scope.mock.calls.at(-1)?.[0].channel?.id.toString()).toBe(s.sfwChannelId);
- expect(scope.mock.calls.at(-1)?.[0].channel?.isNsfw).toBe(false);
- });
-
- it('accepts nsfw forwards into a thread only under an nsfw parent', async () => {
- const s = await setup();
- const nsfwThread = await startThread(s.owner.token, s.nsfwChannelId);
- const sfwThread = await startThread(s.owner.token, s.sfwChannelId);
- const source = await sendMessage(harness, s.owner.token, s.sfwChannelId, 'forward me');
- vi.spyOn(
- MessageSendService.prototype as unknown as {snapshotsContainNsfwContent: () => boolean},
- 'snapshotsContainNsfwContent',
- ).mockReturnValue(true);
- const reference = {type: 1, channel_id: s.sfwChannelId, message_id: source.id};
- await post(s.owner.token, nsfwThread.id, {message_reference: reference});
- await post(
- s.owner.token,
- sfwThread.id,
- {message_reference: reference},
- 403,
- APIErrorCodes.NSFW_CONTENT_AGE_RESTRICTED,
- );
- });
-
it('requires age verification for posts and post data under an nsfw forum', async () => {
const s = await setup();
const minor = await createTestAccount(harness, {dateOfBirth: '2012-01-01'});
diff --git a/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts b/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts
index fd2f40fde..062b25f6c 100644
--- a/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadPinsAck.test.ts
@@ -10,7 +10,7 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
diff --git a/fluxer_api/src/api/channel/tests/ThreadRoutes.test.ts b/fluxer_api/src/api/channel/tests/ThreadRoutes.test.ts
index a9143b4be..1b58444d0 100644
--- a/fluxer_api/src/api/channel/tests/ThreadRoutes.test.ts
+++ b/fluxer_api/src/api/channel/tests/ThreadRoutes.test.ts
@@ -4,7 +4,6 @@ import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/te
import {createChannelID, createMessageID, createUserID} from '@app/api/BrandedTypes';
import {createTestBotAccount} from '@app/api/bot/tests/BotTestUtils';
import {ChannelRepository} from '@app/api/channel/ChannelRepository';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
import {
acceptInvite,
addMemberRole,
@@ -16,14 +15,12 @@ import {THREADS_FEATURE, THREADS_FEATURE_HEADER, threadsRequest} from '@app/api/
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {sendMessage} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, MessageTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {ServerMessageFlags, ThreadMemberFlags} from '@fluxer/constants/src/ThreadConstants';
import {ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';
-import {ThreadAlreadyCreatedForMessageError} from '@fluxer/errors/src/domains/channel/ThreadAlreadyCreatedForMessageError';
import type {
ActiveThreadsResponse,
ArchivedThreadsResponse,
@@ -32,8 +29,7 @@ import type {
import type {ThreadMemberResponse} from '@fluxer/schema/src/domains/channel/ThreadSchemas';
import type {GuildRoleResponse} from '@fluxer/schema/src/domains/guild/GuildRoleSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {RateLimitService} from '@pkgs/rate_limit/src/RateLimitService';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
@@ -67,10 +63,6 @@ describe('thread routes', () => {
clearChannelThreadsTaintCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -110,6 +102,16 @@ describe('thread routes', () => {
.execute();
}
+ async function threadMessages(token: string, channelId: string): Promise<Array<MessageResponse>> {
+ return threadsRequest<Array<MessageResponse>>(harness, token).get(`/channels/${channelId}/messages`).execute();
+ }
+
+ async function threadCreatedMessages(s: Setup): Promise<Array<MessageResponse>> {
+ return (await threadMessages(s.owner.token, s.channelId)).filter(
+ (message) => message.type === MessageTypes.THREAD_CREATED,
+ );
+ }
+
describe('control arm', () => {
async function snapshot(path: string, method: string, token: string, headers: Record<string, string>) {
const response = await harness.requestJson({
@@ -180,7 +182,6 @@ describe('thread routes', () => {
it('creates a public thread that shares the message id', async () => {
const s = await setup();
const message = await sendMessage(harness, s.member.token, s.channelId, 'start here');
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
const thread = await threadsRequest<ThreadChannelResponse>(harness, s.owner.token)
.post(`/channels/${s.channelId}/messages/${message.id}/threads`)
.body({name: 'Discussion', auto_archive_duration: 1440})
@@ -204,25 +205,6 @@ describe('thread routes', () => {
expect(thread.member).toBeUndefined();
expect('position' in thread).toBe(false);
expect('permission_overwrites' in thread).toBe(false);
- const threadEvents = dispatch.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event !== 'GUILD_AUDIT_LOG_ENTRY_CREATE');
- expect(threadEvents.map((params) => params.event)).toEqual(['THREAD_CREATE', 'MESSAGE_UPDATE', 'MESSAGE_CREATE']);
- expect(threadEvents[0]!.data).toMatchObject({id: message.id, newly_created: true});
- const starter = threadEvents[2]!.data as MessageResponse;
- expect(starter).toMatchObject({
- id: message.id,
- channel_id: message.id,
- type: MessageTypes.THREAD_STARTER_MESSAGE,
- message_reference: {channel_id: s.channelId, message_id: message.id},
- });
- expect(starter.referenced_message?.id).toBe(message.id);
- expect(starter.referenced_message?.thread?.id).toBe(message.id);
- expect(starter.referenced_message?.thread && 'member' in starter.referenced_message.thread).toBe(false);
- const update = threadEvents[1]!.data as MessageResponse & {__thread_only_update?: boolean};
- expect(update.flags & ServerMessageFlags.HAS_THREAD).toBe(ServerMessageFlags.HAS_THREAD);
- expect(update.__thread_only_update).toBe(true);
- expect(update.thread?.id).toBe(message.id);
const stored = await repository.messages.getMessage(
createChannelID(BigInt(s.channelId)),
createMessageID(BigInt(message.id)),
@@ -241,7 +223,6 @@ describe('thread routes', () => {
const nearBottom = await sendMessage(harness, s.owner.token, s.channelId, 'recent news');
let latest = nearBottom;
for (let i = 0; i < 4; i++) latest = await sendMessage(harness, s.owner.token, s.channelId, `filler ${i}`);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
for (const message of [nearBottom, pushedUp]) {
await threadsRequest(harness, s.owner.token)
.post(`/channels/${s.channelId}/messages/${message.id}/threads`)
@@ -249,9 +230,7 @@ describe('thread routes', () => {
.expect(201)
.execute();
}
- const announced = dispatch.mock.calls
- .map(([params]) => params.data as MessageResponse)
- .filter((data) => data.type === MessageTypes.THREAD_CREATED);
+ const announced = await threadCreatedMessages(s);
expect(announced).toHaveLength(1);
expect(announced[0]).toMatchObject({channel_id: s.channelId, content: 'old news'});
expect(announced[0]!.message_reference?.channel_id).toBe(pushedUp.id);
@@ -337,23 +316,6 @@ describe('thread routes', () => {
.execute();
});
- it('refunds the parent slowmode when the thread write loses a race', async () => {
- const s = await setup();
- await threadsRequest(harness, s.owner.token)
- .patch(`/channels/${s.channelId}`)
- .body({rate_limit_per_user: 60})
- .expect(200)
- .execute();
- const message = await sendMessage(harness, s.owner.token, s.channelId, 'x');
- vi.spyOn(ThreadRepository.prototype, 'create').mockRejectedValueOnce(new ThreadAlreadyCreatedForMessageError());
- await threadsRequest(harness, s.member.token)
- .post(`/channels/${s.channelId}/messages/${message.id}/threads`)
- .body({name: 'raced'})
- .expect(400, APIErrorCodes.THREAD_ALREADY_CREATED_FOR_MESSAGE)
- .execute();
- await startThread(s.member.token, s.channelId, {name: 'next', type: ChannelTypes.PUBLIC_THREAD});
- });
-
it('resets the thread create slowmode when the parent rate limit changes', async () => {
const s = await setup();
const setRateLimit = (seconds: number) =>
@@ -369,21 +331,18 @@ describe('thread routes', () => {
.body({name: 'blocked', type: ChannelTypes.PUBLIC_THREAD})
.expect(400, APIErrorCodes.SLOWMODE_RATE_LIMITED)
.execute();
- const clear = vi.spyOn(RateLimitService.prototype, 'clearLimitsByIdentifierPrefix');
await setRateLimit(30);
- expect(clear.mock.calls).toEqual([[`slowmode:${s.channelId}:`], [`slowmode-thread:${s.channelId}:`]]);
await startThread(s.member.token, s.channelId, {name: 'second', type: ChannelTypes.PUBLIC_THREAD});
});
});
- it('refuses a limited account on both thread create routes without dispatching', async () => {
+ it('refuses a limited account on both thread create routes', async () => {
const s = await setup();
const message = await sendMessage(harness, s.owner.token, s.channelId, 'start here');
await createBuilder(harness, '')
.post(`/test/users/${s.member.userId}/security-flags`)
.body({set_flags: ['ACCOUNT_LIMITED']})
.execute();
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await threadsRequest(harness, s.member.token)
.post(`/channels/${s.channelId}/threads`)
.body({name: 'limited', type: ChannelTypes.PUBLIC_THREAD})
@@ -395,7 +354,7 @@ describe('thread routes', () => {
.expect(403, APIErrorCodes.ACCOUNT_LIMITED)
.execute();
expect(await repository.threads.getState(createChannelID(BigInt(message.id)))).toBeNull();
- expect(dispatch.mock.calls.filter(([params]) => params.event.startsWith('THREAD_'))).toEqual([]);
+ expect(await threadCreatedMessages(s)).toEqual([]);
});
describe('start thread without a message', () => {
@@ -449,18 +408,12 @@ describe('thread routes', () => {
it('posts a thread created message in the parent for public threads only', async () => {
const s = await setup();
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
const publicThread = await startThread(s.owner.token, s.channelId);
- const created = dispatch.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'MESSAGE_CREATE')
- .map((params) => params.data as MessageResponse);
+ await startThread(s.owner.token, s.channelId, {name: 'quiet', type: ChannelTypes.PRIVATE_THREAD});
+ const created = await threadCreatedMessages(s);
expect(created).toHaveLength(1);
- expect(created[0]).toMatchObject({type: MessageTypes.THREAD_CREATED, channel_id: s.channelId, content: 'topic'});
+ expect(created[0]).toMatchObject({channel_id: s.channelId, content: 'topic'});
expect(created[0]!.message_reference?.channel_id).toBe(publicThread.id);
- dispatch.mockClear();
- await startThread(s.owner.token, s.channelId, {name: 'quiet', type: ChannelTypes.PRIVATE_THREAD});
- expect(dispatch.mock.calls.filter(([params]) => params.event === 'MESSAGE_CREATE')).toEqual([]);
});
it('refuses private threads without create private threads', async () => {
@@ -489,7 +442,6 @@ describe('thread routes', () => {
it('joins and leaves a thread', async () => {
const s = await setup();
const thread = await startThread(s.owner.token, s.channelId);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await threadsRequest(harness, s.member.token)
.put(`/channels/${thread.id}/thread-members/@me`)
.expect(204)
@@ -498,14 +450,7 @@ describe('thread routes', () => {
.put(`/channels/${thread.id}/thread-members/@me`)
.expect(204)
.execute();
- const joined = dispatch.mock.calls.filter(([params]) => params.event === 'THREAD_MEMBERS_UPDATE');
- expect(joined).toHaveLength(1);
- expect(joined[0]![0].data).toMatchObject({
- id: thread.id,
- guild_id: s.guildId,
- member_count: 2,
- added_members: [{id: thread.id, user_id: s.member.userId, flags: 0}],
- });
+ expect((await repository.threads.getState(createChannelID(BigInt(thread.id))))?.memberCount).toBe(2);
await threadsRequest(harness, s.member.token)
.delete(`/channels/${thread.id}/thread-members/@me`)
.expect(204)
@@ -560,70 +505,32 @@ describe('thread routes', () => {
it('adds and removes other members with recipient system messages', async () => {
const s = await setup();
const thread = await startThread(s.owner.token, s.channelId);
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await threadsRequest(harness, s.owner.token)
.put(`/channels/${thread.id}/thread-members/${s.member.userId}`)
.expect(204)
.execute();
- const recipientAdd = dispatch.mock.calls
- .map(([params]) => params)
- .find((params) => params.event === 'MESSAGE_CREATE')?.data as MessageResponse | undefined;
- expect(recipientAdd).toMatchObject({type: MessageTypes.RECIPIENT_ADD, channel_id: thread.id});
+ const recipientAdd = (await threadMessages(s.owner.token, thread.id)).find(
+ (message) => message.type === MessageTypes.RECIPIENT_ADD,
+ );
+ expect(recipientAdd).toMatchObject({channel_id: thread.id});
expect(recipientAdd?.mentions.map((user) => user.id)).toEqual([s.member.userId]);
await threadsRequest(harness, s.member.token)
.delete(`/channels/${thread.id}/thread-members/${s.owner.userId}`)
.expect(403, APIErrorCodes.MISSING_PERMISSIONS)
.execute();
- dispatch.mockClear();
await threadsRequest(harness, s.owner.token)
.delete(`/channels/${thread.id}/thread-members/${s.member.userId}`)
.expect(204)
.execute();
- const events = dispatch.mock.calls.map(([params]) => params.event);
- expect(events).toContain('THREAD_MEMBERS_UPDATE');
- const removed = dispatch.mock.calls.find(([params]) => params.event === 'THREAD_MEMBERS_UPDATE')![0].data;
- expect(removed).toMatchObject({removed_member_ids: [s.member.userId], member_count: 1});
+ const messages = await threadMessages(s.owner.token, thread.id);
+ expect(messages.some((message) => message.type === MessageTypes.RECIPIENT_REMOVE)).toBe(true);
+ expect((await repository.threads.getState(createChannelID(BigInt(thread.id))))?.memberCount).toBe(1);
await threadsRequest(harness, s.owner.token)
.delete(`/channels/${thread.id}/thread-members/${s.member.userId}`)
.expect(404, APIErrorCodes.UNKNOWN_THREAD_MEMBER)
.execute();
});
- it('posts one recipient message when concurrent adds or removes race past the membership check', async () => {
- const s = await setup();
- const thread = await startThread(s.owner.token, s.channelId);
- const realGetMember = ThreadRepository.prototype.getMember;
- let stale: Awaited<ReturnType<ThreadRepository['getMember']>> = null;
- vi.spyOn(ThreadRepository.prototype, 'getMember').mockImplementation(function (this: ThreadRepository, ...args) {
- return args[1].toString() === s.member.userId ? Promise.resolve(stale) : realGetMember.apply(this, args);
- });
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const recipientMessages = (type: number) =>
- dispatch.mock.calls.filter(
- ([params]) => params.event === 'MESSAGE_CREATE' && (params.data as MessageResponse).type === type,
- );
- const put = () =>
- threadsRequest(harness, s.owner.token)
- .put(`/channels/${thread.id}/thread-members/${s.member.userId}`)
- .expect(204)
- .execute();
- await Promise.all([put(), put()]);
- expect(recipientMessages(MessageTypes.RECIPIENT_ADD)).toHaveLength(1);
- stale = await realGetMember.call(
- repository.threads as ThreadRepository,
- createChannelID(BigInt(thread.id)),
- createUserID(BigInt(s.member.userId)),
- );
- expect(stale).not.toBeNull();
- const del = () =>
- threadsRequest(harness, s.owner.token)
- .delete(`/channels/${thread.id}/thread-members/${s.member.userId}`)
- .expect(204)
- .execute();
- await Promise.all([del(), del()]);
- expect(recipientMessages(MessageTypes.RECIPIENT_REMOVE)).toHaveLength(1);
- });
-
it('refuses adding a user who is not a guild member', async () => {
const s = await setup();
const outsider = await createTestAccount(harness);
@@ -657,18 +564,18 @@ describe('thread routes', () => {
.body({name: 'mods', permissions: ThreadPermissionFlags.MANAGE_THREADS.toString()})
.execute();
await addMemberRole(harness, s.owner.token, s.guildId, third.userId, role.id);
- const setTimeout = (until: string | null) =>
+ const setTimedOutUntil = (until: string | null) =>
threadsRequest(harness, s.owner.token)
.patch(`/guilds/${s.guildId}/members/${third.userId}`)
.body({communication_disabled_until: until})
.expect(200)
.execute();
- await setTimeout(new Date(Date.now() + 10 * 60 * 1000).toISOString());
+ await setTimedOutUntil(new Date(Date.now() + 10 * 60 * 1000).toISOString());
await threadsRequest(harness, s.member.token)
.put(`/channels/${thread.id}/thread-members/${third.userId}`)
.expect(403, APIErrorCodes.MISSING_PERMISSIONS)
.execute();
- await setTimeout(null);
+ await setTimedOutUntil(null);
await threadsRequest(harness, s.member.token)
.put(`/channels/${thread.id}/thread-members/${third.userId}`)
.expect(204)
@@ -884,28 +791,6 @@ describe('thread routes', () => {
});
});
- describe('announcement parents', () => {
- it('refuses a thread whose parent became an announcement channel mid-create', async () => {
- const s = await setup();
- const parentId = createChannelID(BigInt(s.channelId));
- const count = ThreadRepository.prototype.countActiveThreads;
- vi.spyOn(ThreadRepository.prototype, 'countActiveThreads').mockImplementationOnce(async function (
- this: ThreadRepository,
- guildId,
- ) {
- const parent = await repository.channelData.findUnique(parentId);
- await repository.channelData.upsert({...parent!.toRow(), type: ChannelTypes.GUILD_ANNOUNCEMENT});
- return count.call(this, guildId);
- });
- await threadsRequest(harness, s.owner.token)
- .post(`/channels/${s.channelId}/threads`)
- .body({name: 'late', type: ChannelTypes.PUBLIC_THREAD})
- .expect(400, APIErrorCodes.INVALID_CHANNEL_TYPE)
- .execute();
- expect(await repository.threads.listThreadIdsByParent(parentId, {limit: 1})).toEqual([]);
- });
- });
-
describe('admin', () => {
it('lists every thread of a guild and deletes thread data', async () => {
const s = await setup();
diff --git a/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts b/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts
index 91c7fbb6d..c3c7eca5b 100644
--- a/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts
+++ b/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts
@@ -6,8 +6,8 @@ import {ConnectionService} from '@app/api/connection/ConnectionService';
import {ConnectionLimitReachedError} from '@app/api/connection/errors/ConnectionLimitReachedError';
import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
import type {UserConnectionRow} from '@app/api/database/types/ConnectionTypes';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
+import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {
ConnectionTypes,
@@ -53,7 +53,7 @@ describe('ConnectionService connection limit', () => {
for (let index = 0; index < MAX_CONNECTIONS_PER_USER; index++) {
await repository.create(connectionRow(userId, `connection-${index}`, index));
}
- const service = new ConnectionService(repository, {} as unknown as IGatewayService);
+ const service = new ConnectionService(repository, new NoopGatewayService());
const error = await service.initiateConnection(userId, ConnectionTypes.DOMAIN, 'over-the-limit.example').then(
() => null,
@@ -73,7 +73,7 @@ describe('ConnectionService connection limit', () => {
for (let index = 0; index < MAX_CONNECTIONS_PER_USER - 1; index++) {
await repository.create(connectionRow(userId, `connection-${index}`, index));
}
- const service = new ConnectionService(repository, {} as unknown as IGatewayService);
+ const service = new ConnectionService(repository, new NoopGatewayService());
await expect(
service.initiateConnection(userId, ConnectionTypes.DOMAIN, 'under-the-limit.example'),
diff --git a/fluxer_api/src/api/database/CassandraSchemaStartup.test.ts b/fluxer_api/src/api/database/CassandraSchemaStartup.test.ts
index 2c2fe1661..af2b26fa7 100644
--- a/fluxer_api/src/api/database/CassandraSchemaStartup.test.ts
+++ b/fluxer_api/src/api/database/CassandraSchemaStartup.test.ts
@@ -12,7 +12,7 @@ import {
import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {afterEach, describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
const THIS_DIR = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(THIS_DIR, '../../../..');
diff --git a/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts b/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts
index a32fa05c8..57d43b6e9 100644
--- a/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts
+++ b/fluxer_api/src/api/donation/tests/DonationCheckout.test.ts
@@ -52,14 +52,10 @@ describe('POST /donations/checkout', () => {
.body({...createValidCheckoutBody(), interval: null, is_business: false})
.expect(200)
.execute();
- const [business, personal] = stripeHandlers.spies.createdCheckoutSessions as unknown as Array<{
- mode?: string;
- customer_creation?: string;
- invoice_creation?: {enabled?: string};
- }>;
+ const [business, personal] = stripeHandlers.spies.createdCheckoutSessions;
expect(business).toMatchObject({mode: 'payment', customer_creation: 'always', invoice_creation: {enabled: 'true'}});
expect(personal).toMatchObject({mode: 'payment', customer_creation: 'always'});
- expect(personal?.invoice_creation).toBeUndefined();
+ expect(personal).not.toHaveProperty('invoice_creation');
});
test('sets subscription mode', async () => {
await createDonationCheckoutBuilder(harness).body(createValidCheckoutBody()).expect(200).execute();
diff --git a/fluxer_api/src/api/donation/tests/DonationManage.test.ts b/fluxer_api/src/api/donation/tests/DonationManage.test.ts
index 24c7990fd..e6c9efaa4 100644
--- a/fluxer_api/src/api/donation/tests/DonationManage.test.ts
+++ b/fluxer_api/src/api/donation/tests/DonationManage.test.ts
@@ -13,7 +13,7 @@ import {createPwnedPasswordsRangeHandler} from '@app/api/test/msw/handlers/Pwned
import {createStripeApiHandlers, type StripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';
import {server} from '@app/api/test/msw/server';
import {createBuilderWithoutAuth, type TestRequestBuilder} from '@app/api/test/TestRequestBuilder';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
type DonationManageAlert = 'link_expired' | 'link_used' | 'link_invalid' | 'no_customer' | 'portal_error';
@@ -195,9 +195,6 @@ describe('GET and POST /donations/manage', () => {
});
});
describe('edge cases', () => {
- afterEach(() => {
- vi.useRealTimers();
- });
test('handles token for donor with cancelled subscription', async () => {
const customerId = 'cus_test_cancelled';
await createDonorWithoutSubscription(TEST_DONOR_EMAIL, customerId);
@@ -207,14 +204,9 @@ describe('GET and POST /donations/manage', () => {
expect(stripeHandlers.spies.createdPortalSessions).toHaveLength(1);
expect(stripeHandlers.spies.createdPortalSessions[0]?.customer).toBe(customerId);
});
- test('handles token at its exact expiry instant', async () => {
- const expiresAt = new Date();
- vi.useFakeTimers({toFake: ['Date']});
- vi.setSystemTime(expiresAt);
+ test('rejects an expired token without using it', async () => {
await createDonorWithCustomerId(TEST_DONOR_EMAIL, 'cus_test');
- await createMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN, expiresAt, null);
- expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(confirmUrl(TEST_MAGIC_LINK_TOKEN));
- vi.setSystemTime(expiresAt.getTime() + 1);
+ await createMagicLinkToken(TEST_DONOR_EMAIL, TEST_MAGIC_LINK_TOKEN, new Date(Date.now() - 1000), null);
expect(await openManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_expired'));
expect(await redeemManageLink(TEST_MAGIC_LINK_TOKEN)).toBe(alertUrl('link_expired'));
expect(await isTokenUsed(TEST_MAGIC_LINK_TOKEN)).toBe(false);
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementClosure.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementClosure.test.ts
index 33656b1c8..3a6d79ffe 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementClosure.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementClosure.test.ts
@@ -154,7 +154,7 @@ describe('Enforcement closures', () => {
const response = await closeRequest(harness, staff, target.userId, {days_until_deletion: 30, basis: {type}})
.expect(HTTP_STATUS.CONFLICT, APIErrorCodes.ENFORCEMENT_DECISION_OWNS_STATE)
.execute();
- expect((response as unknown as {decision_id: string}).decision_id).toBe(decisionId);
+ expect(response).toMatchObject({decision_id: decisionId});
expect((await loadUser(target)).pendingDeletionAt).toBeNull();
});
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementContent.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementContent.test.ts
index b71a315a7..d7cb74df1 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementContent.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementContent.test.ts
@@ -30,7 +30,7 @@ import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
interface ValidationErrorBody {
errors: Array<{path: string; code: string}>;
@@ -162,7 +162,7 @@ describe('Enforcement content, profile and community decisions', () => {
expect(worker.byTask('messageShred')).toEqual([]);
});
- test('a restricted shred stores every entry without content before the job is queued', async () => {
+ test('a restricted shred stores every entry without content', async () => {
const {target, entries} = await guildMessages(2);
const response = await shredRequest(target.userId, {entries, basis: enforcement(RESTRICTED)})
.expect(HTTP_STATUS.OK)
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts
index 514b1013b..ea1a069e4 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementNetworkBlock.test.ts
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {randomBytes} from 'node:crypto';
import {AdminRepository} from '@app/api/admin/AdminRepository';
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createUserID} from '@app/api/BrandedTypes';
import {resetIpBanExemptionsForTesting} from '@app/api/ban/IpBanExemptions';
import {getConfig} from '@app/api/Config';
import {upsertOne} from '@app/api/database/CassandraQueryExecution';
@@ -20,7 +22,7 @@ import {
} from '@app/api/enforcement/tests/EnforcementTestUtils';
import {ipBanCache} from '@app/api/middleware/IpBanMiddleware';
import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
-import {BannedIps} from '@app/api/Tables';
+import {AuthSessionTombstones, BannedIps} from '@app/api/Tables';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
@@ -29,7 +31,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {ms} from 'itty-time';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
interface ValidationErrorBody {
errors: Array<{path: string; code: string}>;
@@ -69,10 +71,6 @@ describe('Enforcement network blocks', () => {
staff = await createStaff(harness);
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
await harness?.shutdown();
});
@@ -178,15 +176,28 @@ describe('Enforcement network blocks', () => {
expect((await loadUser(target)).enforcementDecisionId).toBeNull();
});
- function sightings(entries: Array<[string, number]>) {
- vi.spyOn(getUserRepository(), 'listAuthSessionTombstones').mockResolvedValue(
- entries.map(([ip, lastUsed]) => ({clientIp: ip, approximateLastUsedAt: new Date(lastUsed)})) as never,
- );
+ async function sightings(target: TestAccount, entries: Array<[string, number]>) {
+ for (const [ip, lastUsed] of entries) {
+ await upsertOne(
+ AuthSessionTombstones.insert({
+ user_id: createUserID(BigInt(target.userId)),
+ session_id_hash: randomBytes(32),
+ created_at: new Date(lastUsed),
+ approx_last_used_at: new Date(lastUsed),
+ client_ip: ip,
+ client_user_agent: null,
+ client_os: null,
+ client_country: null,
+ deleted_at: new Date(),
+ version: 1,
+ }),
+ );
+ }
}
test('only addresses the account used in the last 30 days can be blocked', async () => {
const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- sightings([['45.33.20.1', Date.now() - 40 * DAY]]);
+ await sightings(target, [['45.33.20.1', Date.now() - 40 * DAY]]);
expect(await refusedBlock(target, ['45.33.20.1'])).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_UNKNOWN);
expect(await refusedBlock(target, ['45.33.30.1'])).toBe(ValidationErrorCodes.ENFORCEMENT_NETWORK_UNKNOWN);
await blockingSuspension(target, [TARGET_IP]).expect(HTTP_STATUS.OK).execute();
@@ -199,7 +210,7 @@ describe('Enforcement network blocks', () => {
resetIpBanExemptionsForTesting();
try {
const target = await createTestAccount(harness, {ipAddress: TARGET_IP});
- sightings([
+ await sightings(target, [
['45.33.40.1', Date.now()],
['100.64.1.1', Date.now()],
['192.168.1.5', Date.now()],
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts
index e85d5313c..db172b3ac 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts
@@ -35,7 +35,7 @@ import {DeletionReasons} from '@fluxer/constants/src/Core';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {ms} from 'itty-time';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
describe('Enforcement suspensions', () => {
let harness: ApiTestHarness;
@@ -66,11 +66,12 @@ describe('Enforcement suspensions', () => {
return {target, channelId: systemChannel.id, channelName: systemChannel.name!, messageId: message.id};
}
- test('records the decision before the state and sets the pointer in the same user write', async () => {
+ test('records the decision and points the suspended user at it', async () => {
const target = await createTestAccount(harness);
const decisionId = await suspend(harness, staff, target.userId);
const user = await loadUser(target);
expect(user.enforcementDecisionId).toBe(BigInt(decisionId));
+ expect(user.tempBannedUntil).not.toBeNull();
expect((user.flags & UserFlags.DISABLED) !== 0n).toBe(true);
const decision = await getDecision(harness, staff, decisionId);
expect(decision).toMatchObject({kind: 'suspension', status: 'active', notice_status: 'sent', replaced: false});
@@ -306,9 +307,7 @@ describe('Enforcement suspensions', () => {
test('records undelivered when email is off on the instance', async () => {
const target = await createTestAccount(harness);
- const config = getInstanceConfigRepository();
- const effective = await config.getEffectiveEmailConfig();
- vi.spyOn(config, 'getEffectiveEmailConfig').mockResolvedValue({...effective, enabled: false});
+ await getInstanceConfigRepository().setInstanceIntegrationsConfig({email: {delivery: 'off'}});
await clearTestEmails(harness);
const decisionId = await suspend(harness, staff, target.userId);
expect((await getDecision(harness, staff, decisionId)).notice_status).toBe('undelivered');
diff --git a/fluxer_api/src/api/guild/ExpressionSourceGuild.test.ts b/fluxer_api/src/api/guild/ExpressionSourceGuild.test.ts
deleted file mode 100644
index b3f97c58a..000000000
--- a/fluxer_api/src/api/guild/ExpressionSourceGuild.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {resolveExpressionSourceGuild} from '@app/api/guild/ExpressionSourceGuild';
-import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';
-import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
-import {describe, expect, it} from 'vitest';
-
-describe('resolveExpressionSourceGuild', () => {
- it('limits features to the badge flags', async () => {
- const community = await resolveExpressionSourceGuild({
- loadGuild: () =>
- Promise.resolve({
- id: '20',
- name: 'Blob Club',
- icon: null,
- features: [
- GuildFeatures.DISCOVERABLE,
- GuildFeatures.VERIFIED,
- GuildFeatures.INVITES_DISABLED,
- GuildFeatures.CLONE_EMOJI_ENABLED,
- ],
- } as unknown as GuildResponse),
- isMember: () => Promise.resolve(false),
- });
- expect(community.features).toEqual(expect.arrayContaining([GuildFeatures.DISCOVERABLE, GuildFeatures.VERIFIED]));
- expect(community.features).not.toContain(GuildFeatures.INVITES_DISABLED);
- expect(community.features).not.toContain(GuildFeatures.CLONE_EMOJI_ENABLED);
- });
-});
diff --git a/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts b/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts
index 13627a79c..aeafca5bc 100644
--- a/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts
+++ b/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts
@@ -18,8 +18,8 @@ import {setInjectedGatewayService} from '@app/api/middleware/ServiceRegistry';
import {getGuildRepository} from '@app/api/middleware/ServiceSingletons';
import {banUser} from '@app/api/moderation/tests/ModerationTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import syncDiscoveryIndex from '@app/api/worker/tasks/SyncDiscoveryIndex';
@@ -34,7 +34,6 @@ import type {
DiscoveryGuildListResponse,
} from '@fluxer/schema/src/domains/guild/GuildDiscoverySchemas';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type {WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
async function setGuildMemberCount(harness: ApiTestHarness, guildId: string, memberCount: number): Promise<void> {
@@ -49,8 +48,6 @@ interface LiveGuildCounts {
onlineCount: number;
}
-const WORKER_HELPERS = {logger: new NoopLogger()} as unknown as WorkerTaskHelpers;
-
class CapturingPublisher implements ActivityPublisher {
readonly events: Array<Event> = [];
@@ -162,7 +159,7 @@ describe('Discovery Search and Join', () => {
expect(firstPage.guilds.map((guild) => guild.id)).toEqual([guildIds[0], guildIds[1]]);
liveCounts.set(guildIds[0], {memberCount: 5, onlineCount: 0});
setWorkerDependenciesForTest({guildRepository: getGuildRepository(), gatewayService});
- await syncDiscoveryIndex({}, WORKER_HELPERS);
+ await syncDiscoveryIndex({}, createTestWorkerHelpers());
const secondPage = await createBuilder<DiscoveryGuildListResponse>(harness, searcher.token)
.get('/discovery/guilds?sort_by=member_count&limit=2&offset=2')
.expect(HTTP_STATUS.OK)
diff --git a/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts b/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts
index 9ad444a32..37e108f16 100644
--- a/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildAuditLogService.test.ts
@@ -1,13 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {
- createChannelID,
- createGuildID,
- createRoleID,
- createUserID,
- type RoleID,
- type UserID,
-} from '@app/api/BrandedTypes';
+import {createGuildID, createUserID} from '@app/api/BrandedTypes';
import {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
@@ -15,7 +8,7 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
-import {afterEach, assert, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, assert, beforeEach, describe, expect, it} from 'vitest';
const GUILD_ID = createGuildID(1420000000000000000n);
const ACTOR_ID = createUserID(1420000000000000001n);
diff --git a/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts b/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts
deleted file mode 100644
index ce3c4072a..000000000
--- a/fluxer_api/src/api/guild/tests/GuildDeletionJob.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuildID} from '@app/api/BrandedTypes';
-import {processRecordedGuildDeletions, recordGuildDeletions} from '@app/api/guild/tests/GuildDeletionTestUtils';
-import {acceptInvite, createChannelInvite, createGuild, getChannel} from '@app/api/guild/tests/GuildTestUtils';
-import {getGuildRepository} from '@app/api/middleware/ServiceSingletons';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import type {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-describe('Guild deletion job', () => {
- let harness: ApiTestHarness;
- let worker: RecordingWorkerService;
-
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
-
- beforeEach(async () => {
- await harness.reset();
- worker = recordGuildDeletions();
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- async function guildWithMember(): Promise<{owner: TestAccount; member: TestAccount; guild: GuildResponse}> {
- const owner = await createTestAccount(harness);
- const member = await createTestAccount(harness);
- const guild = await createGuild(harness, owner.token, 'Deletion Guild');
- const channel = await getChannel(harness, owner.token, guild.system_channel_id!);
- const invite = await createChannelInvite(harness, owner.token, channel.id);
- await acceptInvite(harness, member.token, invite.code);
- return {owner, member, guild};
- }
-
- async function deleteAsOwner(owner: TestAccount, guildId: string): Promise<void> {
- await createBuilder(harness, owner.token)
- .post(`/guilds/${guildId}/delete`)
- .body({password: owner.password})
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- }
-
- function storedGuild(guildId: string) {
- return getGuildRepository().findUnique(createGuildID(BigInt(guildId)));
- }
-
- test('a purge interrupted by a gateway failure completes when retried', async () => {
- const {owner, guild} = await guildWithMember();
- await deleteAsOwner(owner, guild.id);
- const leaveGuild = NoopGatewayService.prototype.leaveGuild;
- const failing = vi
- .spyOn(NoopGatewayService.prototype, 'leaveGuild')
- .mockRejectedValueOnce(new Error('gateway timeout'))
- .mockImplementation(function (this: NoopGatewayService, params) {
- return leaveGuild.call(this, params);
- });
- await expect(processRecordedGuildDeletions(worker)).rejects.toThrow('gateway timeout');
- expect(await storedGuild(guild.id)).not.toBeNull();
- await processRecordedGuildDeletions(worker);
- expect(await storedGuild(guild.id)).toBeNull();
- await processRecordedGuildDeletions(worker);
- expect(failing).toHaveBeenCalled();
- });
-});
diff --git a/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts b/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts
index d0b2b4a0e..6c54a5266 100644
--- a/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts
@@ -8,8 +8,7 @@ import {guildVisitRepository} from '@app/api/guild/visits/GuildVisitorAccess';
import {getGuildRepository, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface SessionData {
data: {visit_guild_ids: Array<string>};
diff --git a/fluxer_api/src/api/guild/tests/GuildVisitorReads.test.ts b/fluxer_api/src/api/guild/tests/GuildVisitorReads.test.ts
index 235d82c1d..c2237d646 100644
--- a/fluxer_api/src/api/guild/tests/GuildVisitorReads.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildVisitorReads.test.ts
@@ -13,7 +13,7 @@ import type {LimitConfigSnapshot} from '@fluxer/limits/src/LimitTypes';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, assert, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, assert, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Registered {
token: string;
diff --git a/fluxer_api/src/api/guild/tests/GuildVisits.test.ts b/fluxer_api/src/api/guild/tests/GuildVisits.test.ts
index 6d361ed0a..fe4375c08 100644
--- a/fluxer_api/src/api/guild/tests/GuildVisits.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildVisits.test.ts
@@ -17,7 +17,7 @@ import {GuildVisitSources} from '@fluxer/constants/src/GuildVisitConstants';
import {Headers} from '@fluxer/constants/src/Headers';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import type {GuildVisitResponse, GuildVisitStartResponse} from '@fluxer/schema/src/domains/guild/GuildVisitSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Registered {
token: string;
@@ -361,60 +361,16 @@ describe('Guild visits', () => {
await discoveryVisit().expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.GUILD_VISITS_DISABLED).execute();
});
- it.each([
- {maxAge: 0, expectedWireExpiry: null, expectedStoredExpiry: null},
- {
- maxAge: 60,
- expectedWireExpiry: '2026-10-23T02:21:00.000Z',
- expectedStoredExpiry: new Date('2026-10-23T02:21:00.000Z'),
- },
- ])(
- 'retains a $maxAge-second invite expiry when starting a later visit',
- async ({maxAge, expectedWireExpiry, expectedStoredExpiry}) => {
- vi.useFakeTimers({toFake: ['Date']});
- vi.setSystemTime(new Date('2026-10-23T02:20:00.000Z'));
- const {guildId, code} = await createVisitGuild('Invite expiry', {max_age: maxAge, unique: true});
- const visitor = await createUnclaimed();
- const invite = await createBuilderWithoutAuth<{expires_at: string | null}>(harness)
- .get(`/invites/${code}`)
- .execute();
- expect(invite.expires_at).toBe(expectedWireExpiry);
- vi.advanceTimersByTime(10000);
- const started = await startVisit(visitor.token, code).execute();
- expect(started).toEqual({
- guild_id: guildId,
- member: false,
- visit: {
- guild_id: guildId,
- source: 1,
- started_at: '2026-10-23T02:20:10.000Z',
- opened_at: '2026-10-23T02:20:10.000Z',
- },
- });
- const row = await guildVisitRepository().get(
- createUserID(BigInt(visitor.user_id)),
- createGuildID(BigInt(guildId)),
- );
- expect(row).toEqual({
- user_id: createUserID(BigInt(visitor.user_id)),
- guild_id: createGuildID(BigInt(guildId)),
- source: 1,
- invite_code: code,
- invite_expires_at: expectedStoredExpiry,
- started_at: new Date('2026-10-23T02:20:10.000Z'),
- opened_at: new Date('2026-10-23T02:20:10.000Z'),
- });
- const visits = await createBuilder<Array<GuildVisitResponse>>(harness, visitor.token)
- .get('/users/@me/guild-visits')
- .execute();
- expect(visits).toEqual([
- {
- guild_id: guildId,
- source: 1,
- started_at: '2026-10-23T02:20:10.000Z',
- opened_at: '2026-10-23T02:20:10.000Z',
- },
- ]);
- },
- );
+ it.each([0, 60])('stores the invite expiry of a %i-second invite on the visit', async (maxAge) => {
+ const {guildId, code} = await createVisitGuild('Invite expiry', {max_age: maxAge, unique: true});
+ const visitor = await createUnclaimed();
+ const invite = await createBuilderWithoutAuth<{expires_at: string | null}>(harness)
+ .get(`/invites/${code}`)
+ .execute();
+ expect(invite.expires_at === null).toBe(maxAge === 0);
+ await startVisit(visitor.token, code).execute();
+ const row = await guildVisitRepository().get(createUserID(BigInt(visitor.user_id)), createGuildID(BigInt(guildId)));
+ expect(row?.invite_code).toBe(code);
+ expect(row?.invite_expires_at ?? null).toEqual(invite.expires_at === null ? null : new Date(invite.expires_at));
+ });
});
diff --git a/fluxer_api/src/api/infrastructure/AvatarServiceSizeLimits.test.ts b/fluxer_api/src/api/infrastructure/AvatarServiceSizeLimits.test.ts
index fddfb6ec5..bf21b0fd4 100644
--- a/fluxer_api/src/api/infrastructure/AvatarServiceSizeLimits.test.ts
+++ b/fluxer_api/src/api/infrastructure/AvatarServiceSizeLimits.test.ts
@@ -1,108 +1,42 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {AvatarService} from '@app/api/infrastructure/AvatarService';
-import type {IMediaService} from '@app/api/infrastructure/IMediaService';
-import type {IStorageService} from '@app/api/infrastructure/IStorageService';
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createTestGuild, VALID_PNG_BASE64} from '@app/api/emoji/tests/EmojiTestUtils';
+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 {EMOJI_MAX_SIZE, STICKER_MAX_SIZE} from '@fluxer/constants/src/LimitConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
-import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
-import type {LimitConfigSnapshot, LimitRule} from '@fluxer/limits/src/LimitTypes';
-import {describe, expect, it} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-function createSnapshot(rules: Array<LimitRule> = []): LimitConfigSnapshot {
- return {traitDefinitions: [], rules};
+function paddedImage(byteLength: number): string {
+ const image = Buffer.from(VALID_PNG_BASE64, 'base64');
+ return `data:image/png;base64,${Buffer.concat([image, Buffer.alloc(byteLength - image.length)]).toString('base64')}`;
}
-function createService(snapshot: LimitConfigSnapshot): AvatarService {
- const mediaService = {
- getMetadata: () => {
- throw new Error('getMetadata should not be reached for an oversized image');
- },
- } as unknown as IMediaService;
- const storageService = {} as unknown as IStorageService;
- return new AvatarService(storageService, mediaService, {getConfigSnapshot: () => snapshot});
-}
-
-function encodedImage(byteLength: number): string {
- return Buffer.alloc(byteLength, 1).toString('base64');
-}
-
-async function captureValidationError(promise: Promise<unknown>): Promise<InputValidationError> {
- try {
- await promise;
- } catch (error) {
- expect(error).toBeInstanceOf(InputValidationError);
- return error as InputValidationError;
- }
- throw new Error('expected the upload to be rejected');
-}
-
-describe('AvatarService emoji and sticker size ceilings', () => {
- it('rejects an emoji one byte over the built-in ceiling', async () => {
- const service = createService(createSnapshot());
- const error = await captureValidationError(
- service.processEmoji({
- errorPath: 'image',
- base64Image: encodedImage(EMOJI_MAX_SIZE + 1),
- guildFeatures: [],
- }),
- );
- expect(error.getLocalizedErrors()).toEqual([
- {path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: EMOJI_MAX_SIZE}},
- ]);
+describe('emoji and sticker size ceilings', () => {
+ let harness: ApiTestHarness;
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
});
- it('rejects a sticker one byte over the built-in ceiling', async () => {
- const service = createService(createSnapshot());
- const error = await captureValidationError(
- service.processSticker({
- errorPath: 'image',
- base64Image: encodedImage(STICKER_MAX_SIZE + 1),
- guildFeatures: [],
- }),
- );
- expect(error.getLocalizedErrors()).toEqual([
- {path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: STICKER_MAX_SIZE}},
- ]);
+ beforeEach(async () => {
+ await harness.reset();
});
- it('applies a configured emoji_max_size rule in guild scope', async () => {
- const service = createService(createSnapshot([{id: 'emoji-ceiling', limits: {emoji_max_size: 1024}}]));
- const error = await captureValidationError(
- service.processEmoji({errorPath: 'image', base64Image: encodedImage(2048), guildFeatures: []}),
- );
- expect(error.getLocalizedErrors()).toEqual([
- {path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: 1024}},
- ]);
+ afterAll(async () => {
+ await harness?.shutdown();
});
- it('applies a configured sticker_max_size rule in guild scope', async () => {
- const service = createService(createSnapshot([{id: 'sticker-ceiling', limits: {sticker_max_size: 1024}}]));
- const error = await captureValidationError(
- service.processSticker({errorPath: 'image', base64Image: encodedImage(2048), guildFeatures: []}),
- );
- expect(error.getLocalizedErrors()).toEqual([
- {path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: 1024}},
- ]);
- });
- it('applies a guild-feature-filtered emoji_max_size rule only to a guild that has the feature', async () => {
- const rules: Array<LimitRule> = [
- {id: 'big-emoji', filters: {guildFeatures: ['BIG_EMOJI']}, limits: {emoji_max_size: EMOJI_MAX_SIZE * 2}},
- ];
- const service = createService(createSnapshot(rules));
- const error = await captureValidationError(
- service.processEmoji({
- errorPath: 'image',
- base64Image: encodedImage(EMOJI_MAX_SIZE + 1),
- guildFeatures: [],
- }),
- );
- expect(error.getLocalizedErrors()).toEqual([
- {path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: EMOJI_MAX_SIZE}},
- ]);
- await expect(
- service.processEmoji({
- errorPath: 'image',
- base64Image: encodedImage(EMOJI_MAX_SIZE + 1),
- guildFeatures: ['BIG_EMOJI'],
- }),
- ).rejects.toThrow('getMetadata should not be reached for an oversized image');
+
+ it.each([
+ {path: 'emojis', maxSize: EMOJI_MAX_SIZE, body: {name: 'too_big'}},
+ {path: 'stickers', maxSize: STICKER_MAX_SIZE, body: {name: 'too_big', description: 'too big', tags: []}},
+ ])('rejects $path one byte over the built-in ceiling', async ({path, maxSize, body}) => {
+ const owner = await createTestAccount(harness);
+ const guild = await createTestGuild(harness, owner.token);
+ const json = await createBuilder<{errors?: Array<{path?: string; code?: string}>}>(harness, owner.token)
+ .post(`/guilds/${guild.id}/${path}`)
+ .body({...body, image: paddedImage(maxSize + 1)})
+ .expect(HTTP_STATUS.BAD_REQUEST)
+ .execute();
+ expect(json.errors?.[0]).toMatchObject({path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT});
});
});
diff --git a/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts b/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts
index 722b21e42..c66cb39db 100644
--- a/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts
+++ b/fluxer_api/src/api/infrastructure/ControllerCachePurgeAdapter.test.ts
@@ -2,7 +2,9 @@
import type {APICachePurgeConfig} from '@app/api/config/APIConfig';
import {createControllerCachePurgeAdapter} from '@app/api/infrastructure/ControllerCachePurgeAdapter';
-import {afterEach, beforeEach, describe, expect, it, type MockInstance, vi} from 'vitest';
+import {server} from '@app/api/test/msw/server';
+import {HttpResponse, http} from 'msw';
+import {describe, expect, it} from 'vitest';
const ENDPOINT = 'https://controller.test/v1/orgs/org-a/sites/site-b/purge';
@@ -16,23 +18,30 @@ function prefixes(count: number): Array<string> {
return Array.from({length: count}, (_, index) => `media.test/attachments/1/${index}/photo`);
}
+function serveController(statuses: Array<number>): Array<number> {
+ const chunkSizes: Array<number> = [];
+ server.use(
+ http.post(ENDPOINT, async ({request}) => {
+ const {patterns} = (await request.json()) as {patterns: Array<string>};
+ chunkSizes.push(patterns.length);
+ return new HttpResponse(null, {status: statuses[chunkSizes.length - 1] ?? 202});
+ }),
+ );
+ return chunkSizes;
+}
+
describe('createControllerCachePurgeAdapter', () => {
it('splits a batch into requests of at most 30 patterns', async () => {
- fetchSpy.mockImplementation(async () => new Response(null, {status: 202}));
+ const chunkSizes = serveController([]);
const outcome = await createControllerCachePurgeAdapter(CONFIG).purge(prefixes(65));
expect(outcome).toEqual({kind: 'purged'});
- expect(fetchSpy).toHaveBeenCalledTimes(3);
- expect(sentPatterns(fetchSpy, 0)).toHaveLength(30);
- expect(sentPatterns(fetchSpy, 1)).toHaveLength(30);
- expect(sentPatterns(fetchSpy, 2)).toHaveLength(5);
+ expect(chunkSizes).toEqual([30, 30, 5]);
});
it('stops at the first chunk that fails so the whole batch is retried', async () => {
- fetchSpy
- .mockResolvedValueOnce(new Response(null, {status: 202}))
- .mockResolvedValueOnce(new Response(null, {status: 503}));
+ const chunkSizes = serveController([202, 503]);
const outcome = await createControllerCachePurgeAdapter(CONFIG).purge(prefixes(90));
expect(outcome).toEqual({kind: 'failed', status: 503, error: null});
- expect(fetchSpy).toHaveBeenCalledTimes(2);
+ expect(chunkSizes).toEqual([30, 30]);
});
});
diff --git a/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts b/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts
index 373984674..d049e3281 100644
--- a/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts
+++ b/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.test.ts
@@ -3,45 +3,28 @@
import {createUserID, type UserID} from '@app/api/BrandedTypes';
import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
import {KVBulkMessageDeletionQueueService} from '@app/api/infrastructure/KVBulkMessageDeletionQueueService';
-import {User} from '@app/api/models/User';
-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {createTestWorkerHelpers, SyncTaskWorkerService} from '@app/api/test/SyncTaskWorkerService';
+import {UserRepository} from '@app/api/user/repositories/UserRepository';
import processPendingBulkMessageDeletions from '@app/api/worker/tasks/ProcessPendingBulkMessageDeletions';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {afterEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, describe, expect, test} from 'vitest';
-function createUser(userId: UserID, pendingBulkMessageDeletionAt: Date | null): User {
- return new User({
- ...EMPTY_USER_ROW,
- user_id: userId,
- username: `user${userId}`,
- pending_bulk_message_deletion_at: pendingBulkMessageDeletionAt,
- });
-}
-
-function createHarness(users: Array<User>) {
+async function createHarness(users: Array<{userId: UserID; pendingAt: Date | null}>) {
const kvClient = new MockKVProvider();
- const scanCalls: Array<number> = [];
- const userRepository = {
- async scanAllUsersPage(limit: number): Promise<{users: Array<User>; pageState: null}> {
- scanCalls.push(limit);
- return {users, pageState: null};
- },
- async findUnique(userId: UserID): Promise<User | null> {
- return users.find((user) => user.id === userId) ?? null;
- },
- } as unknown as UserRepository;
- const jobs: Array<{name: string; payload: unknown}> = [];
- const workerService = {
- async addJob(name: string, payload: unknown): Promise<bigint> {
- jobs.push({name, payload});
- return 0n;
- },
- } as unknown as WorkerDependencies['workerService'];
+ const userRepository = new UserRepository();
+ for (const {userId, pendingAt} of users) {
+ await userRepository.create({
+ ...EMPTY_USER_ROW,
+ user_id: userId,
+ username: `user${userId}`,
+ pending_bulk_message_deletion_at: pendingAt,
+ });
+ }
+ const workerService = new SyncTaskWorkerService({}, {deferred: true});
const bulkMessageDeletionQueueService = new KVBulkMessageDeletionQueueService(kvClient, userRepository);
setWorkerDependenciesForTest({bulkMessageDeletionQueueService, userRepository, workerService});
- return {kvClient, scanCalls, jobs, bulkMessageDeletionQueueService};
+ return {kvClient, workerService, bulkMessageDeletionQueueService};
}
describe('processPendingBulkMessageDeletions', () => {
@@ -51,7 +34,7 @@ describe('processPendingBulkMessageDeletions', () => {
test('replaces the old sorted-set member when a user is rescheduled', async () => {
const userId = createUserID(1234n);
- const harness = createHarness([]);
+ const harness = await createHarness([]);
const oldAt = new Date(1_700_000_000_000);
const newAt = new Date(oldAt.getTime() + 60_000);
await harness.bulkMessageDeletionQueueService.scheduleDeletion(userId, oldAt);
@@ -67,29 +50,28 @@ describe('processPendingBulkMessageDeletions', () => {
test('rebuilds the queue from the users table when the state version is missing', async () => {
const userId = createUserID(1234n);
const scheduledAt = new Date(Date.now() - 60_000);
- const harness = createHarness([createUser(userId, scheduledAt)]);
+ const harness = await createHarness([{userId, pendingAt: scheduledAt}]);
await processPendingBulkMessageDeletions({}, createTestWorkerHelpers());
- expect(harness.scanCalls).toEqual([1000]);
- expect(harness.jobs).toEqual([
+ expect(harness.workerService.pending.map(({taskType, payload}) => ({taskType, payload}))).toEqual([
{
- name: 'bulkDeleteUserMessages',
+ taskType: 'bulkDeleteUserMessages',
payload: {userId: userId.toString(), scheduledAt: scheduledAt.getTime()},
},
]);
- expect((await harness.kvClient.exists('bulk_message_deletion_queue:state_version')) === 1).toBe(true);
+ expect(await harness.kvClient.exists('bulk_message_deletion_queue:state_version')).toBe(1);
});
test('skips the run when another worker holds the rebuild lock', async () => {
const userId = createUserID(9012n);
- const harness = createHarness([createUser(userId, new Date(Date.now() - 60_000))]);
+ const harness = await createHarness([{userId, pendingAt: new Date(Date.now() - 60_000)}]);
await harness.kvClient.set('bulk_message_deletion_queue:rebuild_lock', 'other-worker');
await processPendingBulkMessageDeletions({}, createTestWorkerHelpers());
- expect(harness.scanCalls).toEqual([]);
- expect(harness.jobs).toEqual([]);
+ expect(harness.workerService.pending).toEqual([]);
+ expect(await harness.bulkMessageDeletionQueueService.getQueueSize()).toBe(0);
expect(await harness.kvClient.get('bulk_message_deletion_queue:rebuild_lock')).toBe('other-worker');
});
});
diff --git a/fluxer_api/src/api/infrastructure/StorageService.test.ts b/fluxer_api/src/api/infrastructure/StorageService.test.ts
index 0d60e16f6..310bfe161 100644
--- a/fluxer_api/src/api/infrastructure/StorageService.test.ts
+++ b/fluxer_api/src/api/infrastructure/StorageService.test.ts
@@ -1,9 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {PassThrough, Readable} from 'node:stream';
import {Config} from '@app/api/Config';
import {StorageObjectListingOverflowError} from '@app/api/infrastructure/IStorageService';
import {StorageService} from '@app/api/infrastructure/StorageService';
+import {server} from '@app/api/test/msw/server';
+import {HttpResponse, http} from 'msw';
import {describe, expect, it} from 'vitest';
interface S3BucketConfigOverrides {
@@ -70,187 +71,122 @@ describe('StorageService.getPresignedUploadURL', () => {
},
);
});
-
- it('gives both clients the configured addressing rather than pinning one to path style', async () => {
- await withS3Config(
- {
- endpoint: 'https://s3.example.test',
- presignedUrlBase: '',
- forcePathStyle: false,
- region: 'eu-central-1',
- accessKeyId: 'fluxer',
- secretAccessKey: 'fluxer-secret',
- buckets: {uploads: 'fluxer-uploads'},
- },
- async () => {
- const service = new StorageService();
- const probe = service as unknown as {
- client: {config: {forcePathStyle?: unknown}};
- presignClient: {config: {forcePathStyle?: unknown}};
- };
- const resolve = async (value: unknown): Promise<unknown> =>
- typeof value === 'function' ? await (value as () => Promise<unknown>)() : value;
-
- expect(await resolve(probe.client.config.forcePathStyle)).toBe(false);
- expect(await resolve(probe.presignClient.config.forcePathStyle)).toBe(false);
- },
- );
- });
});
-function bodyStream(chunks: Array<Buffer>): PassThrough {
- const stream = new PassThrough();
- const writeChunk = (index: number): void => {
- if (stream.destroyed) {
- return;
- }
- const chunk = chunks[index];
- if (chunk === undefined) {
- stream.end();
- return;
- }
- stream.write(chunk);
- setImmediate(() => writeChunk(index + 1));
- };
- writeChunk(0);
- return stream;
+function createService(endpoint = 'http://s3.test', forcePathStyle = true): StorageService {
+ return new StorageService({
+ endpoint,
+ forcePathStyle,
+ region: 'us-east-1',
+ accessKeyId: 'fluxer',
+ secretAccessKey: 'fluxer-secret',
+ });
}
-function serveGetObject(service: StorageService, out: {Body: PassThrough; ContentLength?: number}): void {
- Object.assign(service, {client: {send: async () => out}});
+const OBJECT_URL = 'http://s3.test/fluxer-downloads/desktop/stable/manifest.json';
+
+function serveObject(body: Uint8Array, headers: Record<string, string> = {}): void {
+ server.use(http.get(OBJECT_URL, () => new HttpResponse(body, {headers})));
}
describe('StorageService.readObject', () => {
it('refuses an object whose declared length is already over the cap', async () => {
- const service = new StorageService();
- const body = bodyStream([Buffer.alloc(64, 1)]);
- serveGetObject(service, {Body: body, ContentLength: 64});
-
- await expect(service.readObject('fluxer-downloads', 'desktop/stable/manifest.json', 32)).rejects.toThrow(
+ serveObject(new Uint8Array(64).fill(1), {'content-length': '64'});
+ await expect(createService().readObject('fluxer-downloads', 'desktop/stable/manifest.json', 32)).rejects.toThrow(
/exceeds maximum buffer size of 32 bytes \(got 64 bytes\)/u,
);
- expect(body.destroyed).toBe(true);
});
- it('refuses an object that outgrows the cap mid-stream when no length is declared', async () => {
- const service = new StorageService();
- const body = bodyStream([Buffer.alloc(24, 1), Buffer.alloc(24, 2)]);
- serveGetObject(service, {Body: body});
-
- await expect(service.readObject('fluxer-downloads', 'desktop/stable/manifest.json', 32)).rejects.toThrow(
- /exceeds maximum buffer size of 32 bytes \(got at least 48 bytes\)/u,
+ it('refuses an object that outgrows the cap when no length is declared', async () => {
+ server.use(
+ http.get(OBJECT_URL, () => {
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array(24).fill(1));
+ controller.enqueue(new Uint8Array(24).fill(2));
+ controller.close();
+ },
+ });
+ return new HttpResponse(stream);
+ }),
+ );
+ await expect(createService().readObject('fluxer-downloads', 'desktop/stable/manifest.json', 32)).rejects.toThrow(
+ /exceeds maximum buffer size of 32 bytes/u,
);
- expect(body.destroyed).toBe(true);
});
it('returns every byte of an object that exactly fills the cap', async () => {
- const service = new StorageService();
- serveGetObject(service, {Body: bodyStream([Buffer.alloc(16, 7), Buffer.alloc(16, 9)])});
-
- await expect(service.readObject('fluxer-downloads', 'desktop/stable/manifest.json', 32)).resolves.toEqual(
- new Uint8Array([...Array(16).fill(7), ...Array(16).fill(9)]),
+ const bytes = new Uint8Array([...Array(16).fill(7), ...Array(16).fill(9)]);
+ serveObject(bytes, {'content-length': '32'});
+ await expect(createService().readObject('fluxer-downloads', 'desktop/stable/manifest.json', 32)).resolves.toEqual(
+ bytes,
);
});
-
- it('rejects rather than hanging when the object store resets the body mid-transfer', async () => {
- const service = new StorageService();
- const reset = new Error('socket hang up');
- const body = new Readable({read() {}});
- Object.assign(service, {client: {send: async () => ({Body: body})}});
- const read = service.readObject('fluxer-downloads', 'desktop/stable/manifest.json', 1024);
- body.push(Buffer.alloc(8, 1));
- setImmediate(() => body.destroy(reset));
-
- await expect(read).rejects.toThrow(/socket hang up/u);
- }, 5000);
});
-interface ListObjectsPage {
- Contents?: Array<{Key: string; LastModified?: Date}>;
- IsTruncated?: boolean;
- NextContinuationToken?: string;
+function listingXml(keys: Array<string>, nextToken?: string | null): string {
+ const contents = keys.map((key) => `<Contents><Key>${key}</Key></Contents>`).join('');
+ const truncated = nextToken !== undefined;
+ const next = nextToken ? `<NextContinuationToken>${nextToken}</NextContinuationToken>` : '';
+ return `<?xml version="1.0" encoding="UTF-8"?><ListBucketResult><Name>fluxer-downloads</Name><Prefix>desktop/</Prefix><IsTruncated>${truncated}</IsTruncated>${next}${contents}</ListBucketResult>`;
}
-function serveListPages(service: StorageService, pages: Array<ListObjectsPage>): {tokens: Array<string | undefined>} {
- const tokens: Array<string | undefined> = [];
- let index = 0;
- Object.assign(service, {
- client: {
- send: async (command: {input: {ContinuationToken?: string}}) => {
- tokens.push(command.input.ContinuationToken);
- const page = pages[index] ?? {};
- index += 1;
- return page;
- },
- },
- });
- return {tokens};
+function serveListing(pages: Array<string>): Array<string | null> {
+ const tokens: Array<string | null> = [];
+ server.use(
+ http.get('http://s3.test/fluxer-downloads', ({request}) => {
+ tokens.push(new URL(request.url).searchParams.get('continuation-token'));
+ const page = pages[tokens.length - 1] ?? listingXml([]);
+ return new HttpResponse(page, {headers: {'content-type': 'application/xml'}});
+ }),
+ );
+ return tokens;
}
describe('StorageService.listObjects', () => {
it('returns every page of a truncated listing', async () => {
- const service = new StorageService();
- const {tokens} = serveListPages(service, [
- {
- Contents: [{Key: 'desktop/a.exe'}, {Key: 'desktop/b.exe'}],
- IsTruncated: true,
- NextContinuationToken: 'page-2',
- },
- {Contents: [{Key: 'desktop/c.exe'}], IsTruncated: false},
+ const tokens = serveListing([
+ listingXml(['desktop/a.exe', 'desktop/b.exe'], 'page-2'),
+ listingXml(['desktop/c.exe']),
]);
- const objects = await service.listObjects({bucket: 'fluxer-downloads', prefix: 'desktop/'});
+ const objects = await createService().listObjects({bucket: 'fluxer-downloads', prefix: 'desktop/'});
expect(objects.map(({key}) => key)).toEqual(['desktop/a.exe', 'desktop/b.exe', 'desktop/c.exe']);
- expect(tokens).toEqual([undefined, 'page-2']);
+ expect(tokens).toEqual([null, 'page-2']);
});
it('throws a typed overflow error when the prefix outgrows the requested cap', async () => {
- const service = new StorageService();
- serveListPages(service, [
- {
- Contents: [{Key: 'desktop/a.exe'}, {Key: 'desktop/b.exe'}],
- IsTruncated: true,
- NextContinuationToken: 'page-2',
- },
- ]);
+ serveListing([listingXml(['desktop/a.exe', 'desktop/b.exe'], 'page-2')]);
await expect(
- service.listObjects({bucket: 'fluxer-downloads', prefix: 'desktop/', maxObjects: 2}),
+ createService().listObjects({bucket: 'fluxer-downloads', prefix: 'desktop/', maxObjects: 2}),
).rejects.toBeInstanceOf(StorageObjectListingOverflowError);
});
it('throws rather than returning a partial listing when the continuation token is missing', async () => {
- const service = new StorageService();
- serveListPages(service, [{Contents: [{Key: 'desktop/a.exe'}], IsTruncated: true}]);
- await expect(service.listObjects({bucket: 'fluxer-downloads', prefix: 'desktop/'})).rejects.toThrow(
+ serveListing([listingXml(['desktop/a.exe'], null)]);
+ await expect(createService().listObjects({bucket: 'fluxer-downloads', prefix: 'desktop/'})).rejects.toThrow(
/continuation token/u,
);
});
});
-function copySourceFor(endpoint: string, forcePathStyle: boolean): Promise<unknown> {
- const service = new StorageService({
- endpoint,
- forcePathStyle,
- region: 'us-east-1',
- accessKeyId: 'fluxer',
- secretAccessKey: 'fluxer-secret',
- });
- let copySource: unknown;
- Object.assign(service, {
- client: {
- send: async (command: {input: {CopySource?: unknown}}) => {
- copySource = command.input.CopySource;
- return {};
- },
- },
+async function copySourceFor(endpoint: string, forcePathStyle: boolean): Promise<string | null> {
+ let copySource: string | null = null;
+ server.use(
+ http.put('*', ({request}) => {
+ copySource = request.headers.get('x-amz-copy-source');
+ return new HttpResponse(
+ '<?xml version="1.0" encoding="UTF-8"?><CopyObjectResult><ETag>"etag"</ETag></CopyObjectResult>',
+ {headers: {'content-type': 'application/xml'}},
+ );
+ }),
+ );
+ await createService(endpoint, forcePathStyle).copyObject({
+ sourceBucket: 'fluxer-uploads',
+ sourceKey: 'a b/c+d.pdf',
+ destinationBucket: 'fluxer-cdn',
+ destinationKey: 'attachments/1/2/c.pdf',
});
- return service
- .copyObject({
- sourceBucket: 'fluxer-uploads',
- sourceKey: 'a b/c+d.pdf',
- destinationBucket: 'fluxer-cdn',
- destinationKey: 'attachments/1/2/c.pdf',
- })
- .then(() => copySource);
+ return copySource;
}
describe('StorageService.copyObject copy source', () => {
diff --git a/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuild.test.ts b/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuild.test.ts
index 73bb73f6f..c54d50ed2 100644
--- a/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuild.test.ts
+++ b/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuild.test.ts
@@ -1,47 +1,47 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createUserID} from '@app/api/BrandedTypes';
+import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';
import {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
-import {User} from '@app/api/models/User';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
+import {UserRepository} from '@app/api/user/repositories/UserRepository';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {describe, expect, it} from 'vitest';
-function createUser(id: bigint, overrides: Partial<Pick<UserRow, 'bot' | 'flags'>> = {}): User {
- return new User({
+function userRow(id: bigint, overrides: Partial<Pick<UserRow, 'bot' | 'flags'>> = {}): UserRow {
+ return {
...EMPTY_USER_ROW,
user_id: createUserID(id),
- pending_deletion_at: new Date('2026-06-01T00:00:00.000Z'),
- deletion_reason_code: 0,
bot: overrides.bot ?? false,
flags: overrides.flags ?? 0n,
- });
-}
-
-function createUserRepository(users: Array<User>): UserRepository {
- let served = false;
- return {
- async scanAllUsersPage() {
- if (served) {
- return {users: [], pageState: null};
- }
- served = true;
- return {users, pageState: null};
- },
- } as unknown as UserRepository;
+ };
}
describe('KVAccountDeletionQueueService rebuild', () => {
it('does not requeue accounts the deletion worker refuses to process', async () => {
+ setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
const kvClient = new MockKVProvider();
- const users = [createUser(1n, {bot: true}), createUser(2n, {flags: UserFlags.APP_STORE_REVIEWER}), createUser(3n)];
- const service = new KVAccountDeletionQueueService(kvClient, createUserRepository(users));
+ const userRepository = new UserRepository(kvClient);
+ for (const row of [
+ userRow(1400000000000000001n, {bot: true}),
+ userRow(1400000000000000002n, {flags: UserFlags.APP_STORE_REVIEWER}),
+ userRow(1400000000000000003n),
+ ]) {
+ const user = await userRepository.create(row);
+ await userRepository.updateDeletionSchedule(user, {
+ pending_deletion_at: new Date('2026-06-01T00:00:00.000Z'),
+ deletion_reason_code: 0,
+ });
+ }
+ const service = new KVAccountDeletionQueueService(kvClient, userRepository);
await service.rebuildState();
expect(await service.getQueueSize()).toBe(1);
- expect(await service.getReadyDeletions(Date.now(), 100)).toEqual([{userId: 3n, deletionReasonCode: 0}]);
+ expect(await service.getReadyDeletions(Date.now(), 100)).toEqual([
+ {userId: 1400000000000000003n, deletionReasonCode: 0},
+ ]);
});
});
diff --git a/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuildLock.test.ts b/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuildLock.test.ts
deleted file mode 100644
index 277dd3ea4..000000000
--- a/fluxer_api/src/api/infrastructure/tests/KVAccountDeletionQueueRebuildLock.test.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createUserID} from '@app/api/BrandedTypes';
-import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
-import {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
-import {User} from '@app/api/models/User';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {ms} from 'itty-time';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-const PAGE_DURATION_MS = ms('3 minutes');
-const PAGE_COUNT = 3;
-
-function createPendingUser(index: number): User {
- return new User({
- ...EMPTY_USER_ROW,
- user_id: createUserID(BigInt(7000 + index)),
- pending_deletion_at: new Date('2026-06-01T00:00:00.000Z'),
- deletion_reason_code: 0,
- bot: false,
- flags: 0n,
- });
-}
-
-function createSlowUserRepository(): UserRepository {
- let page = 0;
- return {
- async scanAllUsersPage() {
- vi.advanceTimersByTime(PAGE_DURATION_MS);
- page += 1;
- return {
- users: [createPendingUser(page)],
- pageState: page < PAGE_COUNT ? `page-${page}` : null,
- };
- },
- } as unknown as UserRepository;
-}
-
-describe('KVAccountDeletionQueueService rebuild lock', () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('keeps holding the rebuild lock across a scan longer than the lock ttl', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-06-01T00:00:00.000Z'));
- const kvClient = new MockKVProvider();
- const service = new KVAccountDeletionQueueService(kvClient, createSlowUserRepository());
- const token = await service.acquireRebuildLock();
- expect(token).not.toBeNull();
-
- await service.rebuildState(token);
-
- expect(await service.acquireRebuildLock()).toBeNull();
- expect(await service.releaseRebuildLock(token!)).toBe(true);
- });
-});
diff --git a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts b/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts
deleted file mode 100644
index d99582cfb..000000000
--- a/fluxer_api/src/api/infrastructure/tests/LiveKitWebhookService.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createChannelID, createGuildID} from '@app/api/BrandedTypes';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
-import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
-import {SERVER_MUTE_ATTRIBUTE} from '@app/api/infrastructure/LiveKitService';
-import {LiveKitWebhookService} from '@app/api/infrastructure/LiveKitWebhookService';
-import type {VoiceRepository} from '@app/api/voice/VoiceRepository';
-import {VoiceTopology} from '@app/api/voice/VoiceTopology';
-import {TrackSource, type WebhookEvent} from 'livekit-server-sdk';
-import {describe, expect, it, vi} from 'vitest';
-
-const GUILD_ID = createGuildID(1n);
-const CHANNEL_ID = createChannelID(2n);
-
-function trackPublished(source: TrackSource, attributes: Record<string, string>): WebhookEvent {
- return {
- event: 'track_published',
- room: {name: `guild_${GUILD_ID}_channel_${CHANNEL_ID}`},
- participant: {
- identity: 'user_3_conn-1',
- attributes,
- metadata: JSON.stringify({
- user_id: '3',
- channel_id: CHANNEL_ID.toString(),
- guild_id: GUILD_ID.toString(),
- connection_id: 'conn-1',
- region_id: 'eu',
- server_id: 'eu-1',
- token_nonce: 'nonce',
- issued_at: '0',
- }),
- },
- track: {sid: 'TR_new', source},
- } as unknown as WebhookEvent;
-}
-
-function trackHarness() {
- const muteMicrophoneTrack = vi.fn(async () => {});
- const service = new LiveKitWebhookService(
- {} as unknown as IVoiceRoomStore,
- {} as unknown as IGatewayService,
- {muteMicrophoneTrack} as unknown as ILiveKitService,
- new VoiceTopology({} as unknown as VoiceRepository, null),
- );
- return {service, muteMicrophoneTrack};
-}
-
-describe('LiveKitWebhookService track_published', () => {
- it('mutes a microphone published by a participant the guild has muted', async () => {
- const {service, muteMicrophoneTrack} = trackHarness();
-
- await service.processEvent({
- event: trackPublished(TrackSource.MICROPHONE, {[SERVER_MUTE_ATTRIBUTE]: 'true'}),
- apiKey: 'key',
- });
-
- expect(muteMicrophoneTrack).toHaveBeenCalledWith({
- guildId: GUILD_ID,
- channelId: CHANNEL_ID,
- userId: 3n,
- connectionId: 'conn-1',
- regionId: 'eu',
- serverId: 'eu-1',
- trackSid: 'TR_new',
- });
- });
-
- it('leaves a microphone alone when the participant is not muted by the guild', async () => {
- const {service, muteMicrophoneTrack} = trackHarness();
-
- await service.processEvent({event: trackPublished(TrackSource.MICROPHONE, {}), apiKey: 'key'});
-
- expect(muteMicrophoneTrack).not.toHaveBeenCalled();
- });
-
- it('leaves other track sources alone', async () => {
- const {service, muteMicrophoneTrack} = trackHarness();
-
- await service.processEvent({
- event: trackPublished(TrackSource.CAMERA, {[SERVER_MUTE_ATTRIBUTE]: 'true'}),
- apiKey: 'key',
- });
-
- expect(muteMicrophoneTrack).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts
index 94f6834fc..8e20d0565 100644
--- a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts
+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts
@@ -14,7 +14,7 @@ import {ensureSetupToken, isSetupTokenEnforced} from '@app/api/instance/SetupTok
import {InstanceConfigWriteRaceExecutor} from '@app/api/instance/tests/InstanceConfigWriteRaceExecutor';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
const REGISTRATION_CONFIG_KEY = 'registration_config';
const REGISTRATION_URLS_KEY = 'registration_urls';
@@ -693,7 +693,8 @@ describe('InstanceConfigRepository setup token', () => {
});
it('confirms the admin bootstrap against the database and repairs a stale snapshot', async () => {
- const stale = createPod();
+ const stale = new InstanceConfigRepository(new MockKVProvider());
+ repositories.push(stale);
const writer = createPod();
expect(await stale.isAdminBootstrapped()).toBe(false);
await writer.claimAdminBootstrap();
@@ -708,9 +709,12 @@ describe('InstanceConfigRepository setup token', () => {
it('refuses to start when the setup token cannot be stored', async () => {
useSelfHostedProduction();
- const pod = createPod();
- vi.spyOn(pod, 'createSetupTokenIfAbsent').mockRejectedValueOnce(new Error('database down'));
- await expect(ensureSetupToken(pod, accountExists)).rejects.toThrow('database down');
+ executor.watch(SETUP_TOKEN_HASH_KEY);
+ executor.competeBeforeEachWrite(async () => {
+ throw new Error('database down');
+ });
+ await expect(ensureSetupToken(createPod(), accountExists)).rejects.toThrow('database down');
+ expect(await executor.readDirectly(SETUP_TOKEN_HASH_KEY)).toBeNull();
});
});
diff --git a/fluxer_api/src/api/instance/InstanceController.test.ts b/fluxer_api/src/api/instance/InstanceController.test.ts
index b45d650c1..404bbc6d7 100644
--- a/fluxer_api/src/api/instance/InstanceController.test.ts
+++ b/fluxer_api/src/api/instance/InstanceController.test.ts
@@ -1,98 +1,67 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {SsoService} from '@app/api/auth/services/SsoService';
+import {createAuthHarness} from '@app/api/auth/tests/AuthTestUtils';
import {Config} from '@app/api/Config';
-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
-import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
-import {InstanceController} from '@app/api/instance/InstanceController';
-import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
-import type {HonoEnv} from '@app/api/types/HonoEnv';
+import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {DEFAULT_DOMAIN_MIGRATION_CONFIG} from '@fluxer/schema/src/domains/admin/DomainMigrationSchemas';
-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {Hono} from 'hono';
-import {afterEach, describe, expect, it} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
-describe('InstanceController discovery captcha', () => {
- const repositories: Array<InstanceConfigRepository> = [];
+interface DiscoveryResponse {
+ captcha: {provider: string};
+ features: {discovery_enabled?: boolean};
+ domain_migration: unknown;
+}
+describe('InstanceController discovery', () => {
+ let harness: ApiTestHarness;
+ let repository: InstanceConfigRepository;
+ const previousDiscoveryEnabled = Config.discovery.enabled;
+
+ beforeAll(async () => {
+ harness = await createAuthHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ repository = getInstanceConfigRepository();
+ });
afterEach(() => {
- for (const repository of repositories) {
- repository.shutdown();
- }
- repositories.length = 0;
+ Config.discovery.enabled = previousDiscoveryEnabled;
+ repository.clearCacheForTesting();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
});
- function createRepository(): InstanceConfigRepository {
- setCassandraQueryExecutorForTesting(new InMemoryCassandraQueryExecutor());
- const repository = new InstanceConfigRepository(new MockKVProvider());
- repositories.push(repository);
- return repository;
- }
-
- function createApp(repository: InstanceConfigRepository): Hono<HonoEnv> {
- const app = new Hono<HonoEnv>({strict: true});
- app.use('*', async (ctx, next) => {
- ctx.set('instanceConfigRepository', repository);
- ctx.set('limitConfigService', {
- getConfigWireFormat: () => ({version: 2, traitDefinitions: [], rules: [], defaultsHash: 'test'}),
- } as unknown as LimitConfigService);
- ctx.set('ssoService', {
- getPublicStatus: async () => ({
- enabled: false,
- enforced: false,
- display_name: null,
- button_label: null,
- redirect_uri: '',
- }),
- } as unknown as SsoService);
- await next();
- });
- InstanceController(app);
- return app;
- }
-
- async function readCaptcha(repository: InstanceConfigRepository): Promise<DiscoveryCaptcha> {
- const response = await createApp(repository).request('http://localhost/.well-known/fluxer');
- expect(response.status).toBe(200);
- return ((await response.json()) as {captcha: DiscoveryCaptcha}).captcha;
+ async function fetchDiscovery() {
+ const result = await createBuilderWithoutAuth<DiscoveryResponse>(harness).get('/.well-known/fluxer').executeRaw();
+ expect(result.response.status).toBe(200);
+ return result;
}
it('advertises altcha by default', async () => {
- await expect(readCaptcha(createRepository())).resolves.toEqual({provider: 'altcha'});
+ expect((await fetchDiscovery()).json.captcha).toEqual({provider: 'altcha'});
});
it('advertises no provider once an admin turns the captcha off', async () => {
await repository.updateCaptchaConfig({enabled: false});
- await expect(readCaptcha(repository)).resolves.toEqual({provider: 'none'});
+ expect((await fetchDiscovery()).json.captcha).toEqual({provider: 'none'});
});
it('publishes whether discovery is enabled', async () => {
- const previousDiscoveryEnabled = Config.discovery.enabled;
- const app = createApp(createRepository());
- const readDiscoveryEnabled = async () => {
- const response = await app.request('http://localhost/.well-known/fluxer');
- expect(response.status).toBe(200);
- return ((await response.json()) as {features: {discovery_enabled?: boolean}}).features.discovery_enabled;
- };
- try {
- Config.discovery.enabled = false;
- await expect(readDiscoveryEnabled()).resolves.toBe(false);
+ Config.discovery.enabled = false;
+ expect((await fetchDiscovery()).json.features.discovery_enabled).toBe(false);
- Config.discovery.enabled = true;
- await expect(readDiscoveryEnabled()).resolves.toBe(true);
- } finally {
- Config.discovery.enabled = previousDiscoveryEnabled;
- }
+ Config.discovery.enabled = true;
+ expect((await fetchDiscovery()).json.features.discovery_enabled).toBe(true);
});
it('publishes the domain migration kill switch and anonymous rollout without the targeting lists', async () => {
- const repository = createRepository();
- const app = createApp(repository);
-
- const initial = await app.request('http://localhost/.well-known/fluxer');
- expect(((await initial.json()) as {domain_migration: unknown}).domain_migration).toEqual({
+ const initial = await fetchDiscovery();
+ expect(initial.json.domain_migration).toEqual({
enabled: false,
anonymous_rollout_basis_points: 0,
rollout_salt: 'domain-migration-v1',
@@ -109,9 +78,9 @@ describe('InstanceController discovery captcha', () => {
standalone_forwarding: true,
});
- const updated = await app.request('http://localhost/.well-known/fluxer');
- expect(updated.headers.get('etag')).not.toBe(initial.headers.get('etag'));
- expect(((await updated.json()) as {domain_migration: unknown}).domain_migration).toEqual({
+ const updated = await fetchDiscovery();
+ expect(updated.response.headers.get('etag')).not.toBe(initial.response.headers.get('etag'));
+ expect(updated.json.domain_migration).toEqual({
enabled: true,
anonymous_rollout_basis_points: 1500,
rollout_salt: 'domain-migration-v1',
diff --git a/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts b/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts
index 80db0435e..8c6d0834f 100644
--- a/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts
+++ b/fluxer_api/src/api/instance/tests/AccountIdentityMode.test.ts
@@ -5,14 +5,14 @@ import {createAuthHarness, createTestAccount, setUserACLs} from '@app/api/auth/t
import {getConfig} from '@app/api/Config';
import {getCachedAccountIdentityMode} from '@app/api/instance/AccountIdentityModeCache';
import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
-import {getCacheService, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {AccountIdentityModes} from '@fluxer/constants/src/AccountIdentityConstants';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const ACCOUNT_IDENTITY_CONFIG_KEY = 'account_identity_config';
const SETUP_TOKEN = 'setup-token-for-tests-0123456789-abcdefghijklmnopqrstuvwxyz';
diff --git a/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts b/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
index 994452975..fc72da02f 100644
--- a/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
+++ b/fluxer_api/src/api/instance/tests/DiscoverySelfHostFields.test.ts
@@ -1,35 +1,37 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import type {SsoService} from '@app/api/auth/services/SsoService';
-import {getConfig} from '@app/api/Config';
-import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
-import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
-import {InstanceController} from '@app/api/instance/InstanceController';
-import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
-import type {HonoEnv} from '@app/api/types/HonoEnv';
+import {createAuthHarness} from '@app/api/auth/tests/AuthTestUtils';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
+import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {parseInstanceDiscoveryDocument} from '@fluxer/instance_bootstrap/src/Discovery';
import type {WellKnownFluxerResponse} from '@fluxer/schema/src/domains/instance/InstanceSchemas';
-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import {Hono} from 'hono';
-import {afterEach, describe, expect, it} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('discovery fields for self-hosted clients', () => {
- const repositories: Array<InstanceConfigRepository> = [];
- const discoveryEnabled = getConfig().discovery.enabled;
+ let harness: ApiTestHarness;
+ beforeAll(async () => {
+ harness = await createAuthHarness();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ });
afterEach(() => {
- getConfig().discovery.enabled = discoveryEnabled;
- for (const repository of repositories) {
- repository.shutdown();
- }
- repositories.length = 0;
+ getInstanceConfigRepository().clearCacheForTesting();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
});
it('keeps friend requests off on an instance that turned direct messages off before the split', async () => {
- const repository = createRepository();
- await repository.setConfig('instance_policy_config', JSON.stringify({direct_messages_disabled: true}));
- const discovery = await readDiscovery(repository);
+ await getInstanceConfigRepository().setConfig(
+ 'instance_policy_config',
+ JSON.stringify({direct_messages_disabled: true}),
+ );
+ const discovery = await createBuilderWithoutAuth<WellKnownFluxerResponse>(harness)
+ .get('/.well-known/fluxer')
+ .execute();
expect(discovery.community).toMatchObject({direct_messages_disabled: true, friends_disabled: true});
});
diff --git a/fluxer_api/src/api/middleware/tests/BlocklistSeverityLabel.test.ts b/fluxer_api/src/api/middleware/tests/BlocklistSeverityLabel.test.ts
index cbaa3e760..19d65cfeb 100644
--- a/fluxer_api/src/api/middleware/tests/BlocklistSeverityLabel.test.ts
+++ b/fluxer_api/src/api/middleware/tests/BlocklistSeverityLabel.test.ts
@@ -5,7 +5,7 @@ import {ContentBlocklistCategory, ContentBlocklistSeverity} from '@app/api/const
import {bannedAvatarHashCache} from '@app/api/middleware/BannedAvatarHashCache';
import {fileShaCache} from '@app/api/middleware/FileShaCache';
import {urlBlocklistCache} from '@app/api/middleware/UrlBlocklistCache';
-import {afterEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, describe, expect, it} from 'vitest';
const SEVERITIES = [
['allow', ContentBlocklistSeverity.ALLOW],
@@ -28,19 +28,15 @@ const rowMeta = {
describe('blocklist severity is a stored label', () => {
afterEach(() => {
- vi.restoreAllMocks();
urlBlocklistCache.resetForTesting();
fileShaCache.resetForTesting();
bannedAvatarHashCache.resetForTesting();
});
it.each(SEVERITIES)('a %s url row and url domain row still block', async (_label, severity) => {
- vi.spyOn(AdminRepository.prototype, 'loadAllBannedUrls').mockResolvedValue([
- {...rowMeta, url_canonical: 'https://blocked.example/path', severity},
- ]);
- vi.spyOn(AdminRepository.prototype, 'loadAllBannedUrlDomains').mockResolvedValue([
- {...rowMeta, domain: 'blocked-domain.example', match_subdomains: true, severity},
- ]);
+ const repository = new AdminRepository();
+ await repository.banUrl({...rowMeta, url_canonical: 'https://blocked.example/path', severity});
+ await repository.banUrlDomain({...rowMeta, domain: 'blocked-domain.example', match_subdomains: true, severity});
await urlBlocklistCache.refresh();
expect(urlBlocklistCache.size.urls).toBe(1);
expect(urlBlocklistCache.isUrlBanned('https://blocked.example/path')).toBe(true);
@@ -50,9 +46,12 @@ describe('blocklist severity is a stored label', () => {
});
it.each(SEVERITIES)('a %s file sha row still blocks', async (_label, severity) => {
- vi.spyOn(AdminRepository.prototype, 'loadAllBannedFileShas').mockResolvedValue([
- {...rowMeta, sha256_hex: FILE_SHA.toUpperCase(), content_type: 'image/png', severity},
- ]);
+ await new AdminRepository().banFileSha({
+ ...rowMeta,
+ sha256_hex: FILE_SHA.toUpperCase(),
+ content_type: 'image/png',
+ severity,
+ });
await fileShaCache.refresh();
expect(fileShaCache.size).toBe(1);
expect(fileShaCache.isBanned(FILE_SHA)).toBe(true);
@@ -60,9 +59,7 @@ describe('blocklist severity is a stored label', () => {
});
it.each(SEVERITIES)('a %s avatar hash row still blocks', async (_label, severity) => {
- vi.spyOn(AdminRepository.prototype, 'loadAllBannedAvatarHashes').mockResolvedValue([
- {...rowMeta, hash_short: AVATAR_HASH, severity},
- ]);
+ await new AdminRepository().banAvatarHash({...rowMeta, hash_short: AVATAR_HASH, severity});
await bannedAvatarHashCache.refresh();
expect(bannedAvatarHashCache.size).toBe(1);
expect(bannedAvatarHashCache.isBanned(AVATAR_HASH)).toBe(true);
diff --git a/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts
index 6db2ae9ba..4e7ca47d6 100644
--- a/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts
+++ b/fluxer_api/src/api/middleware/tests/CaptchaMiddleware.test.ts
@@ -2,6 +2,7 @@
import {Config} from '@app/api/Config';
import {CaptchaMiddleware} from '@app/api/middleware/CaptchaMiddleware';
+import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {CAPTCHA_TEST_HEADER} from '@app/api/test/CaptchaTestUtils';
import type {HonoEnv} from '@app/api/types/HonoEnv';
import {CaptchaProviders} from '@fluxer/constants/src/CaptchaConstants';
@@ -12,10 +13,9 @@ import {afterEach, beforeEach, describe, expect, it} from 'vitest';
const CHEAP_CAPTCHA_CONFIG: CaptchaConfig = {...DEFAULT_CAPTCHA_CONFIG, cost: 1000, max_counter: 100};
-function createHarness(captcha: CaptchaConfig): (headers: Record<string, string>) => Promise<Response> {
- const repository = {
- getCaptchaConfig: async () => captcha,
- } as unknown as InstanceConfigRepository;
+async function createHarness(captcha: CaptchaConfig): Promise<(headers: Record<string, string>) => Promise<Response>> {
+ const repository = getInstanceConfigRepository();
+ await repository.updateCaptchaConfig(captcha);
const app = new Hono<HonoEnv>();
app.use(async (ctx, next) => {
ctx.set('instanceConfigRepository', repository);
@@ -40,19 +40,21 @@ describe('CaptchaMiddleware', () => {
});
it('passes every request while the captcha is disabled', async () => {
- const response = await createHarness({...CHEAP_CAPTCHA_CONFIG, provider: CaptchaProviders.NONE})({});
+ const request = await createHarness({...CHEAP_CAPTCHA_CONFIG, provider: CaptchaProviders.NONE});
+ const response = await request({});
expect(response.status).toBe(200);
});
it('passes a test-mode request that does not opt in', async () => {
Config.dev.testModeEnabled = true;
- const request = createHarness(CHEAP_CAPTCHA_CONFIG);
+ const request = await createHarness(CHEAP_CAPTCHA_CONFIG);
expect((await request({})).status).toBe(200);
expect((await request({[CAPTCHA_TEST_HEADER]: 'true'})).status).toBe(400);
});
it('answers a request with no token with CAPTCHA_REQUIRED and an ALTCHA challenge', async () => {
- const response = await createHarness(CHEAP_CAPTCHA_CONFIG)({});
+ const request = await createHarness(CHEAP_CAPTCHA_CONFIG);
+ const response = await request({});
expect(response.status).toBe(400);
expect(await response.json()).toMatchObject({
code: 'CAPTCHA_REQUIRED',
@@ -62,7 +64,8 @@ describe('CaptchaMiddleware', () => {
});
it('answers a token that is not an ALTCHA payload with INVALID_CAPTCHA and a fresh challenge', async () => {
- const response = await createHarness(CHEAP_CAPTCHA_CONFIG)({'x-captcha-token': 'legacy-provider-token'});
+ const request = await createHarness(CHEAP_CAPTCHA_CONFIG);
+ const response = await request({'x-captcha-token': 'legacy-provider-token'});
expect(response.status).toBe(400);
expect(await response.json()).toMatchObject({
code: 'INVALID_CAPTCHA',
diff --git a/fluxer_api/src/api/middleware/tests/ConcurrencyLimitMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/ConcurrencyLimitMiddleware.test.ts
index cc537bb90..4c81148d0 100644
--- a/fluxer_api/src/api/middleware/tests/ConcurrencyLimitMiddleware.test.ts
+++ b/fluxer_api/src/api/middleware/tests/ConcurrencyLimitMiddleware.test.ts
@@ -3,9 +3,8 @@
import {ConcurrencyLimitMiddleware} from '@app/api/middleware/ConcurrencyLimitMiddleware';
import type {HonoEnv} from '@app/api/types/HonoEnv';
import {AppErrorHandler} from '@fluxer/errors/src/domains/core/ErrorHandlers';
-import {Logger} from '@fluxer/logger/src/Logger';
import {Hono} from 'hono';
-import {describe, expect, test, vi} from 'vitest';
+import {describe, expect, test} from 'vitest';
interface Deferred {
promise: Promise<void>;
@@ -48,7 +47,6 @@ function buildApp(maxInflightRequests: number) {
describe('ConcurrencyLimitMiddleware', () => {
test('sheds with 503 once the in-flight ceiling is reached', async () => {
const {app, release, entered} = buildApp(1);
- const errorLoggerSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
const inflight = app.request('/slow');
try {
await entered.promise;
@@ -63,13 +61,11 @@ describe('ConcurrencyLimitMiddleware', () => {
expect((await inflight).status).toBe(200);
} finally {
release.resolve();
- errorLoggerSpy.mockRestore();
}
});
test('admits probe paths while shedding everything else', async () => {
const {app, release, entered} = buildApp(1);
- const errorLoggerSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
const inflight = app.request('/slow');
try {
await entered.promise;
@@ -83,26 +79,19 @@ describe('ConcurrencyLimitMiddleware', () => {
await inflight;
} finally {
release.resolve();
- errorLoggerSpy.mockRestore();
}
});
test('releases the slot when the handler throws', async () => {
const {app} = buildApp(1);
- const errorLoggerSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
- try {
- for (let attempt = 0; attempt < 3; attempt += 1) {
- expect((await app.request('/boom')).status).toBe(500);
- }
- expect((await app.request('/fast')).status).toBe(200);
- } finally {
- errorLoggerSpy.mockRestore();
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ expect((await app.request('/boom')).status).toBe(500);
}
+ expect((await app.request('/fast')).status).toBe(200);
});
test('releases the slot taken by a shed request', async () => {
const {app, release, entered} = buildApp(1);
- const errorLoggerSpy = vi.spyOn(Logger.prototype, 'error').mockImplementation(() => {});
const inflight = app.request('/slow');
try {
await entered.promise;
@@ -116,7 +105,6 @@ describe('ConcurrencyLimitMiddleware', () => {
expect((await app.request('/fast')).status).toBe(200);
} finally {
release.resolve();
- errorLoggerSpy.mockRestore();
}
});
});
diff --git a/fluxer_api/src/api/middleware/tests/IpBanMiddleware.test.ts b/fluxer_api/src/api/middleware/tests/IpBanMiddleware.test.ts
index 9113322b4..2076a3590 100644
--- a/fluxer_api/src/api/middleware/tests/IpBanMiddleware.test.ts
+++ b/fluxer_api/src/api/middleware/tests/IpBanMiddleware.test.ts
@@ -1,16 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {ipBanCache} from '@app/api/middleware/IpBanMiddleware';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {beforeEach, describe, expect, it} from 'vitest';
beforeEach(() => {
ipBanCache.resetCaches();
});
-afterEach(() => {
- vi.useRealTimers();
-});
-
describe('IpBanCache', () => {
it('blocks IPv4-mapped IPv6 when a single IPv4 address is banned', () => {
ipBanCache.ban('127.0.0.1');
@@ -48,21 +44,4 @@ describe('IpBanCache', () => {
expect(match?.kind).toBe('permanent');
expect(match?.expiresAt).toBe(null);
});
- it('stops matching a temporary ban once it has expired', () => {
- vi.useFakeTimers({toFake: ['Date']});
- ipBanCache.banTemp('203.0.113.52', 3600);
- ipBanCache.banTemp('203.0.113.0/24', 3600);
- expect(ipBanCache.isBanned('203.0.113.52')).toBe(true);
- expect(ipBanCache.isBanned('203.0.113.53')).toBe(true);
- vi.advanceTimersByTime(3_600_001);
- expect(ipBanCache.getMatch('203.0.113.52')).toBe(null);
- expect(ipBanCache.getMatch('203.0.113.53')).toBe(null);
- });
- it('keeps matching a permanent ban that shares an address with an expired temporary one', () => {
- vi.useFakeTimers({toFake: ['Date']});
- ipBanCache.banTemp('203.0.113.54', 3600);
- ipBanCache.ban('203.0.113.54');
- vi.advanceTimersByTime(3_600_001);
- expect(ipBanCache.getMatch('203.0.113.54')?.kind).toBe('permanent');
- });
});
diff --git a/fluxer_api/src/api/middleware/tests/ProfileSubstringBlocklistCache.test.ts b/fluxer_api/src/api/middleware/tests/ProfileSubstringBlocklistCache.test.ts
index ecc4f75b0..b95d6fe59 100644
--- a/fluxer_api/src/api/middleware/tests/ProfileSubstringBlocklistCache.test.ts
+++ b/fluxer_api/src/api/middleware/tests/ProfileSubstringBlocklistCache.test.ts
@@ -2,7 +2,7 @@
import {AdminRepository} from '@app/api/admin/AdminRepository';
import {ProfileSubstringBlocklistCache} from '@app/api/middleware/ProfileSubstringBlocklistCache';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
describe('ProfileSubstringBlocklistCache', () => {
let cache: ProfileSubstringBlocklistCache;
@@ -10,15 +10,25 @@ describe('ProfileSubstringBlocklistCache', () => {
cache = new ProfileSubstringBlocklistCache();
});
afterEach(() => {
- vi.restoreAllMocks();
cache.resetForTesting();
});
it('refresh replaces every scope while preserving name widening and normalized matches', async () => {
cache.add('bio', 'oldbio');
- vi.spyOn(AdminRepository.prototype, 'loadAllBannedProfileSubstrings').mockResolvedValue([
- {scope: 'username', substring: 'Unban Tor', added_at: null, added_by: null, notes: null},
- {scope: 'bio', substring: 'blockedbio', added_at: null, added_by: null, notes: null},
- ]);
+ const repository = new AdminRepository();
+ await repository.banProfileSubstring({
+ scope: 'username',
+ substring: 'Unban Tor',
+ added_at: null,
+ added_by: null,
+ notes: null,
+ });
+ await repository.banProfileSubstring({
+ scope: 'bio',
+ substring: 'blockedbio',
+ added_at: null,
+ added_by: null,
+ notes: null,
+ });
await cache.refresh();
expect(cache.containsBannedSubstring('nickname', 'unban tor')).toBe(true);
expect(cache.containsBannedSubstring('global_name', 'u n b a n t o r')).toBe(true);
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2ConcurrentRedemption.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2ConcurrentRedemption.test.ts
index c57c5c841..615a50b42 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2ConcurrentRedemption.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2ConcurrentRedemption.test.ts
@@ -6,9 +6,8 @@ import {
exchangeOAuth2AuthorizationCode,
} from '@app/api/oauth/tests/OAuthTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
const CONCURRENT_REQUESTS = 8;
@@ -17,17 +16,6 @@ interface TokenResult {
accessToken: string | null;
}
-function addQueryLatency(): void {
- const executeQuery = InMemoryCassandraQueryExecutor.prototype.executeQuery;
- vi.spyOn(InMemoryCassandraQueryExecutor.prototype, 'executeQuery').mockImplementation(async function (
- this: InMemoryCassandraQueryExecutor,
- ...args: Parameters<typeof executeQuery>
- ) {
- await new Promise((resolve) => setTimeout(resolve, 1));
- return executeQuery.apply(this, args);
- } as typeof executeQuery);
-}
-
async function postToken(
harness: ApiTestHarness,
clientId: string,
@@ -53,14 +41,7 @@ async function postConcurrently(
clientSecret: string,
form: Record<string, string>,
): Promise<Array<TokenResult>> {
- addQueryLatency();
- try {
- return await Promise.all(
- Array.from({length: CONCURRENT_REQUESTS}, () => postToken(harness, clientId, clientSecret, form)),
- );
- } finally {
- vi.restoreAllMocks();
- }
+ return Promise.all(Array.from({length: CONCURRENT_REQUESTS}, () => postToken(harness, clientId, clientSecret, form)));
}
function expectSingleSuccess(results: Array<TokenResult>): void {
@@ -76,7 +57,6 @@ describe('OAuth2 concurrent grant redemption', () => {
harness = await createApiTestHarness();
});
afterEach(async () => {
- vi.restoreAllMocks();
await harness?.shutdown();
});
diff --git a/fluxer_api/src/api/payment_disputes/tests/PaymentDisputeReviews.test.ts b/fluxer_api/src/api/payment_disputes/tests/PaymentDisputeReviews.test.ts
index e8f31ed24..69bdfed97 100644
--- a/fluxer_api/src/api/payment_disputes/tests/PaymentDisputeReviews.test.ts
+++ b/fluxer_api/src/api/payment_disputes/tests/PaymentDisputeReviews.test.ts
@@ -4,25 +4,12 @@ import {AdminRepository} from '@app/api/admin/AdminRepository';
import {AdminAuditService} from '@app/api/admin/services/AdminAuditService';
import {createUserID} from '@app/api/BrandedTypes';
import {Config, getConfig} from '@app/api/Config';
-import {
- type CassandraQueryExecutorForTesting,
- setCassandraQueryExecutorForTesting,
-} from '@app/api/database/CassandraQueryExecution';
-import {
- type CassandraParams,
- Db,
- isConditionalQuery,
- nextVersion,
- type PreparedQuery,
-} from '@app/api/database/CassandraTypes';
+import {setCassandraQueryExecutorForTesting} from '@app/api/database/CassandraQueryExecution';
import type {PaymentDisputeReviewRow} from '@app/api/database/types/PaymentDisputeTypes';
import {getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
import {getEmailService, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {shouldCloseAfterPaymentDispute} from '@app/api/payment_disputes/PaymentDisputeEnforcement';
-import {
- PaymentDisputeRepository,
- type PaymentDisputeReviewPatch,
-} from '@app/api/payment_disputes/PaymentDisputeRepository';
+import {PaymentDisputeRepository} from '@app/api/payment_disputes/PaymentDisputeRepository';
import {
getPaymentDisputeReviewBlockers,
PaymentDisputeReviewService,
@@ -35,7 +22,7 @@ import {EmailDeliveryModes} from '@fluxer/constants/src/AccountConfigConstants';
import {SmtpTlsModes} from '@fluxer/constants/src/SmtpConstants';
import {MS_PER_DAY, MS_PER_SECOND} from '@fluxer/date_utils/src/DateConstants';
import type Stripe from 'stripe';
-import {afterEach, assert, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, assert, beforeEach, describe, expect, test} from 'vitest';
const PAID_AT = new Date('2026-11-03T16:00:00Z');
const DISPUTED_AT = new Date(PAID_AT.getTime() + 30 * MS_PER_DAY);
@@ -325,9 +312,10 @@ describe('payment dispute review alerts through SMTP', () => {
pendingOpens.add(pending);
await smtp.entered;
- expect(await repository.findReview('dp_test_1')).toEqual(
- review({created_at: REVIEW_OPENED_AT, evidence_due_by: null}),
- );
+ const opened = await repository.findReview('dp_test_1');
+ assert(opened !== null);
+ const openedAt = opened.created_at;
+ expect(opened).toEqual(review({created_at: openedAt, evidence_due_by: null}));
expect(await adminRepository.listAllAuditLogsPaginated(AUDIT_PAGE_SIZE)).toMatchObject([
{
targetType: 'user',
@@ -342,7 +330,7 @@ describe('payment dispute review alerts through SMTP', () => {
['evidence_due_by', ''],
['blockers', ''],
]),
- createdAt: REVIEW_OPENED_AT,
+ createdAt: expect.any(Date),
},
]);
expect(smtp.delivered).toEqual([]);
@@ -353,13 +341,13 @@ describe('payment dispute review alerts through SMTP', () => {
);
smtp.release();
- expect(await pending).toEqual(review({created_at: REVIEW_OPENED_AT, evidence_due_by: null}));
+ expect(await pending).toEqual(review({created_at: openedAt, evidence_due_by: null}));
expect(smtp.delivered).toHaveLength(accepted);
expect(await service.openReview(SUBJECT, dispute)).toEqual(
- review({created_at: REVIEW_OPENED_AT, evidence_due_by: null, version: 2}),
+ review({created_at: openedAt, evidence_due_by: null, version: 2}),
);
expect(await repository.findReview('dp_test_1')).toEqual(
- review({created_at: REVIEW_OPENED_AT, evidence_due_by: null, version: 2}),
+ review({created_at: openedAt, evidence_due_by: null, version: 2}),
);
expect(smtp.attempts).toHaveLength(1);
expect(smtp.delivered).toHaveLength(accepted);
diff --git a/fluxer_api/src/api/read_state/PushClearOnReply.test.ts b/fluxer_api/src/api/read_state/PushClearOnReply.test.ts
index 93320930b..d42528dc2 100644
--- a/fluxer_api/src/api/read_state/PushClearOnReply.test.ts
+++ b/fluxer_api/src/api/read_state/PushClearOnReply.test.ts
@@ -11,10 +11,9 @@ import {
} from '@app/api/channel/tests/ChannelTestUtils';
import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface AckResponse {
read_states: Array<{
@@ -23,33 +22,6 @@ interface AckResponse {
}>;
}
-interface ReadSignals {
- clears: Array<{channelId: string; messageId: string}>;
- acks: Array<{channel_id: string; message_id: string}>;
-}
-
-async function captureReadSignals(userId: string, action: () => Promise<void>): Promise<ReadSignals> {
- const clearSpy = vi.spyOn(NoopGatewayService.prototype, 'clearPushChannelNotifications');
- const presenceSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
- try {
- await action();
- return {
- clears: clearSpy.mock.calls
- .filter(([params]) => params.userId.toString() === userId)
- .map(([params]) => ({channelId: params.channelId.toString(), messageId: params.messageId.toString()})),
- acks: presenceSpy.mock.calls
- .filter(([params]) => params.userId.toString() === userId && params.event === 'MESSAGE_ACK')
- .map(([params]) => {
- const data = params.data as {channel_id: string; message_id: string};
- return {channel_id: data.channel_id, message_id: data.message_id};
- }),
- };
- } finally {
- clearSpy.mockRestore();
- presenceSpy.mockRestore();
- }
-}
-
async function readLastMessageId(
harness: ApiTestHarness,
token: string,
@@ -64,36 +36,6 @@ async function readLastMessageId(
return response.read_states[0]?.last_message_id;
}
-async function ackMessage(
- harness: ApiTestHarness,
- token: string,
- channelId: string,
- messageId: string,
- body: {manual?: boolean; mention_count?: number} = {},
-): Promise<void> {
- await createBuilder(harness, token)
- .post(`/channels/${channelId}/messages/${messageId}/ack`)
- .body(body)
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
-}
-
-async function ringCall(harness: ApiTestHarness, token: string, channelId: string): Promise<void> {
- await createBuilder(harness, token)
- .post(`/channels/${channelId}/call/ring`)
- .body({})
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
-}
-
-async function latestMessageId(harness: ApiTestHarness, token: string, channelId: string): Promise<string> {
- const messages = await createBuilder<Array<{id: string}>>(harness, token)
- .get(`/channels/${channelId}/messages?limit=1`)
- .expect(HTTP_STATUS.OK)
- .execute();
- return messages[0]!.id;
-}
-
async function setupDm(harness: ApiTestHarness): Promise<{alice: TestAccount; bob: TestAccount; channelId: string}> {
const alice = await createTestAccount(harness);
const bob = await createTestAccount(harness);
@@ -104,7 +46,7 @@ async function setupDm(harness: ApiTestHarness): Promise<{alice: TestAccount; bo
return {alice, bob, channelId: dm.id};
}
-describe('push clear on reply', () => {
+describe('read state on reply', () => {
let harness: ApiTestHarness;
beforeAll(async () => {
harness = await createApiTestHarness();
@@ -116,37 +58,11 @@ describe('push clear on reply', () => {
await harness?.shutdown();
});
- it('replying in a DM clears the partner message push up to the reply without a MESSAGE_ACK', async () => {
+ it('replying in a DM marks the channel read up to the reply', async () => {
const {alice, bob, channelId} = await setupDm(harness);
const fromBob = await sendMessage(harness, bob.token, channelId, 'ping from bob');
- let replyId = '';
- const signals = await captureReadSignals(alice.userId, async () => {
- const reply = await sendMessage(harness, alice.token, channelId, 'reply from alice');
- replyId = reply.id;
- });
- expect(BigInt(replyId) > BigInt(fromBob.id)).toBe(true);
- expect(signals.clears).toEqual([{channelId, messageId: replyId}]);
- expect(signals.acks).toEqual([]);
- expect(await readLastMessageId(harness, alice.token, channelId, fromBob.id)).toBe(replyId);
- });
-
- it('a follow-up message with nothing new unread sends no push clear', async () => {
- const {alice, bob, channelId} = await setupDm(harness);
- await sendMessage(harness, bob.token, channelId, 'ping from bob');
- await sendMessage(harness, alice.token, channelId, 'reply from alice');
- const signals = await captureReadSignals(alice.userId, async () => {
- await sendMessage(harness, alice.token, channelId, 'second reply from alice');
- });
- expect(signals.clears).toEqual([]);
- expect(signals.acks).toEqual([]);
- });
-
- it('the first message in a DM with nothing unread sends no push clear', async () => {
- const {alice, channelId} = await setupDm(harness);
- const signals = await captureReadSignals(alice.userId, async () => {
- await sendMessage(harness, alice.token, channelId, 'hello from alice');
- });
- expect(signals.clears).toEqual([]);
+ const reply = await sendMessage(harness, alice.token, channelId, 'reply from alice');
+ expect(await readLastMessageId(harness, alice.token, channelId, fromBob.id)).toBe(reply.id);
});
it('the read state RPC reports the reply as the last read message', async () => {
@@ -165,21 +81,7 @@ describe('push clear on reply', () => {
expect(await readState(alice.userId, '1')).toBeNull();
});
- it('an explicit ack in a DM sends exactly one push clear and one MESSAGE_ACK', async () => {
- const {alice, bob, channelId} = await setupDm(harness);
- const fromBob = await sendMessage(harness, bob.token, channelId, 'ping from bob');
- const signals = await captureReadSignals(alice.userId, async () => {
- await createBuilder(harness, alice.token)
- .post(`/channels/${channelId}/messages/${fromBob.id}/ack`)
- .body({})
- .expect(HTTP_STATUS.NO_CONTENT)
- .execute();
- });
- expect(signals.clears).toEqual([{channelId, messageId: fromBob.id}]);
- expect(signals.acks).toEqual([{channel_id: channelId, message_id: fromBob.id}]);
- });
-
- it('replying in a guild text channel clears the other member message push up to the reply without a MESSAGE_ACK', async () => {
+ it('replying in a guild text channel marks the channel read up to the reply', async () => {
const alice = await createTestAccount(harness);
const bob = await createTestAccount(harness);
await ensureSessionStarted(harness, alice.token);
@@ -189,86 +91,7 @@ describe('push clear on reply', () => {
const invite = await createChannelInvite(harness, alice.token, channel.id);
await acceptInvite(harness, bob.token, invite.code);
const fromBob = await sendMessage(harness, bob.token, channel.id, 'ping from bob');
- let replyId = '';
- const signals = await captureReadSignals(alice.userId, async () => {
- const reply = await sendMessage(harness, alice.token, channel.id, 'reply from alice');
- replyId = reply.id;
- });
- expect(BigInt(replyId) > BigInt(fromBob.id)).toBe(true);
- expect(signals.clears).toEqual([{channelId: channel.id, messageId: replyId}]);
- expect(signals.acks).toEqual([]);
- expect(await readLastMessageId(harness, alice.token, channel.id, fromBob.id)).toBe(replyId);
- });
-
- it('starting a call clears the caller push for messages still unread up to the call message', async () => {
- const {alice, bob, channelId} = await setupDm(harness);
- const first = await sendMessage(harness, bob.token, channelId, 'first from bob');
- const second = await sendMessage(harness, bob.token, channelId, 'second from bob');
- await ackMessage(harness, alice.token, channelId, first.id);
- const signals = await captureReadSignals(alice.userId, async () => {
- await ringCall(harness, alice.token, channelId);
- });
- const callMessageId = await latestMessageId(harness, alice.token, channelId);
- expect(BigInt(callMessageId) > BigInt(second.id)).toBe(true);
- expect(signals.clears).toEqual([{channelId, messageId: callMessageId}]);
- expect(signals.acks).toEqual([]);
- });
-
- it('starting a call with nothing unread sends the caller no push clear', async () => {
- const {alice, bob, channelId} = await setupDm(harness);
- const fromBob = await sendMessage(harness, bob.token, channelId, 'ping from bob');
- await ackMessage(harness, alice.token, channelId, fromBob.id);
- const signals = await captureReadSignals(alice.userId, async () => {
- await ringCall(harness, alice.token, channelId);
- });
- expect(signals.clears).toEqual([]);
- });
-
- it('ending a call clears a participant push up to the call message only when it was unread', async () => {
- const {alice, bob, channelId} = await setupDm(harness);
- const fromBob = await sendMessage(harness, bob.token, channelId, 'ping from bob');
- await ringCall(harness, alice.token, channelId);
- const callMessageId = await latestMessageId(harness, alice.token, channelId);
- await ackMessage(harness, bob.token, channelId, fromBob.id, {manual: true, mention_count: 0});
- const endCall = async () => {
- await createBuilder(harness, '')
- .post('/test/rpc-session-init')
- .body({
- type: 'call_ended',
- channel_id: channelId,
- message_id: callMessageId,
- participants: [alice.userId, bob.userId],
- ended_timestamp: Date.now(),
- })
- .expect(HTTP_STATUS.OK)
- .execute();
- };
- const clearSpy = vi.spyOn(NoopGatewayService.prototype, 'clearPushChannelNotifications');
- try {
- await endCall();
- const clears = clearSpy.mock.calls.map(([params]) => ({
- userId: params.userId.toString(),
- channelId: params.channelId.toString(),
- messageId: params.messageId.toString(),
- }));
- expect(clears).toEqual([{userId: bob.userId, channelId, messageId: callMessageId}]);
- } finally {
- clearSpy.mockRestore();
- }
- });
-
- it('joining a guild with an active system channel sends the joiner no push clear', async () => {
- const alice = await createTestAccount(harness);
- const bob = await createTestAccount(harness);
- await ensureSessionStarted(harness, alice.token);
- await ensureSessionStarted(harness, bob.token);
- const guild = await createGuild(harness, alice.token, 'Push Clear Join Guild');
- const systemChannelId = guild.system_channel_id!;
- await sendMessage(harness, alice.token, systemChannelId, 'welcome');
- const invite = await createChannelInvite(harness, alice.token, systemChannelId);
- const signals = await captureReadSignals(bob.userId, async () => {
- await acceptInvite(harness, bob.token, invite.code);
- });
- expect(signals.clears).toEqual([]);
+ const reply = await sendMessage(harness, alice.token, channel.id, 'reply from alice');
+ expect(await readLastMessageId(harness, alice.token, channel.id, fromBob.id)).toBe(reply.id);
});
});
diff --git a/fluxer_api/src/api/read_state/tests/ThreadReadStates.test.ts b/fluxer_api/src/api/read_state/tests/ThreadReadStates.test.ts
index 05d8e5cfb..702b366b8 100644
--- a/fluxer_api/src/api/read_state/tests/ThreadReadStates.test.ts
+++ b/fluxer_api/src/api/read_state/tests/ThreadReadStates.test.ts
@@ -7,13 +7,12 @@ import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/Chann
import {ensureSessionStarted, sendMessage} from '@app/api/message/tests/MessageTestUtils';
import {clearReadStateChannelMetaCacheForTesting} from '@app/api/read_state/ReadStateChannelMeta';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import {ReadStateFlags} from '@fluxer/constants/src/ThreadConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface ReadStateWire {
id: string;
@@ -42,10 +41,6 @@ describe('thread read states', () => {
clearReadStateChannelMetaCacheForTesting();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
clearChannelThreadsTaintCacheForTesting();
await harness.shutdown();
@@ -117,21 +112,18 @@ describe('thread read states', () => {
expect(incapable.read_states.some((readState) => readState.id === s.thread.id)).toBe(false);
});
- it('returns flags from the bulk ack and scopes MESSAGE_ACK to thread sessions', async () => {
+ it('returns flags from the bulk ack only to thread sessions', async () => {
const s = await activeSetup();
const sent = await threadsRequest<MessageResponse>(harness, s.member.token)
.post(`/channels/${s.thread.id}/messages`)
.body({content: 'hello'})
.execute();
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
const acked = await threadsRequest<{read_states: Array<ReadStateWire>}>(harness, s.owner.token)
.post('/read-states/ack')
.body({read_states: [{channel_id: s.thread.id, message_id: sent.id}]})
.expect(200)
.execute();
expect(acked.read_states).toEqual([expect.objectContaining({id: s.thread.id, flags: THREAD_FLAGS})]);
- const ack = dispatch.mock.calls.find(([params]) => params.event === 'MESSAGE_ACK')?.[0];
- expect(ack?.data).toMatchObject({flags: THREAD_FLAGS, __thread_scoped: s.guildId});
const incapable = await threadsRequest<{read_states: Array<ReadStateWire>}>(harness, s.owner.token, {
capable: false,
})
diff --git a/fluxer_api/src/api/report/tests/ReportProfileSnapshot.test.ts b/fluxer_api/src/api/report/tests/ReportProfileSnapshot.test.ts
index 71d5e5af6..bdb333a1c 100644
--- a/fluxer_api/src/api/report/tests/ReportProfileSnapshot.test.ts
+++ b/fluxer_api/src/api/report/tests/ReportProfileSnapshot.test.ts
@@ -31,7 +31,7 @@ import {UserFlags} from '@fluxer/constants/src/UserConstants';
import type {GuildMemberResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {listReportProfileSnapshotAssets} from '@fluxer/schema/src/domains/report/ReportProfileSnapshotSchemas';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface ReportResponse {
report_id: string;
@@ -345,20 +345,6 @@ describe('Report profile snapshots', () => {
expect(await countReports()).toBe(2);
});
- test('a notice whose ticket is claimed elsewhere copies no images', async () => {
- const {target} = await setupProfile(harness);
- const ticket = await issueTicket(harness);
- const copiesBefore = harness.storageService.getCopiedObjects().length;
- const claim = vi.spyOn(ReportRepository.prototype, 'consumeDsaTicket').mockResolvedValueOnce(false);
- await submitDsa(harness, ticket, {report_type: 'user', user_id: target.userId})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_DSA_TICKET)
- .execute();
- expect(claim).toHaveBeenCalledTimes(1);
- claim.mockRestore();
- expect(harness.storageService.getCopiedObjects()).toHaveLength(copiesBefore);
- expect(await countReports()).toBe(0);
- });
-
test('notices filed through the DSA form keep the same snapshots', async () => {
const {owner, target, guild, profile} = await setupProfile(harness);
const named = await updateGuild(harness, owner.token, guild.id, {name: 'Original Guild', icon: FIRST_IMAGE});
diff --git a/fluxer_api/src/api/rpc/tests/RpcThreadCollections.test.ts b/fluxer_api/src/api/rpc/tests/RpcThreadCollections.test.ts
index fcaa8b890..a17e59ddf 100644
--- a/fluxer_api/src/api/rpc/tests/RpcThreadCollections.test.ts
+++ b/fluxer_api/src/api/rpc/tests/RpcThreadCollections.test.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {ThreadRepository} from '@app/api/channel/repositories/ThreadRepository';
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
@@ -10,7 +9,7 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
interface RpcEnvelope<T> {
type: string;
@@ -63,23 +62,17 @@ describe('RpcService thread collections', () => {
test('active guild channel collections carry the gate and forums but load threads separately', async () => {
await setup();
await startThread();
- const spy = vi.spyOn(ThreadRepository.prototype, 'listActiveThreads');
- try {
- const {data} = await rpc<{
- thread_gate: {active: boolean; config_version: number};
- thread_tainted: boolean;
- thread_only_channels: Array<unknown>;
- }>({type: 'guild_collection', guild_id: guildId, collection: 'channels'});
- expect(data.thread_gate.active).toBe(true);
- expect(data.thread_gate.config_version).toBe(0);
- expect(data.thread_tainted).toBe(true);
- expect(data.thread_only_channels).toEqual([]);
- for (const key of ['threads', 'thread_members', 'thread_parent_settings', 'thread_load_failed']) {
- expect(data).not.toHaveProperty(key);
- }
- expect(spy).not.toHaveBeenCalled();
- } finally {
- spy.mockRestore();
+ const {data} = await rpc<{
+ thread_gate: {active: boolean; config_version: number};
+ thread_tainted: boolean;
+ thread_only_channels: Array<unknown>;
+ }>({type: 'guild_collection', guild_id: guildId, collection: 'channels'});
+ expect(data.thread_gate.active).toBe(true);
+ expect(data.thread_gate.config_version).toBe(0);
+ expect(data.thread_tainted).toBe(true);
+ expect(data.thread_only_channels).toEqual([]);
+ for (const key of ['threads', 'thread_members', 'thread_parent_settings', 'thread_load_failed']) {
+ expect(data).not.toHaveProperty(key);
}
});
diff --git a/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts b/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts
index 7f68f64ef..1db245e9f 100644
--- a/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts
+++ b/fluxer_api/src/api/search/tests/ThreadSearchEndpoint.test.ts
@@ -5,11 +5,11 @@ import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@ap
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
-import {getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
+import {getSnowflakeService, setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {getThreadSearchService} from '@app/api/SearchFactory';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
+import {SyncTaskWorkerService} from '@app/api/test/SyncTaskWorkerService';
import refreshSearchIndex from '@app/api/worker/tasks/RefreshSearchIndex';
import {backfillThreadSearch, syncThreadSearchDocument} from '@app/api/worker/tasks/ThreadSearchTasks';
import {clearWorkerDependencies, setWorkerDependencies} from '@app/api/worker/WorkerContext';
@@ -22,7 +22,7 @@ import type {
} from '@fluxer/schema/src/domains/channel/ForumRequestSchemas';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const HANDLERS: Record<string, WorkerTaskHandler> = {
syncThreadSearchDocument,
@@ -40,7 +40,7 @@ interface Setup {
describe('thread search', () => {
let harness: ApiTestHarness;
- let pending: Array<Promise<unknown>>;
+ let worker: SyncTaskWorkerService;
beforeAll(async () => {
harness = await createApiTestHarness({search: 'enabled'});
@@ -50,20 +50,13 @@ describe('thread search', () => {
await harness.reset();
clearChannelThreadsTaintCacheForTesting();
setWorkerDependencies(await initializeWorkerDependencies(getSnowflakeService()));
- pending = [];
- vi.spyOn(NoopWorkerService.prototype, 'addJob').mockImplementation((async (
- task: string,
- payload: Record<string, unknown>,
- ) => {
- const handler = HANDLERS[task];
- if (handler) pending.push(handler(payload, createTestWorkerHelpers({attempt: {isLastAttempt: true}})));
- return 0n;
- }) as () => Promise<bigint>);
+ worker = new SyncTaskWorkerService(HANDLERS, {deferred: true});
+ setInjectedWorkerService(worker);
await getThreadSearchService()!.deleteAllDocuments();
});
afterEach(() => {
- vi.restoreAllMocks();
+ setInjectedWorkerService(new NoopWorkerService());
});
afterAll(async () => {
@@ -73,7 +66,7 @@ describe('thread search', () => {
});
async function settle(): Promise<void> {
- while (pending.length > 0) await Promise.all(pending.splice(0));
+ await worker.drain({maxAttempts: 1});
}
async function setup(): Promise<Setup> {
diff --git a/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts b/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts
index f610c0340..f854cddb4 100644
--- a/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts
+++ b/fluxer_api/src/api/store_billing/tests/StoreNotificationClaims.test.ts
@@ -3,7 +3,7 @@
import {KvOnceClaims} from '@app/api/infrastructure/KvOnceClaims';
import {appStoreNotificationClaimKey} from '@app/api/store_billing/StoreNotificationClaims';
import {WORKER_LANES} from '@app/api/worker/WorkerLaneConfig';
-import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
+import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
import {ms} from 'itty-time';
import {describe, expect, it} from 'vitest';
@@ -11,21 +11,15 @@ const LIFECYCLE_REDELIVERY_DELAY_MS = ms('5 seconds');
describe('StoreNotificationClaims', () => {
it('lets an abandoned claim expire before the lifecycle lane stops redelivering', async () => {
- const ttls: Array<number> = [];
- const kv = {
- async setnx(_key: string, _value: string, ttlSeconds?: number): Promise<boolean> {
- ttls.push(ttlSeconds ?? 0);
- return true;
- },
- } as unknown as IKVProvider;
- const claims = new KvOnceClaims(kv);
- expect(await claims.tryClaim(appStoreNotificationClaimKey('7b4d9c1e-0000-4000-8000-000000000001'))).toBe('claimed');
+ const kv = new MockKVProvider();
+ const key = appStoreNotificationClaimKey('7b4d9c1e-0000-4000-8000-000000000001');
+ expect(await new KvOnceClaims(kv).tryClaim(key)).toBe('claimed');
const lane = WORKER_LANES.find((entry) => entry.name === 'lifecycle');
expect(lane?.taskTypes).toContain('processAppStoreNotification');
expect(lane?.taskTypes).toContain('processGooglePlayNotification');
const retryWindowMs = lane!.ackWaitMs + (lane!.maxDeliver - 1) * LIFECYCLE_REDELIVERY_DELAY_MS;
- expect(ttls).toHaveLength(1);
- expect(ttls[0] * 1000).toBeGreaterThanOrEqual(lane!.ackWaitMs);
- expect(ttls[0] * 1000).toBeLessThanOrEqual(retryWindowMs / 2);
+ const ttlMs = (await kv.ttl(key)) * 1000;
+ expect(ttlMs).toBeGreaterThanOrEqual(lane!.ackWaitMs);
+ expect(ttlMs).toBeLessThanOrEqual(retryWindowMs / 2);
});
});
diff --git a/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts b/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts
index dc8ffa84b..21e8dfe0e 100644
--- a/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts
+++ b/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts
@@ -15,7 +15,7 @@ import {
setStoredBillingConfig,
} from '@app/api/stripe/BillingConfigCache';
import {getStripeClient} from '@app/api/stripe/StripeClient';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
const ENV_PRICES = {
monthlyUsd: 'price_monthly_usd',
diff --git a/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts b/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts
index c1d1fc843..c7f975248 100644
--- a/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts
+++ b/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts
@@ -23,6 +23,7 @@ import {
type StripeApiHandlers,
} from '@app/api/test/msw/handlers/StripeApiHandlers';
import {server} from '@app/api/test/msw/server';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {getCurrencyPreferences, getGiftCurrencyPreferences, isLocalizedCurrency} from '@app/api/utils/CurrencyUtils';
@@ -116,7 +117,7 @@ function restoreGlobalState(state: GlobalState): void {
setStoredBillingConfig(state.storedBilling);
}
-const WORKER_HELPERS = {logger: new NoopLogger()} as unknown as WorkerTaskHelpers;
+const WORKER_HELPERS = createTestWorkerHelpers();
function useOperatorBilling(overrides: Partial<StoredBillingConfig> = {}): void {
Config.instance.selfHosted = true;
diff --git a/fluxer_api/src/api/stripe/tests/StripeWebhookCheckout.test.ts b/fluxer_api/src/api/stripe/tests/StripeWebhookCheckout.test.ts
index 09d0a858b..29379ca7d 100644
--- a/fluxer_api/src/api/stripe/tests/StripeWebhookCheckout.test.ts
+++ b/fluxer_api/src/api/stripe/tests/StripeWebhookCheckout.test.ts
@@ -28,9 +28,8 @@ import {PaymentRepository} from '@app/api/user/repositories/PaymentRepository';
import {UserRepository} from '@app/api/user/repositories/UserRepository';
import {HttpStatus} from '@fluxer/constants/src/HttpConstants';
import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
-import {MS_PER_DAY, MS_PER_MINUTE} from '@fluxer/date_utils/src/DateConstants';
-import Stripe from 'stripe';
-import {afterAll, afterEach, assert, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {MS_PER_DAY} from '@fluxer/date_utils/src/DateConstants';
+import {afterAll, afterEach, assert, beforeAll, beforeEach, describe, expect, test} from 'vitest';
const MOCK_PRICES = {
monthlyUsd: 'price_monthly_usd',
@@ -147,8 +146,8 @@ describe('StripeWebhookService - checkout.session.completed', () => {
test.each([
['valid timestamp without consent', '2025-01-02T03:04:05.000Z', null, '2025-01-02T03:04:05.000Z'],
['valid timestamp with consent', '2025-01-02T03:04:05.000Z', 'accepted', '2025-01-02T03:04:05.000Z'],
- ['invalid timestamp with consent', 'invalid', 'accepted', '2026-10-21T12:00:00.000Z'],
- ['empty timestamp with consent', '', 'accepted', '2026-10-21T12:00:00.000Z'],
+ ['invalid timestamp with consent', 'invalid', 'accepted', 'now'],
+ ['empty timestamp with consent', '', 'accepted', 'now'],
['invalid timestamp without consent', 'invalid', null, null],
['empty timestamp without consent', '', null, null],
] as const)('recovers a missing payment with %s', async (_label, timestamp, consent, expected) => {
@@ -164,12 +163,19 @@ describe('StripeWebhookService - checkout.session.completed', () => {
},
});
event.data.object.consent = {terms_of_service: consent};
+ const before = Date.now();
await sendStripeWebhook(harness, event);
const payment = await new PaymentRepository().getPaymentByCheckoutSession(sessionId);
expect(payment?.status).toBe('completed');
- expect(payment?.euWithdrawalWaiverAcceptedAt?.toISOString() ?? null).toBe(expected);
+ const acceptedAt = payment?.euWithdrawalWaiverAcceptedAt ?? null;
+ if (expected === 'now') {
+ expect(acceptedAt?.getTime()).toBeGreaterThanOrEqual(before);
+ expect(acceptedAt?.getTime()).toBeLessThanOrEqual(Date.now());
+ } else {
+ expect(acceptedAt?.toISOString() ?? null).toBe(expected);
+ }
});
test('flags an open payment dispute review when a checkout opened before the dispute completes', async () => {
diff --git a/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts b/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts
index 390563f1c..98e4beefb 100644
--- a/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts
+++ b/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts
@@ -13,6 +13,7 @@ import {createUserID, type UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import {createApiContext} from '@app/api/CreateApiContext';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
+import {Db} from '@app/api/database/CassandraTypes';
import {close, endDecision} from '@app/api/enforcement/tests/EnforcementTestUtils';
import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
import {getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
@@ -45,7 +46,7 @@ import {UserFlags, UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
import type {EnforcementDecisionResponse} from '@fluxer/schema/src/domains/admin/EnforcementSchemas';
import {EmailService} from '@pkgs/email/src/EmailService';
import {SmtpEmailProvider} from '@pkgs/email/src/SmtpEmailProvider';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
const DAY_MS = 24 * 60 * 60 * 1000;
const EXEMPT_REASONS = [
@@ -176,10 +177,18 @@ describe('Plutonium payment disputes', () => {
return smtp;
}
- function passWarningDate(): void {
- const now = Date.now();
- vi.useFakeTimers({toFake: ['Date']});
- vi.setSystemTime(new Date(now + 8 * DAY_MS));
+ async function backdateReview(
+ disputeId: string,
+ field: 'warning_deadline' | 'closed_at',
+ agoMs: number,
+ ): Promise<void> {
+ const review = await disputes.findReview(disputeId);
+ expect(review).not.toBeNull();
+ await disputes.updateReview(review!, {[field]: Db.set(new Date(Date.now() - agoMs))});
+ }
+
+ async function passWarningDate(disputeId: string): Promise<void> {
+ await backdateReview(disputeId, 'warning_deadline', DAY_MS);
}
let eventCounter = 0;
@@ -951,7 +960,7 @@ describe('Plutonium payment disputes', () => {
expect(smtp.attempts).toHaveLength(1);
expect(smtp.attempts[0]).toMatchObject({from: '<[email protected]>', to: `<${buyer.email}>`});
expect(smtp.delivered).toEqual([]);
- passWarningDate();
+ await passWarningDate('dp_pi_warn_incomplete');
await closeDispute('pi_warn_incomplete', 'lost');
const user = await userRepository.findUniqueAssert(idOf(buyer));
expect(user.flags & UserFlags.DELETED).toBe(0n);
@@ -975,7 +984,7 @@ describe('Plutonium payment disputes', () => {
await openDispute('pi_warn_lost');
const admin = await staff();
await decide(admin, 'dp_pi_warn_lost', 'unjustified', 'Plutonium was used for three weeks.');
- passWarningDate();
+ await passWarningDate('dp_pi_warn_lost');
await closeDispute('pi_warn_lost', 'lost');
expect(stripe.spies.cancelledSubscriptions).toEqual(['sub_pi_warn_lost']);
const review = await disputes.findReview('dp_pi_warn_lost');
@@ -1037,7 +1046,7 @@ describe('Plutonium payment disputes', () => {
await openDispute('pi_warn_lost_twice');
const admin = await staff();
await decide(admin, 'dp_pi_warn_lost_twice', 'unjustified');
- passWarningDate();
+ await passWarningDate('dp_pi_warn_lost_twice');
await closeDispute('pi_warn_lost_twice', 'lost');
await closeDispute('pi_warn_lost_twice', 'lost');
const emails = await listTestEmails(harness, {recipient: buyer.email});
@@ -1056,7 +1065,7 @@ describe('Plutonium payment disputes', () => {
pending_deletion_at: holderDeletionAt,
deletion_reason_code: DeletionReasons.USER_REQUESTED,
});
- passWarningDate();
+ await passWarningDate('dp_pi_warn_holder');
await closeDispute('pi_warn_holder', 'lost');
const closed = await userRepository.findUniqueAssert(idOf(buyer));
expect(closed.flags & UserFlags.DELETED).toBe(UserFlags.DELETED);
@@ -1082,7 +1091,8 @@ describe('Plutonium payment disputes', () => {
const admin = await staff();
await decide(admin, 'dp_pi_two_lost_a', 'unjustified');
await decide(admin, 'dp_pi_two_lost_b', 'unjustified');
- passWarningDate();
+ await passWarningDate('dp_pi_two_lost_a');
+ await passWarningDate('dp_pi_two_lost_b');
await closeDispute('pi_two_lost_a', 'lost');
await closeDispute('pi_two_lost_b', 'lost');
const decisionId = (await disputes.findReview('dp_pi_two_lost_a'))?.enforcement_decision_id ?? null;
@@ -1119,7 +1129,7 @@ describe('Plutonium payment disputes', () => {
const admin = await staff();
await decide(admin, 'dp_pi_warn_waits', 'unjustified', 'Plutonium was used for three weeks.');
const spamDecisionId = await close(harness, admin, buyer.userId);
- passWarningDate();
+ await passWarningDate('dp_pi_warn_waits');
await closeDispute('pi_warn_waits', 'lost');
expect((await disputes.findReview('dp_pi_warn_waits'))?.enforcement_decision_id ?? null).toBeNull();
const waiting = (await reviews(admin)).find((entry) => entry.dispute_id === 'dp_pi_warn_waits');
@@ -1163,7 +1173,7 @@ describe('Plutonium payment disputes', () => {
const admin = await staff();
await decide(admin, 'dp_pi_warn_swept', 'unjustified');
const spamDecisionId = await close(harness, admin, buyer.userId);
- passWarningDate();
+ await passWarningDate('dp_pi_warn_swept');
await closeDispute('pi_warn_swept', 'lost');
setInjectedWorkerService(new NoopWorkerService());
try {
@@ -1178,7 +1188,7 @@ describe('Plutonium payment disputes', () => {
await closePaymentDisputeAccounts({}, createTestWorkerHelpers());
expect((await disputes.findReview('dp_pi_warn_swept'))?.enforcement_decision_id ?? null).toBeNull();
- vi.setSystemTime(new Date(Date.now() + 11 * 60 * 1000));
+ await backdateReview('dp_pi_warn_swept', 'closed_at', 11 * 60 * 1000);
await closePaymentDisputeAccounts({}, createTestWorkerHelpers());
const decisionId = (await disputes.findReview('dp_pi_warn_swept'))?.enforcement_decision_id ?? null;
expect(decisionId).not.toBeNull();
@@ -1207,7 +1217,7 @@ describe('Plutonium payment disputes', () => {
await openDispute('pi_warn_reversed');
const admin = await staff();
await decide(admin, 'dp_pi_warn_reversed', 'unjustified');
- passWarningDate();
+ await passWarningDate('dp_pi_warn_reversed');
await closeDispute('pi_warn_reversed', 'lost');
const decisionId = String((await disputes.findReview('dp_pi_warn_reversed'))?.enforcement_decision_id);
const reversed = await createBuilder<ReviewResponse & {reversal_note: string}>(harness, admin.token)
@@ -1247,7 +1257,7 @@ describe('Plutonium payment disputes', () => {
await openDispute('pi_warn_ended');
const admin = await staff();
await decide(admin, 'dp_pi_warn_ended', 'unjustified');
- passWarningDate();
+ await passWarningDate('dp_pi_warn_ended');
await closeDispute('pi_warn_ended', 'lost');
const decisionId = String((await disputes.findReview('dp_pi_warn_ended'))?.enforcement_decision_id);
await createBuilder(harness, admin.token)
diff --git a/fluxer_api/src/api/test/TestConstants.ts b/fluxer_api/src/api/test/TestConstants.ts
index 291fac8fa..f2a3241f3 100644
--- a/fluxer_api/src/api/test/TestConstants.ts
+++ b/fluxer_api/src/api/test/TestConstants.ts
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
export const TEST_TIMEOUTS = {
- IMMEDIATE: 20,
QUICK: 100,
} as const;
export const TEST_CREDENTIALS = {
diff --git a/fluxer_api/src/api/user/NewConversationLimit.ts b/fluxer_api/src/api/user/NewConversationLimit.ts
index 7aad1c8d8..54f5c361a 100644
--- a/fluxer_api/src/api/user/NewConversationLimit.ts
+++ b/fluxer_api/src/api/user/NewConversationLimit.ts
@@ -12,7 +12,7 @@ import {RelationshipTypes} from '@fluxer/constants/src/UserConstants';
import {NewConversationsLimitedError} from '@fluxer/errors/src/domains/user/NewConversationsLimitedError';
import type {ICacheService} from '@pkgs/cache/src/ICacheService';
-export const NEW_CONVERSATION_LIMIT_MAX_MS = 7 * 24 * 60 * 60 * 1000;
+const NEW_CONVERSATION_LIMIT_MAX_MS = 7 * 24 * 60 * 60 * 1000;
const RECENT_PAGE = 100;
const OPENING_PAGE = 50;
diff --git a/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.test.ts b/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.test.ts
deleted file mode 100644
index 2d2aa245c..000000000
--- a/fluxer_api/src/api/user/entrance_sound/EntranceSoundService.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createUserID, type EntranceSoundID, type UserID} from '@app/api/BrandedTypes';
-import {Config} from '@app/api/Config';
-import type {IMediaService} from '@app/api/infrastructure/IMediaService';
-import type {IStorageService} from '@app/api/infrastructure/IStorageService';
-import type {EntranceSound} from '@app/api/models/EntranceSound';
-import type {EntranceSoundRepository} from '@app/api/user/entrance_sound/EntranceSoundRepository';
-import {EntranceSoundService} from '@app/api/user/entrance_sound/EntranceSoundService';
-import {describe, expect, it, vi} from 'vitest';
-
-const USER_ID = createUserID(1234567890123456n);
-
-function createWavBase64(sampleCount: number): string {
- const dataLength = sampleCount * 2;
- const buffer = Buffer.alloc(44 + dataLength);
- buffer.write('RIFF', 0, 'ascii');
- buffer.writeUInt32LE(36 + dataLength, 4);
- buffer.write('WAVE', 8, 'ascii');
- buffer.write('fmt ', 12, 'ascii');
- buffer.writeUInt32LE(16, 16);
- buffer.writeUInt16LE(1, 20);
- buffer.writeUInt16LE(1, 22);
- buffer.writeUInt32LE(8000, 24);
- buffer.writeUInt32LE(16000, 28);
- buffer.writeUInt16LE(2, 32);
- buffer.writeUInt16LE(16, 34);
- buffer.write('data', 36, 'ascii');
- buffer.writeUInt32LE(dataLength, 40);
- for (let index = 0; index < sampleCount; index += 1) {
- buffer.writeInt16LE(Math.round(8000 * Math.sin(index / 8)), 44 + index * 2);
- }
- return buffer.toString('base64');
-}
-
-const HALF_SECOND_WAV = createWavBase64(4000);
-const OTHER_WAV = createWavBase64(6000);
-
-class FakeEntranceSoundRepository {
- readonly sounds = new Map<string, EntranceSound>();
- failNextUpsert = false;
-
- async listSounds(_userId: UserID): Promise<Array<EntranceSound>> {
- return [...this.sounds.values()];
- }
-
- async getSound(_userId: UserID, soundId: EntranceSoundID): Promise<EntranceSound | null> {
- return this.sounds.get(soundId.toString()) ?? null;
- }
-
- async upsertSound(sound: EntranceSound): Promise<EntranceSound> {
- if (this.failNextUpsert) {
- this.failNextUpsert = false;
- throw new Error('Failed to persist entrance sound');
- }
- this.sounds.set(sound.soundId.toString(), sound);
- return sound;
- }
-
- async deleteSound(_userId: UserID, soundId: EntranceSoundID): Promise<void> {
- this.sounds.delete(soundId.toString());
- }
-
- async deleteSelectionsForSound(_userId: UserID, _soundId: EntranceSoundID): Promise<void> {}
-}
-
-function createService() {
- const repository = new FakeEntranceSoundRepository();
- const objects = new Set<string>();
- const deleteObject = vi.fn(async (_bucket: string, key: string) => {
- objects.delete(key);
- });
- const storageService = {
- uploadObject: async (params: {key: string}) => {
- objects.add(params.key);
- },
- deleteObject,
- } as unknown as IStorageService;
- const mediaService = {
- getMetadata: async () => ({
- format: 'wav',
- content_type: 'audio/wav',
- content_hash: 'content-hash',
- size: 0,
- duration: 0.5,
- nsfw: false,
- }),
- } as unknown as IMediaService;
- const service = new EntranceSoundService(
- repository as unknown as EntranceSoundRepository,
- storageService,
- mediaService,
- );
- return {service, repository, objects, deleteObject};
-}
-
-function keyFromUrl(url: string): string {
- return url.slice(`${Config.endpoints.media}/`.length);
-}
-
-describe('EntranceSoundService shared object references', () => {
- it('keeps the shared object when one of two entries with identical audio is deleted', async () => {
- const {service, objects, deleteObject} = createService();
- const first = await service.upload({userId: USER_ID, name: 'first', base64Audio: HALF_SECOND_WAV});
- const second = await service.upload({userId: USER_ID, name: 'second', base64Audio: HALF_SECOND_WAV});
- expect(keyFromUrl(second.url)).toBe(keyFromUrl(first.url));
-
- await service.delete(USER_ID, first.sound.soundId);
-
- expect(deleteObject).not.toHaveBeenCalled();
- expect(objects.has(keyFromUrl(second.url))).toBe(true);
-
- await service.delete(USER_ID, second.sound.soundId);
-
- expect(deleteObject).toHaveBeenCalledTimes(1);
- expect(deleteObject).toHaveBeenCalledWith(Config.s3.buckets.cdn, keyFromUrl(second.url));
- expect(objects.size).toBe(0);
- });
-
- it('keeps the shared object when a duplicate upload fails to persist', async () => {
- const {service, repository, objects, deleteObject} = createService();
- const first = await service.upload({userId: USER_ID, name: 'first', base64Audio: HALF_SECOND_WAV});
-
- repository.failNextUpsert = true;
- await expect(service.upload({userId: USER_ID, name: 'duplicate', base64Audio: HALF_SECOND_WAV})).rejects.toThrow(
- 'Failed to persist entrance sound',
- );
-
- expect(deleteObject).not.toHaveBeenCalled();
- expect(objects.has(keyFromUrl(first.url))).toBe(true);
- await expect(service.listLibrary(USER_ID)).resolves.toHaveLength(1);
- });
-
- it('rolls back the object when the only entry referencing it fails to persist', async () => {
- const {service, repository, objects, deleteObject} = createService();
-
- repository.failNextUpsert = true;
- await expect(service.upload({userId: USER_ID, name: 'only', base64Audio: HALF_SECOND_WAV})).rejects.toThrow(
- 'Failed to persist entrance sound',
- );
-
- expect(deleteObject).toHaveBeenCalledTimes(1);
- expect(objects.size).toBe(0);
- });
-
- it('deletes the object for a lone entry and leaves other entries alone', async () => {
- const {service, objects, deleteObject} = createService();
- const lone = await service.upload({userId: USER_ID, name: 'lone', base64Audio: HALF_SECOND_WAV});
- const other = await service.upload({userId: USER_ID, name: 'other', base64Audio: OTHER_WAV});
- expect(keyFromUrl(other.url)).not.toBe(keyFromUrl(lone.url));
-
- await service.delete(USER_ID, lone.sound.soundId);
-
- expect(deleteObject).toHaveBeenCalledTimes(1);
- expect(deleteObject).toHaveBeenCalledWith(Config.s3.buckets.cdn, keyFromUrl(lone.url));
- expect(objects.has(keyFromUrl(other.url))).toBe(true);
- });
-});
diff --git a/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts b/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts
index d90600f69..254d7a422 100644
--- a/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts
+++ b/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts
@@ -26,7 +26,7 @@ import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {MS_PER_DAY, MS_PER_HOUR, MS_PER_MINUTE} from '@fluxer/date_utils/src/DateConstants';
import {EmailService} from '@pkgs/email/src/EmailService';
import {SmtpEmailProvider} from '@pkgs/email/src/SmtpEmailProvider';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
const SESSION_HASH_BYTES = 32;
const EXTRA_SESSION_COUNT = 250;
@@ -94,10 +94,9 @@ describe('Account closure and credentials', () => {
await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
});
- test('a session of a user with the DELETED flag is refused and revoked', async () => {
+ test('a session of a user with the DELETED flag is refused', async () => {
const account = await createTestAccount(harness);
- const userId = createUserID(BigInt(account.userId));
- await markDeleted(userId);
+ await markDeleted(createUserID(BigInt(account.userId)));
await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
});
@@ -308,6 +307,7 @@ describe('Account closure and credentials', () => {
},
provider,
);
+ const requestedAt = Date.now();
deletionRequest = harness.requestJson({
path: '/users/@me/delete',
method: 'POST',
@@ -322,18 +322,18 @@ describe('Account closure and credentials', () => {
expect(smtp.attempts[0]?.to).toBe(`<${account.email}>`);
smtp.release();
const response = await deletionRequest;
+ const respondedAt = Date.now();
expect(response.status).toBe(HTTP_STATUS.NO_CONTENT);
expect(smtp.delivered).toEqual([]);
expect(await new AuthSessionRepository().listAuthSessions(userId)).toEqual([]);
const user = await storedUser(userId);
- expect(user.pendingDeletionAt?.toISOString()).toBe('2030-01-02T00:00:00.000Z');
+ const pendingDeletionAt = user.pendingDeletionAt?.getTime() ?? 0;
+ expect(pendingDeletionAt).toBeGreaterThanOrEqual(requestedAt + DELETION_GRACE_HOURS * MS_PER_HOUR);
+ expect(pendingDeletionAt).toBeLessThanOrEqual(respondedAt + DELETION_GRACE_HOURS * MS_PER_HOUR);
expect(user.flags & UserFlags.SELF_DELETED).toBe(UserFlags.SELF_DELETED);
- expect(
- await getKVAccountDeletionQueue().getReadyDeletions(
- new Date('2030-01-02T00:00:00Z').getTime(),
- DELETION_QUEUE_LIMIT,
- ),
- ).toEqual([{userId, deletionReasonCode: 1}]);
+ expect(await getKVAccountDeletionQueue().getReadyDeletions(pendingDeletionAt, DELETION_QUEUE_LIMIT)).toEqual([
+ {userId, deletionReasonCode: 1},
+ ]);
await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
});
});
diff --git a/fluxer_api/src/api/user/tests/AccountDeleteLargeFootprint.test.ts b/fluxer_api/src/api/user/tests/AccountDeleteLargeFootprint.test.ts
index d8ec65157..124d6ff09 100644
--- a/fluxer_api/src/api/user/tests/AccountDeleteLargeFootprint.test.ts
+++ b/fluxer_api/src/api/user/tests/AccountDeleteLargeFootprint.test.ts
@@ -6,12 +6,11 @@ import {fetchMany} from '@app/api/database/CassandraQueryExecution';
import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {Notes, RelationshipsByTarget} from '@app/api/Tables';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {UserRelationshipRepository} from '@app/api/user/repositories/UserRelationshipRepository';
import {deleteAccount, setPendingDeletionAt, waitForDeletionCompletion} from '@app/api/user/tests/UserTestUtils';
import {RelationshipTypes} from '@fluxer/constants/src/UserConstants';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
const RELATIONSHIPS_EACH_WAY = 320;
const GUILD_BANS = 150;
@@ -28,11 +27,10 @@ describe('Deleting an account with a large footprint', () => {
harness = await createApiTestHarness();
});
afterEach(async () => {
- vi.restoreAllMocks();
await harness?.shutdown();
});
- test('relationships, guild bans and notes are removed in bounded batches', async () => {
+ test('removes every relationship, guild ban and note', async () => {
const account = await createTestAccount(harness);
const userId = createUserID(BigInt(account.userId));
const relationships = new UserRelationshipRepository();
@@ -71,13 +69,11 @@ describe('Deleting an account with a large footprint', () => {
}
await deleteAccount(harness, account.token, account.password);
await setPendingDeletionAt(harness, account.userId, new Date(Date.now() - 60_000));
- const batchSpy = vi.spyOn(InMemoryCassandraQueryExecutor.prototype, 'executeBatch');
const result = await createBuilderWithoutAuth<{errors?: Array<{error: string}>}>(harness)
.post('/test/worker/process-pending-deletions')
.execute();
expect(result.errors ?? []).toEqual([]);
await waitForDeletionCompletion(harness, account.userId);
- expect(Math.max(...batchSpy.mock.calls.map(([queries]) => queries.length))).toBeLessThanOrEqual(60);
expect(await relationships.listRelationships(userId)).toHaveLength(0);
const pointingAtUser = await fetchMany(
RelationshipsByTarget.selectCql({where: RelationshipsByTarget.where.eq('target_user_id')}),
diff --git a/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts b/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts
index 2c9cd3108..40c2deb2a 100644
--- a/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts
+++ b/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts
@@ -4,15 +4,13 @@ import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/te
import {decisionBody} from '@app/api/enforcement/tests/EnforcementTestUtils';
import {getMember, setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {profilePseudonym} from '@app/api/user/ProfileVisibility';
import {fetchUser, fetchUserMe, fetchUserProfile} from '@app/api/user/tests/UserTestUtils';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
-import type {GuildMemberResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
const PROFILE_HIDDEN_BIT = Number(UserFlags.PROFILE_HIDDEN);
@@ -63,7 +61,6 @@ describe('hidden profiles', () => {
});
afterEach(async () => {
- vi.restoreAllMocks();
await harness?.shutdown();
});
@@ -98,18 +95,7 @@ describe('hidden profiles', () => {
expect(users[0]).toMatchObject({username: targetName, global_name: 'Shown Name', bio: 'shown bio'});
}
- function memberUpdates(): Array<GuildMemberResponse> {
- const dispatch = vi.mocked(NoopGatewayService.prototype.dispatchGuild);
- return dispatch.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'GUILD_MEMBER_UPDATE' && params.guildId.toString() === guildId)
- .map((params) => params.data as GuildMemberResponse)
- .filter((member) => member.user.id === target.userId);
- }
-
- test('a staff ban hides the profile until the unban restores it, and clients are told both ways', async () => {
- vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- const presence = vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence');
+ test('a staff ban hides the profile until the unban restores it', async () => {
const {user: suspended} = await createBuilder<{user: {enforcement_decision_id: string}}>(harness, admin.token)
.put(`/admin/users/${target.userId}/ban`)
.header('X-Audit-Log-Reason', 'Test suspension')
@@ -121,25 +107,12 @@ describe('hidden profiles', () => {
.execute();
await expectHidden();
await expectStaffSeeStoredProfile();
- expect(memberUpdates().map((member) => [member.user.username, member.user.discriminator, member.nick])).toEqual([
- [pseudonym.username, pseudonym.discriminator, null],
- ]);
- const ownUpdates = presence.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'USER_UPDATE' && params.userId.toString() === target.userId)
- .map((params) => params.data as {username: string});
- expect(ownUpdates.length).toBeGreaterThan(0);
- expect(ownUpdates.every((update) => update.username === targetName)).toBe(true);
await createBuilder(harness, admin.token)
.post(`/admin/enforcement-decisions/${suspended.enforcement_decision_id}/end`)
.body({outcome: 'lifted'})
.expect(HTTP_STATUS.OK)
.execute();
await expectShown();
- expect(memberUpdates().map((member) => [member.user.username, member.nick])).toEqual([
- [pseudonym.username, null],
- [targetName, 'Shown Nick'],
- ]);
});
async function endDecision(decisionId: string) {
diff --git a/fluxer_api/src/api/user/tests/PrivateChannelSettingsPushSync.test.ts b/fluxer_api/src/api/user/tests/PrivateChannelSettingsPushSync.test.ts
deleted file mode 100644
index a03f445ac..000000000
--- a/fluxer_api/src/api/user/tests/PrivateChannelSettingsPushSync.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {GatewayRpcClient} from '@app/api/infrastructure/GatewayRpcClient';
-import {GatewayRpcMethodError, GatewayRpcMethodErrorCodes} from '@app/api/infrastructure/GatewayRpcError';
-import {GatewayService} from '@app/api/infrastructure/GatewayService';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {updateGuildSettings} from '@app/api/user/tests/UserTestUtils';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-const DM_CHANNEL_ID = '1500000000000000005';
-const MUTE_DM = {
- channel_overrides: {
- [DM_CHANNEL_ID]: {collapsed: false, message_notifications: 3, muted: true, mute_config: null},
- },
-};
-
-function gatewayRejectingSyncWith(code: string): GatewayService {
- GatewayRpcClient.createForTests({
- async call(): Promise<unknown> {
- throw new GatewayRpcMethodError(code);
- },
- async destroy(): Promise<void> {},
- });
- return new GatewayService();
-}
-
-function routeSyncThrough(gateway: GatewayService): void {
- vi.spyOn(NoopGatewayService.prototype, 'syncPushUserGuildSettings').mockImplementation((params) =>
- gateway.syncPushUserGuildSettings(params),
- );
-}
-
-describe('Private channel settings push sync', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterEach(async () => {
- vi.restoreAllMocks();
- await GatewayRpcClient.resetForTests();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- it('syncs a muted DM to the push cache under the private scope', async () => {
- const account = await createTestAccount(harness);
- const syncPush = vi.spyOn(NoopGatewayService.prototype, 'syncPushUserGuildSettings');
-
- await updateGuildSettings(harness, account.token, MUTE_DM);
-
- expect(syncPush).toHaveBeenCalledTimes(1);
- const [params] = syncPush.mock.calls[0]!;
- expect(params.userId.toString()).toBe(account.userId);
- expect(params.guildId.toString()).toBe('0');
- expect(params.settings).toMatchObject({
- guild_id: null,
- channel_overrides: {[DM_CHANNEL_ID]: {muted: true}},
- });
- });
-
- it('fails the DM settings update on any other gateway sync error', async () => {
- const account = await createTestAccount(harness);
- routeSyncThrough(gatewayRejectingSyncWith(GatewayRpcMethodErrorCodes.INTERNAL_ERROR));
-
- await createBuilder(harness, account.token)
- .patch('/users/@me/guilds/@me/settings')
- .body(MUTE_DM)
- .expect(502)
- .execute();
- });
-});
diff --git a/fluxer_api/src/api/user/tests/ProfileVisibility.test.ts b/fluxer_api/src/api/user/tests/ProfileVisibility.test.ts
index 5382cc374..caf4a30bf 100644
--- a/fluxer_api/src/api/user/tests/ProfileVisibility.test.ts
+++ b/fluxer_api/src/api/user/tests/ProfileVisibility.test.ts
@@ -2,11 +2,8 @@
import {createGuildID, createUserID} from '@app/api/BrandedTypes';
import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';
-import {mapGuildMemberToResponse} from '@app/api/guild/GuildModel';
-import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
import {LimitConfigService, resetGlobalLimitConfigServiceForTesting} from '@app/api/limits/LimitConfigService';
-import {createRequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import {GuildMember} from '@app/api/models/GuildMember';
import {User} from '@app/api/models/User';
import {isHiddenPartial, isProfileHidden, isUnderEnforcement, profilePseudonym} from '@app/api/user/ProfileVisibility';
@@ -197,7 +194,7 @@ describe('profile visibility', () => {
expect(isUnderEnforcement(user({flags: UserFlags.SPAMMER}), NOW)).toBe(true);
});
- it('hides guild-specific profile details for a hidden member', async () => {
+ it('hides guild-specific profile details for a hidden member', () => {
const member = new GuildMember({
guild_id: createGuildID(5n),
user_id: createUserID(USER_ID),
@@ -220,17 +217,6 @@ describe('profile visibility', () => {
profile_flags: null,
version: 1,
});
- const cache = (partial: ReturnType<typeof mapUserToPartialResponse>) =>
- ({getUserPartialResponse: async () => partial}) as unknown as Pick<UserCacheService, 'getUserPartialResponse'>;
- const hidden = await mapGuildMemberToResponse(
- member,
- cache(mapUserToPartialResponse(user({flags: UserFlags.SPAMMER}))),
- createRequestCache(),
- );
- expect(hidden).toMatchObject({nick: null, avatar: null, banner: null, accent_color: null});
- expect(hidden.user).toMatchObject(profilePseudonym(USER_ID));
- const shown = await mapGuildMemberToResponse(member, cache(mapUserToPartialResponse(user())), createRequestCache());
- expect(shown).toMatchObject({nick: 'Countess', avatar: 'm4v', banner: 'm8n', accent_color: 12});
expect(mapGuildMemberToProfileResponse(member, {hidden: true})).toEqual({
bio: null,
pronouns: null,
diff --git a/fluxer_api/src/api/user/tests/PushOriginReplacement.test.ts b/fluxer_api/src/api/user/tests/PushOriginReplacement.test.ts
index 2f8a30dd1..3432ffb9e 100644
--- a/fluxer_api/src/api/user/tests/PushOriginReplacement.test.ts
+++ b/fluxer_api/src/api/user/tests/PushOriginReplacement.test.ts
@@ -6,7 +6,7 @@ import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {classifyWebPushOrigin, sameUserAgentFamily} from '@app/api/user/services/WebPushOriginReplacement';
import {listPushSubscriptions} from '@app/api/user/tests/UserTestUtils';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const LEGACY_ORIGIN = 'https://web.fluxer.app';
const TARGET_ORIGIN = 'https://fluxer.com';
@@ -85,9 +85,6 @@ describe('web push origin replacement', () => {
afterAll(async () => {
await harness?.shutdown();
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
async function subscribeFrom(
token: string,
@@ -300,30 +297,6 @@ describe('web push origin replacement', () => {
expect(await listSubscriptionIds(approver.token)).toEqual([approverSubscription, paired].sort());
});
- it('completes the approval when the predecessor link cannot be written', async () => {
- const account = await createTestAccount(harness);
- const approver = await loginAccount(harness, account);
- const setex = harness.kvProvider.setex.bind(harness.kvProvider);
- vi.spyOn(harness.kvProvider, 'setex').mockImplementation(async (key, ttl, value) => {
- if (key.startsWith('push_session_predecessor:')) throw new Error('kv down');
- return setex(key, ttl, value);
- });
- const pairedToken = await pairNewSession(approver.token, approver.userId, LEGACY_ORIGIN);
- expect(pairedToken).toBeTruthy();
- });
-
- it('stores a subscribe when the replacement marker cannot be read or written', async () => {
- const account = await createTestAccount(harness);
- const get = harness.kvProvider.get.bind(harness.kvProvider);
- vi.spyOn(harness.kvProvider, 'get').mockImplementation(async (key) => {
- if (key.startsWith('push_origin_replaced:')) throw new Error('kv down');
- return get(key);
- });
- const target = await subscribeFrom(account.token, TARGET_ORIGIN, 'https://push.example.com/target');
- const legacy = await subscribeFrom(account.token, LEGACY_ORIGIN, 'https://push.example.com/legacy');
- expect(await listSubscriptionIds(account.token)).toEqual([legacy, target].sort());
- });
-
it('keeps an installed legacy app subscribed when only a browser tab moved', async () => {
const account = await createTestAccount(harness);
const installed = await subscribeFrom(account.token, LEGACY_ORIGIN, 'https://push.example.com/legacy-app', {
diff --git a/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts b/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts
index 88b4b1563..c8be5327c 100644
--- a/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts
+++ b/fluxer_api/src/api/user/tests/ThreadUserSettings.test.ts
@@ -11,7 +11,7 @@ import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import {ChannelOverrideFlags} from '@fluxer/constants/src/ThreadConstants';
import type {UserGuildSettingsResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const repository = new ChannelRepository();
diff --git a/fluxer_api/src/api/user/tests/UserProfileCacheInvalidation.test.ts b/fluxer_api/src/api/user/tests/UserProfileCacheInvalidation.test.ts
deleted file mode 100644
index bbe403340..000000000
--- a/fluxer_api/src/api/user/tests/UserProfileCacheInvalidation.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createFriendship} from '@app/api/channel/tests/ChannelTestUtils';
-import {UserCacheService} from '@app/api/infrastructure/UserCacheService';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import type {UserProfileFullResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
-
-describe('User Profile Cache Invalidation', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- it('resolves the profile subject and mutual friends without invalidating the users service cache', async () => {
- const viewerAccount = await createTestAccount(harness);
- const targetAccount = await createTestAccount(harness);
- const mutualAccount = await createTestAccount(harness);
- await createFriendship(harness, viewerAccount, targetAccount);
- await createFriendship(harness, viewerAccount, mutualAccount);
- await createFriendship(harness, targetAccount, mutualAccount);
- const invalidateUserCache = vi.spyOn(UserCacheService.prototype, 'invalidateUserCache');
-
- try {
- const profile = await createBuilder<UserProfileFullResponse>(harness, viewerAccount.token)
- .get(`/users/${targetAccount.userId}/profile?with_mutual_friends=true`)
- .execute();
-
- expect(profile.user.id).toBe(targetAccount.userId);
- expect(profile.mutual_friends?.map((friend) => friend.id)).toEqual([mutualAccount.userId]);
- expect(invalidateUserCache).not.toHaveBeenCalled();
- } finally {
- invalidateUserCache.mockRestore();
- }
- });
-});
diff --git a/fluxer_api/src/api/user/tests/UserProfileGuildPropagation.test.ts b/fluxer_api/src/api/user/tests/UserProfileGuildPropagation.test.ts
deleted file mode 100644
index 76765a79f..000000000
--- a/fluxer_api/src/api/user/tests/UserProfileGuildPropagation.test.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createUserID} from '@app/api/BrandedTypes';
-import {createTestGuild, getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
-import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {updateAvatar} from '@app/api/user/tests/UserTestUtils';
-import type {GuildMemberResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, type MockInstance, vi} from 'vitest';
-
-type DispatchGuildSpy = MockInstance<NoopGatewayService['dispatchGuild']>;
-
-interface MemberUpdateDispatch {
- guildId: {toString(): string};
- event: string;
- data: GuildMemberResponse;
-}
-
-function memberUpdatesFor(dispatchGuild: DispatchGuildSpy, guildId: string): Array<MemberUpdateDispatch> {
- return dispatchGuild.mock.calls
- .map(([params]) => params as unknown as MemberUpdateDispatch)
- .filter((params) => params.event === 'GUILD_MEMBER_UPDATE' && params.guildId.toString() === guildId);
-}
-
-describe('User Profile Guild Propagation', () => {
- let harness: ApiTestHarness;
- beforeAll(async () => {
- harness = await createApiTestHarness();
- });
- beforeEach(async () => {
- await harness.reset();
- });
- afterEach(() => {
- vi.restoreAllMocks();
- });
- afterAll(async () => {
- await harness?.shutdown();
- });
-
- it('pushes the new avatar to every guild the user is in', async () => {
- const account = await createTestAccount(harness);
- const guild = await createTestGuild(harness, account.token);
- const dispatchGuild = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
-
- const updated = await updateAvatar(harness, account.token, getPngDataUrl());
-
- expect(updated.avatar).toBeTruthy();
- const updates = memberUpdatesFor(dispatchGuild, guild.id);
- expect(updates).toHaveLength(1);
- expect(updates[0]!.data.user.id).toBe(account.userId);
- expect(updates[0]!.data.user.avatar).toBe(updated.avatar);
- });
-
- it('does not push a member update when no partial field changed', async () => {
- const account = await createTestAccount(harness);
- const guild = await createTestGuild(harness, account.token);
- const dispatchGuild = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
-
- await updateAvatar(harness, account.token, null);
-
- expect(memberUpdatesFor(dispatchGuild, guild.id)).toHaveLength(0);
- });
-
- it('still updates guild members after the committed profile cannot publish its private update', async () => {
- const account = await createTestAccount(harness);
- const guild = await createTestGuild(harness, account.token);
- const dispatchGuild = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
- vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence').mockImplementation(async ({event}) => {
- if (event === 'USER_UPDATE') throw new Error('gateway publish failed');
- });
-
- await createBuilder(harness, account.token)
- .patch('/users/@me')
- .body({avatar: getPngDataUrl()})
- .expect(500)
- .execute();
-
- const stored = await new UserRepository().findUnique(createUserID(BigInt(account.userId)));
- expect(stored?.avatarHash).toBeTruthy();
- const updates = memberUpdatesFor(dispatchGuild, guild.id);
- expect(updates).toHaveLength(1);
- expect(updates[0]!.data.user.avatar).toBe(stored?.avatarHash);
- });
-});
diff --git a/fluxer_api/src/api/user/tests/UserTestUtils.ts b/fluxer_api/src/api/user/tests/UserTestUtils.ts
index 875cab014..7b33ec701 100644
--- a/fluxer_api/src/api/user/tests/UserTestUtils.ts
+++ b/fluxer_api/src/api/user/tests/UserTestUtils.ts
@@ -125,24 +125,6 @@ export async function deleteAccount(harness: ApiTestHarness, token: string, pass
await createBuilder<void>(harness, token).post('/users/@me/delete').body({password}).expect(204).execute();
}
-export async function updateGuildSettings(
- harness: ApiTestHarness,
- token: string,
- data: Record<string, unknown>,
-): Promise<{
- response: Response;
- json: unknown;
-}> {
- const {response, json} = await createBuilder<unknown>(harness, token)
- .patch('/users/@me/guilds/@me/settings')
- .body(data)
- .executeWithResponse();
- if (response.status !== 200) {
- throw new Error(`Expected 200, got ${response.status}`);
- }
- return {response, json};
-}
-
export async function expectDataExists(
harness: ApiTestHarness,
userId: string,
diff --git a/fluxer_api/src/api/utils/AgeUtils.test.ts b/fluxer_api/src/api/utils/AgeUtils.test.ts
index e6a4b7997..83ae0eca0 100644
--- a/fluxer_api/src/api/utils/AgeUtils.test.ts
+++ b/fluxer_api/src/api/utils/AgeUtils.test.ts
@@ -3,7 +3,7 @@
import {getCachedAccountsConfig, setCachedAccountsConfig} from '@app/api/instance/AccountsConfigCache';
import {calculateAge, canUserAccessNsfwContent, parseDateOfBirth} from '@app/api/utils/AgeUtils';
import {DateOfBirthPolicies, type DateOfBirthPolicy} from '@fluxer/constants/src/AccountConfigConstants';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, describe, expect, it, vi} from 'vitest';
function setDateOfBirthPolicy(dateOfBirth: DateOfBirthPolicy): void {
setCachedAccountsConfig({
diff --git a/fluxer_api/src/api/utils/tests/FetchUtils.test.ts b/fluxer_api/src/api/utils/tests/FetchUtils.test.ts
index 488b85551..ec45e0441 100644
--- a/fluxer_api/src/api/utils/tests/FetchUtils.test.ts
+++ b/fluxer_api/src/api/utils/tests/FetchUtils.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import * as FetchUtils from '@app/api/utils/FetchUtils';
-import {describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
function createStream(chunks: Array<string>): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
@@ -65,29 +65,17 @@ describe('streamToBufferWithLimit', () => {
});
it('rejects an oversized response without waiting for cancellation to finish', async () => {
- vi.useFakeTimers();
- const cancelled = Promise.withResolvers<void>();
- const cleanup = Promise.withResolvers<void>();
const stream = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(5));
},
cancel() {
- cancelled.resolve();
- return cleanup.promise;
+ return new Promise<void>(() => {});
},
});
- const settled = vi.fn();
- const result = FetchUtils.streamToBufferWithLimit(stream, {maxBytes: 4}).then(settled, settled);
- try {
- await cancelled.promise;
- await vi.advanceTimersByTimeAsync(0);
- expect(settled).toHaveBeenCalledExactlyOnceWith(expect.any(FetchUtils.ResponseBodyTooLargeError));
- expect(stream.locked).toBe(false);
- } finally {
- cleanup.resolve();
- await result;
- vi.useRealTimers();
- }
+ await expect(FetchUtils.streamToBufferWithLimit(stream, {maxBytes: 4})).rejects.toBeInstanceOf(
+ FetchUtils.ResponseBodyTooLargeError,
+ );
+ expect(stream.locked).toBe(false);
});
});
diff --git a/fluxer_api/src/api/webhook/tests/ChannelFollow.test.ts b/fluxer_api/src/api/webhook/tests/ChannelFollow.test.ts
index 30841a071..53a4f1590 100644
--- a/fluxer_api/src/api/webhook/tests/ChannelFollow.test.ts
+++ b/fluxer_api/src/api/webhook/tests/ChannelFollow.test.ts
@@ -18,7 +18,6 @@ import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {phraseBlocklistCache} from '@app/api/middleware/PhraseBlocklistCache';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {setLimitOverride} from '@app/api/test/LimitTestUtils';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {createWebhook, getChannelWebhooks} from '@app/api/webhook/tests/WebhookTestUtils';
@@ -33,7 +32,7 @@ import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSc
import type {GuildAuditLogListResponse} from '@fluxer/schema/src/domains/guild/GuildAuditLogSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import {WebhookListResponse} from '@fluxer/schema/src/domains/webhook/WebhookSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
async function listMessages(harness: ApiTestHarness, token: string, channelId: string) {
return createBuilder<Array<MessageResponse>>(harness, token).get(`/channels/${channelId}/messages`).execute();
@@ -64,10 +63,6 @@ describe('Channel follow', () => {
world = await announcementWorld(harness);
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
await harness?.shutdown();
});
@@ -136,35 +131,26 @@ describe('Channel follow', () => {
const {b} = world;
const source = await createAnnouncementSourceGuild(harness, 'Forbidden Words Guild');
await addGuildMember(harness, source.owner, source.guild, b.owner);
- vi.spyOn(phraseBlocklistCache, 'containsBannedPhrase').mockImplementation((text) =>
- text.includes('Forbidden Words'),
- );
+ phraseBlocklistCache.add('Forbidden Words');
const followed = await follow(harness, b.owner.token, source.ann.id, b.t1.id);
- vi.restoreAllMocks();
+ phraseBlocklistCache.remove('Forbidden Words');
const webhooks = await getChannelWebhooks(harness, b.t1.id, b.owner.token);
expect(webhooks.find((candidate) => candidate.id === followed.webhook_id)?.name).toBe('#news');
});
test('rejects the follow when the fallback name also fails moderation', async () => {
const {a, b} = world;
- vi.spyOn(phraseBlocklistCache, 'containsBannedPhrase').mockImplementation((text) => text.includes('news'));
+ phraseBlocklistCache.add('news');
await followRequest(harness, b.owner.token, a.ann.id, b.t1.id)
.expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.CONTENT_BLOCKED)
.execute();
- vi.restoreAllMocks();
+ phraseBlocklistCache.remove('news');
expect(await getChannelWebhooks(harness, b.t1.id, b.owner.token)).toHaveLength(0);
});
test('posts a CHANNEL_FOLLOW_ADD system message whose reference has no message id', async () => {
const {a, b} = world;
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
const followed = await follow(harness, b.owner.token, a.ann.id, b.t1.id);
- const webhookUpdates = dispatchSpy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'WEBHOOKS_UPDATE');
- expect(webhookUpdates).toEqual([
- expect.objectContaining({guildId: createGuildID(BigInt(b.guild.id)), data: {channel_id: b.t1.id}}),
- ]);
const webhooks = await getChannelWebhooks(harness, b.t1.id, b.owner.token);
const webhookName = webhooks.find((candidate) => candidate.id === followed.webhook_id)!.name;
const messages = await listMessages(harness, b.owner.token, b.t1.id);
@@ -323,27 +309,6 @@ describe('Channel follow', () => {
}
});
- test('undoes a follow whose source stopped being an announcement channel mid-request', async () => {
- const {a, b} = world;
- const originalCreate = WebhookRepository.prototype.create;
- vi.spyOn(WebhookRepository.prototype, 'create').mockImplementation(async function (this: WebhookRepository, data) {
- const created = await originalCreate.call(this, data);
- await createBuilder(harness, a.owner.token).patch(`/channels/${a.ann.id}`).body({type: 0}).execute();
- return created;
- });
- await followRequest(harness, b.owner.token, a.ann.id, b.t1.id)
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.ANNOUNCEMENT_CHANNEL_REQUIRED)
- .execute();
- vi.restoreAllMocks();
- expect(await getChannelWebhooks(harness, b.t1.id, b.owner.token)).toHaveLength(0);
- expect(await new WebhookRepository().countBySourceChannel(createChannelID(BigInt(a.ann.id)))).toEqual({
- channelCount: 0,
- guildCount: 0,
- });
- const messages = await listMessages(harness, b.owner.token, b.t1.id);
- expect(messages.some((message) => message.type === MessageTypes.CHANNEL_FOLLOW_ADD)).toBe(false);
- });
-
test('refuses to follow while the source guild has announcement channels disabled', async () => {
const {a, b} = world;
await setGuildFeatures(harness, a.guild.id, {add: [GuildFeatures.ANNOUNCEMENT_CHANNELS_DISABLED]});
diff --git a/fluxer_api/src/api/webhook/tests/FollowerWebhookManagement.test.ts b/fluxer_api/src/api/webhook/tests/FollowerWebhookManagement.test.ts
index 7ed6f5c3d..dc1d7064a 100644
--- a/fluxer_api/src/api/webhook/tests/FollowerWebhookManagement.test.ts
+++ b/fluxer_api/src/api/webhook/tests/FollowerWebhookManagement.test.ts
@@ -26,7 +26,6 @@ import {
import {getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
import {processRecordedGuildDeletions, recordGuildDeletions} from '@app/api/guild/tests/GuildDeletionTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {createWebhook, getChannelWebhooks, getGuildWebhooks} from '@app/api/webhook/tests/WebhookTestUtils';
@@ -38,16 +37,7 @@ import {ChannelTypes, MessageFlags, Permissions, WebhookTypes} from '@fluxer/con
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import type {GuildAuditLogListResponse} from '@fluxer/schema/src/domains/guild/GuildAuditLogSchemas';
import {WebhookListResponse, WebhookResponse} from '@fluxer/schema/src/domains/webhook/WebhookSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi} from 'vitest';
-
-function webhooksUpdateChannels(spy: {
- mock: {calls: Array<Parameters<NoopGatewayService['dispatchGuild']>>};
-}): Array<string> {
- return spy.mock.calls
- .map(([params]) => params)
- .filter((params) => params.event === 'WEBHOOKS_UPDATE')
- .map((params) => (params.data as {channel_id: string}).channel_id);
-}
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
async function sourceIndex(sourceChannelId: string) {
return new WebhookRepository().listIdsBySourceChannel(createChannelID(BigInt(sourceChannelId)), {limit: 100});
@@ -66,10 +56,6 @@ describe('Follower webhook management', () => {
world = await announcementWorld(harness);
});
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
afterAll(async () => {
await harness?.shutdown();
});
@@ -165,7 +151,6 @@ describe('Follower webhook management', () => {
test('moves a follower webhook to another text channel and notifies both channels', async () => {
const {a, b} = world;
const followed = await follow(harness, b.owner.token, a.ann.id, b.t1.id);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
const moved = await createBuilder<WebhookResponse>(harness, b.owner.token)
.patch(`/webhooks/${followed.webhook_id}`)
.body({channel_id: b.t2.id})
@@ -174,7 +159,6 @@ describe('Follower webhook management', () => {
expect(moved.type).toBe(WebhookTypes.CHANNEL_FOLLOWER);
expect(moved.source_guild?.id).toBe(a.guild.id);
expect(moved.source_channel?.id).toBe(a.ann.id);
- expect(webhooksUpdateChannels(dispatchSpy).sort()).toEqual([b.t1.id, b.t2.id].sort());
expect(await sourceIndex(a.ann.id)).toEqual([
{webhookId: BigInt(followed.webhook_id), guildId: createGuildID(BigInt(b.guild.id))},
]);
@@ -231,48 +215,14 @@ describe('Follower webhook management', () => {
expect((await findWebhookRow(followed.webhook_id))?.channelId?.toString()).toBe(b.t1.id);
});
- test('a follower webhook move loses to a concurrent conversion of the target to announcement', async () => {
- const {a, b} = world;
- const followed = await follow(harness, b.owner.token, a.ann.id, b.t1.id);
- const originalCount = WebhookRepository.prototype.countByChannel;
- let converted = false;
- vi.spyOn(WebhookRepository.prototype, 'countByChannel').mockImplementation(async function (
- this: WebhookRepository,
- channelId,
- ) {
- const result = await originalCount.call(this, channelId);
- if (!converted && channelId.toString() === b.t2.id) {
- converted = true;
- await createBuilder(harness, b.owner.token)
- .patch(`/channels/${b.t2.id}`)
- .body({type: ChannelTypes.GUILD_ANNOUNCEMENT})
- .expect(HTTP_STATUS.OK)
- .execute();
- }
- return result;
- });
- await createBuilder(harness, b.owner.token)
- .patch(`/webhooks/${followed.webhook_id}`)
- .body({channel_id: b.t2.id})
- .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_FOLLOW_TARGET_CHANNEL)
- .execute();
- vi.restoreAllMocks();
- expect(converted).toBe(true);
- expect((await findWebhookRow(followed.webhook_id))?.channelId?.toString()).toBe(b.t1.id);
- const t2Webhooks = await new WebhookRepository().listByChannel(createChannelID(BigInt(b.t2.id)));
- expect(t2Webhooks.filter((webhook) => webhook.type === WebhookTypes.CHANNEL_FOLLOWER)).toHaveLength(0);
- });
-
test('unfollows by deleting the follower webhook', async () => {
const {a, b} = world;
const followed = await follow(harness, b.owner.token, a.ann.id, b.t1.id);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await createBuilder(harness, b.owner.token)
.delete(`/webhooks/${followed.webhook_id}`)
.header('X-Audit-Log-Reason', 'no longer needed')
.expect(HTTP_STATUS.NO_CONTENT)
.execute();
- expect(webhooksUpdateChannels(dispatchSpy)).toEqual([b.t1.id]);
expect(await findWebhookRow(followed.webhook_id)).toBeNull();
expect(await sourceIndex(a.ann.id)).toEqual([]);
const auditLog = await createBuilder<GuildAuditLogListResponse>(harness, b.owner.token)
@@ -374,7 +324,6 @@ describe('Follower webhook delivery', () => {
afterEach(() => {
disableCrosspostWorker();
- vi.restoreAllMocks();
});
afterAll(async () => {
@@ -463,7 +412,6 @@ describe('Follower webhook delivery', () => {
await followInto(harness, world, world.b.t1.id);
const {copy} = await publishedCopyWithImage(world.b.t1.id);
const admin = await setUserACLs(harness, world.a.member, ['admin:authenticate', 'guild:lookup', 'guild:delete']);
- const dispatchSpy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild');
await createBuilder(harness, admin.token)
.delete(`/admin/guilds/${world.a.guild.id}`)
.body({basis: {type: 'holder_request'}})
@@ -473,14 +421,6 @@ describe('Follower webhook delivery', () => {
expect(world.worker.deadLetters).toHaveLength(0);
expect(await readRow(world.b.t1.id, copy.id)).toBeNull();
expectNoTargetObjectsDeleted();
- expect(
- dispatchSpy.mock.calls.some(
- ([params]) =>
- params.event === 'MESSAGE_DELETE' &&
- params.guildId.toString() === world.b.guild.id &&
- (params.data as {id: string}).id === copy.id,
- ),
- ).toBe(true);
});
test('delivery pauses while the creator cannot view the source and resumes when they rejoin', async () => {
diff --git a/fluxer_api/src/api/webhook/tests/WebhookForumThreads.test.ts b/fluxer_api/src/api/webhook/tests/WebhookForumThreads.test.ts
index 3f9dd7b53..d44cb47f7 100644
--- a/fluxer_api/src/api/webhook/tests/WebhookForumThreads.test.ts
+++ b/fluxer_api/src/api/webhook/tests/WebhookForumThreads.test.ts
@@ -1,13 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {MessageSendService} from '@app/api/channel/services/message/MessageSendService';
import {createChannel, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
@@ -16,7 +14,7 @@ import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/Thr
import type {GuildAuditLogListResponse} from '@fluxer/schema/src/domains/guild/GuildAuditLogSchemas';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import type {WebhookResponse} from '@fluxer/schema/src/domains/webhook/WebhookSchemas';
-import {afterAll, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface Setup {
owner: TestAccount;
@@ -86,41 +84,13 @@ describe('webhooks on forum and media channels', () => {
it('rejects an invalid starter before creating the post', async () => {
const s = await setup();
- const dispatched: Array<string> = [];
- const spy = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild').mockImplementation(async (params) => {
- dispatched.push(params.event);
- });
await execute(s, {thread_name: 'empty'}).expect(400, APIErrorCodes.CANNOT_SEND_EMPTY_MESSAGE).execute();
- spy.mockRestore();
- expect(dispatched).not.toContain('THREAD_CREATE');
const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token)
.get(`/channels/${s.forum.id}`)
.execute();
expect(forum.last_message_id ?? null).toBeNull();
});
- it('rolls clients back to the previous forum last_message_id when the starter fails', async () => {
- const s = await setup();
- const first = await execute(s, {content: 'first', thread_name: 'first'}).execute();
- const dispatched: Array<{event: string; data: unknown}> = [];
- const dispatch = vi.spyOn(NoopGatewayService.prototype, 'dispatchGuild').mockImplementation(async (params) => {
- dispatched.push({event: params.event, data: params.data});
- });
- const send = vi
- .spyOn(MessageSendService.prototype, 'sendWebhookMessage')
- .mockRejectedValueOnce(new Error('starter failed'));
- await execute(s, {content: 'second', thread_name: 'second'}).expect(500).execute();
- send.mockRestore();
- dispatch.mockRestore();
- const events = dispatched.map((entry) => entry.event);
- expect(events).toEqual(['THREAD_CREATE', 'CHANNEL_UPDATE', 'THREAD_DELETE']);
- expect(dispatched[1]!.data).toMatchObject({id: s.forum.id, last_message_id: first.channel_id});
- const forum = await threadsRequest<ChannelResponse>(harness, s.owner.token)
- .get(`/channels/${s.forum.id}`)
- .execute();
- expect(forum.last_message_id).toBe(first.channel_id);
- });
-
it('enforces the forum target rules', async () => {
const s = await setup();
const [, staff] = s.forum.available_tags!;
diff --git a/fluxer_api/src/api/worker/AccountActionConsumer.ts b/fluxer_api/src/api/worker/AccountActionConsumer.ts
index a5880a620..22a288c88 100644
--- a/fluxer_api/src/api/worker/AccountActionConsumer.ts
+++ b/fluxer_api/src/api/worker/AccountActionConsumer.ts
@@ -96,7 +96,7 @@ async function publishOutcome(deps: AccountActionDeps, key: string, outcome: Act
await emitActivity('action_outcome', key, outcome, workerMeta(), outcome.action_id);
}
-export async function handleActionMessage(deps: AccountActionDeps, msg: JsMsg): Promise<void> {
+async function handleActionMessage(deps: AccountActionDeps, msg: JsMsg): Promise<void> {
const env = decodeActionEnvelope(msg.data);
if (!env) {
msg.term('undecodable action envelope');
diff --git a/fluxer_api/src/api/worker/WorkerHeartbeat.ts b/fluxer_api/src/api/worker/WorkerHeartbeat.ts
index 804cf8747..ad467be27 100644
--- a/fluxer_api/src/api/worker/WorkerHeartbeat.ts
+++ b/fluxer_api/src/api/worker/WorkerHeartbeat.ts
@@ -4,7 +4,7 @@ import {writeFileSync} from 'node:fs';
import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
const WORKER_HEARTBEAT_PATH = '/tmp/fluxer-worker-heartbeat';
-export const WORKER_HEARTBEAT_WRITE_INTERVAL_MS = 5000;
+const WORKER_HEARTBEAT_WRITE_INTERVAL_MS = 5000;
export const WORKER_LANE_HEARTBEAT_INTERVAL_MS = 5000;
export const WORKER_LANE_STALE_AFTER_MS = 30000;
export const WORKER_CRON_STALE_AFTER_MS = 90000;
diff --git a/fluxer_api/src/api/worker/tests/AccountActionConsumer.test.ts b/fluxer_api/src/api/worker/tests/AccountActionConsumer.test.ts
deleted file mode 100644
index acc49ae5c..000000000
--- a/fluxer_api/src/api/worker/tests/AccountActionConsumer.test.ts
+++ /dev/null
@@ -1,734 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {
- type ChannelID,
- createChannelID,
- createMessageID,
- createUserID,
- type MessageID,
- type UserID,
-} from '@app/api/BrandedTypes';
-import {SYSTEM_USER_ID} from '@app/api/constants/Core';
-import type {UserRow} from '@app/api/database/types/UserTypes';
-import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
-import type {ActionEnvelope, ActionOutcome} from '@app/api/infrastructure/activity/Contract.generated';
-import {User} from '@app/api/models/User';
-import {NEW_CONVERSATION_LIMIT_MAX_MS} from '@app/api/user/NewConversationLimit';
-import type {AccountStateDeps} from '@app/api/user/services/AccountStateApplier';
-import {type AccountActionDeps, applyAction, handleActionMessage} from '@app/api/worker/AccountActionConsumer';
-import {UserFlags} from '@fluxer/constants/src/UserConstants';
-import type {AdminArchiveResponse} from '@fluxer/schema/src/domains/admin/AdminArchiveSchemas';
-import {createSnowflakeFromTimestamp} from '@fluxer/snowflake/src/Snowflake';
-import type {JsMsg} from '@nats-io/jetstream';
-import {beforeEach, describe, expect, it} from 'vitest';
-
-const USER_ID = '1174109840998400001';
-const NOW = 1_759_000_000_000;
-const DAY_MS = 86_400_000;
-const DELETION_DELAY_MS = 7 * DAY_MS;
-
-function archiveAt(
- requestedAtMs: number,
- userId: UserID,
- requestedBy: UserID,
- archiveId: string,
- failed = false,
-): AdminArchiveResponse {
- return {
- archive_id: archiveId,
- subject_type: 'user',
- subject_id: userId.toString(),
- requested_by: requestedBy.toString(),
- requested_at: new Date(requestedAtMs).toISOString(),
- started_at: null,
- completed_at: null,
- failed_at: failed ? new Date(requestedAtMs + 1_000).toISOString() : null,
- file_size: null,
- progress_percent: 0,
- progress_step: 'Queued',
- error_message: null,
- download_url_expires_at: null,
- expires_at: null,
- };
-}
-
-function limitEnvelope(overrides: Partial<Extract<ActionEnvelope, {type: 'set_account_limit'}>> = {}) {
- return envelope<'set_account_limit'>({
- type: 'set_account_limit',
- user_id: USER_ID,
- on: true,
- ...overrides,
- });
-}
-
-function envelope<T extends ActionEnvelope['type']>(
- body: Omit<Extract<ActionEnvelope, {type: T}>, 'v' | 'id' | 'key' | 'issued_at_ms' | 'expires_at_ms'> &
- Partial<ActionEnvelope>,
-): Extract<ActionEnvelope, {type: T}> {
- return {
- v: 1,
- id: 'a:07:4242:0',
- key: USER_ID,
- issued_at_ms: NOW,
- expires_at_ms: NOW + 60_000,
- ...body,
- } as Extract<ActionEnvelope, {type: T}>;
-}
-
-class FakeUsers {
- readonly rows = new Map<string, UserRow>();
- casFailures = 0;
-
- put(overrides: Partial<UserRow> = {}): void {
- const row: UserRow = {...EMPTY_USER_ROW, user_id: createUserID(BigInt(USER_ID)), flags: 0n, ...overrides};
- this.rows.set(row.user_id.toString(), row);
- }
-
- current(): User {
- return new User(this.rows.get(USER_ID)!);
- }
-
- async findUnique(userId: UserID): Promise<User | null> {
- const row = this.rows.get(userId.toString());
- return row ? new User(row) : null;
- }
-
- async compareAndSetFlags(user: User, flags: bigint): Promise<User | null> {
- const row = this.rows.get(user.id.toString())!;
- if (this.casFailures > 0) {
- this.casFailures--;
- return null;
- }
- if ((row.flags ?? 0n) !== user.flags) return null;
- const next = {...row, flags};
- this.rows.set(user.id.toString(), next);
- return new User(next);
- }
-
- async patchUpsert(userId: UserID, patch: Partial<UserRow>): Promise<User> {
- const next = {...this.rows.get(userId.toString())!, ...patch};
- this.rows.set(userId.toString(), next);
- return new User(next);
- }
-}
-
-interface Harness {
- users: FakeUsers;
- cached: Map<string, unknown>;
- presence: Array<unknown>;
- profiles: Array<unknown>;
- bans: Array<{ip: string; ttl: number}>;
- refreshes: number;
- authored: Array<{channelId: ChannelID; messageId: MessageID}>;
- visibility: Array<UserID>;
- removed: Array<{channelId: ChannelID; authorId: UserID; messageIds: Array<MessageID>}>;
- archives: Array<AdminArchiveResponse>;
- archiveRequests: Array<{userId: UserID; requestedBy: UserID; includeAttachments: boolean}>;
- queued: Map<string, number>;
- deps: AccountActionDeps;
-}
-
-function harness(): Harness {
- const users = new FakeUsers();
- const h: Harness = {
- users,
- cached: new Map(),
- presence: [],
- profiles: [],
- bans: [],
- refreshes: 0,
- authored: [],
- visibility: [],
- removed: [],
- archives: [],
- archiveRequests: [],
- queued: new Map(),
- deps: null as never,
- };
- const authored = {
- listMessagesByAuthor: async (_authorId: UserID, limit: number, before?: MessageID) =>
- [...h.authored]
- .sort((a, b) => (a.messageId > b.messageId ? -1 : 1))
- .filter((m) => before === undefined || m.messageId < before)
- .slice(0, limit),
- };
- const state: AccountStateDeps = {
- users: users as unknown as AccountStateDeps['users'],
- dispatch: {
- userUpdated: async (user) => {
- h.presence.push(user.id);
- },
- profileChanged: async (user) => {
- h.profiles.push(user.id);
- },
- contentVisibilityChanged: async (user) => {
- h.visibility.push(user.id);
- },
- messagesRemoved: async (channelId, authorId, messageIds) => {
- h.removed.push({channelId, authorId, messageIds});
- },
- },
- ipBans: {
- isIpBanned: async () => false,
- banIpTemp: async (ip: string, ttl: number) => {
- h.bans.push({ip, ttl});
- },
- },
- cache: {
- publish: async () => {
- h.refreshes++;
- },
- get: async (key: string) => h.cached.get(key) ?? null,
- set: async (key: string, value: unknown) => {
- h.cached.set(key, value);
- },
- delete: async (key: string) => {
- h.cached.delete(key);
- },
- } as unknown as AccountStateDeps['cache'],
- archives: {
- listArchives: async ({subjectId}) =>
- h.archives.filter((archive) => archive.subject_id === subjectId?.toString()).reverse(),
- triggerUserArchive: async (userId, requestedBy, includeAttachments) => {
- h.archiveRequests.push({userId, requestedBy, includeAttachments});
- const archive = archiveAt(NOW, userId, requestedBy, String(9000 + h.archives.length));
- h.archives.push(archive);
- return archive;
- },
- },
- messageDeletionQueue: {
- scheduleDeletion: async (userId, scheduledAt) => {
- h.queued.set(userId.toString(), scheduledAt.getTime());
- },
- removeFromQueue: async (userId) => {
- h.queued.delete(userId.toString());
- },
- },
- messageDeletionDelayMs: DELETION_DELAY_MS,
- authored: authored as unknown as AccountStateDeps['authored'],
- now: () => NOW,
- };
- h.deps = {
- js: {} as AccountActionDeps['js'],
- state,
- guildInvites: {} as AccountActionDeps['guildInvites'],
- now: () => NOW,
- };
- return h;
-}
-
-describe('account action apply', () => {
- let h: Harness;
- beforeEach(() => {
- h = harness();
- h.users.put();
- });
-
- it('limits the account and reports what it observed', async () => {
- const outcome = await applyAction(h.deps, limitEnvelope());
- expect(outcome).toEqual({
- action_id: 'a:07:4242:0',
- action_type: 'set_account_limit',
- status: 'applied',
- detail: null,
- observed: {flags: UserFlags.ACCOUNT_LIMITED.toString(), deleted: false},
- user_id: USER_ID,
- });
- expect(h.users.current().flags).toBe(UserFlags.ACCOUNT_LIMITED);
- expect(h.presence).toHaveLength(1);
- });
-
- it('is a noop when the limitation already holds, so a redelivery changes nothing', async () => {
- await applyAction(h.deps, limitEnvelope());
- const second = await applyAction(h.deps, limitEnvelope());
- expect(second.status).toBe('noop');
- expect(h.presence).toHaveLength(1);
- });
-
- it('lifts the limitation and keeps the other flags', async () => {
- h.users.put({flags: UserFlags.HAS_SESSION_STARTED | UserFlags.ACCOUNT_LIMITED});
- const lift = limitEnvelope({on: false});
- expect((await applyAction(h.deps, lift)).status).toBe('applied');
- expect(h.users.current().flags).toBe(UserFlags.HAS_SESSION_STARTED);
- expect((await applyAction(h.deps, lift)).status).toBe('noop');
- expect(h.presence).toHaveLength(1);
- });
-
- it('never limits staff, exempt or system accounts', async () => {
- for (const overrides of [{flags: UserFlags.STAFF}, {flags: UserFlags.LIMIT_EXEMPT}, {system: true}] satisfies Array<
- Partial<UserRow>
- >) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, limitEnvelope())).status).toBe('exempt');
- expect(h.users.current().flags & UserFlags.ACCOUNT_LIMITED).toBe(0n);
- }
- expect(h.presence).toHaveLength(0);
- });
-
- it('rereads and retries when the compare and set loses a race', async () => {
- h.users.casFailures = 2;
- const outcome = await applyAction(h.deps, limitEnvelope());
- expect(outcome.status).toBe('applied');
- });
-
- it('gives up after repeated compare and set losses', async () => {
- h.users.casFailures = 3;
- await expect(applyAction(h.deps, limitEnvelope())).rejects.toThrow();
- expect(h.users.current().flags).toBe(0n);
- });
-
- it('treats missing, deleted and bot accounts as ineligible', async () => {
- h.users.rows.clear();
- const missing = await applyAction(h.deps, limitEnvelope());
- expect(missing).toMatchObject({status: 'ineligible', observed: null});
- h.users.put({bot: true});
- const bot = await applyAction(h.deps, limitEnvelope());
- expect(bot.status).toBe('ineligible');
- h.users.put({flags: UserFlags.DELETED});
- const deleted = await applyAction(h.deps, limitEnvelope());
- expect(deleted).toMatchObject({status: 'ineligible', observed: {deleted: true}});
- });
-
- it('limits new conversations until the requested time and lifts the limit once', async () => {
- const on = envelope<'limit_new_conversations'>({
- type: 'limit_new_conversations',
- user_id: USER_ID,
- on: true,
- until_ms: NOW + 86_400_000,
- });
- expect(await applyAction(h.deps, on)).toMatchObject({status: 'applied', user_id: USER_ID});
- expect([...h.cached.values()]).toEqual([{until_ms: NOW + 86_400_000, applied_at_ms: NOW}]);
- expect((await applyAction(h.deps, on)).status).toBe('noop');
- const off = envelope<'limit_new_conversations'>({
- type: 'limit_new_conversations',
- user_id: USER_ID,
- on: false,
- until_ms: NOW,
- });
- expect((await applyAction(h.deps, off)).status).toBe('applied');
- expect(h.cached.size).toBe(0);
- expect((await applyAction(h.deps, off)).status).toBe('noop');
- });
-
- it('caps a limit at the maximum duration and skips one that already ended', async () => {
- const far = envelope<'limit_new_conversations'>({
- type: 'limit_new_conversations',
- user_id: USER_ID,
- on: true,
- until_ms: NOW + 2 * NEW_CONVERSATION_LIMIT_MAX_MS,
- });
- expect((await applyAction(h.deps, far)).status).toBe('applied');
- expect([...h.cached.values()]).toMatchObject([{until_ms: NOW + NEW_CONVERSATION_LIMIT_MAX_MS}]);
- h.cached.clear();
- const past = envelope<'limit_new_conversations'>({
- type: 'limit_new_conversations',
- user_id: USER_ID,
- on: true,
- until_ms: NOW,
- });
- expect((await applyAction(h.deps, past)).status).toBe('noop');
- expect(h.cached.size).toBe(0);
- });
-
- it('never limits staff, trusted, bot or deleted accounts', async () => {
- const on = envelope<'limit_new_conversations'>({
- type: 'limit_new_conversations',
- user_id: USER_ID,
- on: true,
- until_ms: NOW + 86_400_000,
- });
- for (const overrides of [{flags: UserFlags.STAFF}, {flags: UserFlags.LIMIT_EXEMPT}] satisfies Array<
- Partial<UserRow>
- >) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, on)).status).toBe('exempt');
- }
- for (const overrides of [{bot: true}, {flags: UserFlags.DELETED}] satisfies Array<Partial<UserRow>>) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, on)).status).toBe('ineligible');
- }
- expect(h.cached.size).toBe(0);
- });
-
- it('ignores unknown envelope fields', async () => {
- h.users.put({flags: UserFlags.HAS_SESSION_STARTED});
- const action = {...limitEnvelope(), unknown_field: true};
- expect((await applyAction(h.deps, action)).status).toBe('applied');
- expect(h.users.current().flags).toBe(UserFlags.HAS_SESSION_STARTED | UserFlags.ACCOUNT_LIMITED);
- });
-
- it('bans a public address until the requested time and refreshes the ban caches', async () => {
- const outcome = await applyAction(
- h.deps,
- envelope<'temp_ban_ip'>({type: 'temp_ban_ip', ip: '93.184.216.34', until_ms: NOW + 3_600_000}),
- );
- expect(outcome.status).toBe('applied');
- expect(h.bans).toEqual([{ip: '93.184.216.34', ttl: 3600}]);
- expect(h.refreshes).toBe(1);
- });
-
- it('bans an IPv6 client by its /64 same-IP key or by its address', async () => {
- const byKey = await applyAction(
- h.deps,
- envelope<'temp_ban_ip'>({type: 'temp_ban_ip', ip: '2001:4860:1:2::/64', until_ms: NOW + 3_600_000}),
- );
- expect(byKey.status).toBe('applied');
- const loose = await applyAction(
- h.deps,
- envelope<'temp_ban_ip'>({type: 'temp_ban_ip', ip: '2001:4860:1:2::/48', until_ms: NOW + 3_600_000}),
- );
- expect(loose.status).toBe('exempt');
- expect(h.bans).toEqual([{ip: '2001:4860:1:2::/64', ttl: 3600}]);
- });
-
- it('never bans a private address and skips bans about to end', async () => {
- const privateIp = await applyAction(
- h.deps,
- envelope<'temp_ban_ip'>({type: 'temp_ban_ip', ip: '10.0.0.1', until_ms: NOW + 3_600_000}),
- );
- expect(privateIp.status).toBe('exempt');
- const ending = await applyAction(
- h.deps,
- envelope<'temp_ban_ip'>({type: 'temp_ban_ip', ip: '93.184.216.34', until_ms: NOW + 30_000}),
- );
- expect(ending.status).toBe('noop');
- expect(h.bans).toEqual([]);
- });
-
- it('hides the profile reversibly and tells clients both ways', async () => {
- h.users.put({flags: UserFlags.ACCOUNT_LIMITED});
- const hide = envelope<'hide_profile'>({type: 'hide_profile', user_id: USER_ID, on: true});
- expect(await applyAction(h.deps, hide)).toMatchObject({status: 'applied', action_type: 'hide_profile'});
- expect(h.users.current().flags).toBe(UserFlags.ACCOUNT_LIMITED | UserFlags.PROFILE_HIDDEN);
- expect((await applyAction(h.deps, hide)).status).toBe('noop');
- const show = envelope<'hide_profile'>({type: 'hide_profile', user_id: USER_ID, on: false});
- expect((await applyAction(h.deps, show)).status).toBe('applied');
- expect(h.users.current().flags).toBe(UserFlags.ACCOUNT_LIMITED);
- expect((await applyAction(h.deps, show)).status).toBe('noop');
- expect(h.presence).toHaveLength(2);
- expect(h.profiles).toHaveLength(2);
- });
-
- it('never hides staff or trusted profiles and skips bots and deleted accounts', async () => {
- const hide = envelope<'hide_profile'>({type: 'hide_profile', user_id: USER_ID, on: true});
- for (const flags of [UserFlags.STAFF, UserFlags.LIMIT_EXEMPT]) {
- h.users.put({flags});
- expect((await applyAction(h.deps, hide)).status).toBe('exempt');
- }
- for (const overrides of [{bot: true}, {flags: UserFlags.DELETED}] satisfies Array<Partial<UserRow>>) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, hide)).status).toBe('ineligible');
- }
- h.users.put({flags: UserFlags.STAFF | UserFlags.PROFILE_HIDDEN});
- const show = envelope<'hide_profile'>({type: 'hide_profile', user_id: USER_ID, on: false});
- expect((await applyAction(h.deps, show)).status).toBe('applied');
- expect(h.profiles).toHaveLength(1);
- });
-
- function hideEnvelope(on: boolean, sinceMs = NOW - 86_400_000) {
- return envelope<'hide_recent_messages'>({type: 'hide_recent_messages', user_id: USER_ID, since_ms: sinceMs, on});
- }
-
- function authorAt(timestampMs: number, channel: number): MessageID {
- const messageId = createMessageID(createSnowflakeFromTimestamp(timestampMs) + BigInt(h.authored.length));
- h.authored.push({channelId: createChannelID(BigInt(channel)), messageId});
- return messageId;
- }
-
- function removedIds(): Array<MessageID> {
- return h.removed.flatMap((entry) => entry.messageIds).sort((a, b) => (a < b ? -1 : 1));
- }
-
- it('hides every message from the window onward and tells each channel they are gone', async () => {
- const since = NOW - 86_400_000;
- const before = [authorAt(since - 60_000, 100), authorAt(since - 1, 101)];
- const inside: Array<MessageID> = [authorAt(since, 100)];
- for (let i = 0; i < 250; i++) inside.push(authorAt(since + 1_000 + i, 100 + (i % 3)));
- const outcome = await applyAction(h.deps, hideEnvelope(true, since));
- expect(outcome).toEqual({
- action_id: 'a:07:4242:0',
- action_type: 'hide_recent_messages',
- status: 'applied',
- detail: 'messages=251',
- observed: {flags: '0', deleted: false},
- user_id: USER_ID,
- });
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(since);
- expect(h.visibility).toEqual([createUserID(BigInt(USER_ID))]);
- expect(removedIds()).toEqual([...inside].sort((a, b) => (a < b ? -1 : 1)));
- for (const id of before) expect(removedIds()).not.toContain(id);
- for (const entry of h.removed) {
- expect(entry.authorId).toBe(createUserID(BigInt(USER_ID)));
- for (const id of entry.messageIds) {
- expect(h.authored.find((m) => m.messageId === id)?.channelId).toBe(entry.channelId);
- }
- }
- expect(h.users.current().flags).toBe(0n);
- expect(h.queued.size).toBe(0);
- });
-
- it('keeps the wider window when asked again and resends the deletes as a noop', async () => {
- const since = NOW - 86_400_000;
- authorAt(since + 5_000, 100);
- await applyAction(h.deps, hideEnvelope(true, since));
- const later = await applyAction(h.deps, hideEnvelope(true, since + 60_000));
- expect(later).toMatchObject({status: 'noop', detail: 'messages=1'});
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(since);
- expect(h.visibility).toHaveLength(1);
- const wider = await applyAction(h.deps, hideEnvelope(true, since - 60_000));
- expect(wider.status).toBe('applied');
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(since - 60_000);
- expect(h.visibility).toHaveLength(2);
- });
-
- it('reports a hide with nothing in the window as applied with no deletes', async () => {
- authorAt(NOW - 2 * 86_400_000, 100);
- const outcome = await applyAction(h.deps, hideEnvelope(true));
- expect(outcome).toMatchObject({status: 'applied', detail: 'messages=0'});
- expect(h.removed).toEqual([]);
- });
-
- it('restores by clearing the window and sends no gateway events', async () => {
- const since = NOW - 86_400_000;
- authorAt(since + 5_000, 100);
- h.users.put({content_hidden_since: new Date(since)});
- const outcome = await applyAction(h.deps, hideEnvelope(false));
- expect(outcome).toMatchObject({status: 'applied', detail: null, observed: {flags: '0', deleted: false}});
- expect(h.users.current().contentHiddenSince).toBeNull();
- expect(h.removed).toEqual([]);
- expect(h.presence).toHaveLength(0);
- expect(h.visibility).toHaveLength(1);
- expect((await applyAction(h.deps, hideEnvelope(false))).status).toBe('noop');
- expect(h.visibility).toHaveLength(1);
- });
-
- it('never hides staff, trusted or system messages and skips bots and deleted accounts', async () => {
- authorAt(NOW - 1_000, 100);
- for (const overrides of [{flags: UserFlags.STAFF}, {flags: UserFlags.LIMIT_EXEMPT}, {system: true}] satisfies Array<
- Partial<UserRow>
- >) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, hideEnvelope(true))).status).toBe('exempt');
- expect(h.users.current().contentHiddenSince).toBeNull();
- }
- for (const overrides of [{bot: true}, {flags: UserFlags.DELETED}] satisfies Array<Partial<UserRow>>) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, hideEnvelope(true))).status).toBe('ineligible');
- }
- h.users.rows.clear();
- expect(await applyAction(h.deps, hideEnvelope(true))).toMatchObject({status: 'ineligible', observed: null});
- expect(h.removed).toEqual([]);
- expect(h.visibility).toEqual([]);
- h.users.put({flags: UserFlags.STAFF, content_hidden_since: new Date(NOW - 1_000)});
- expect((await applyAction(h.deps, hideEnvelope(false))).status).toBe('applied');
- expect(h.users.current().contentHiddenSince).toBeNull();
- });
-
- it('keeps the message hide and the profile mask independent', async () => {
- const since = NOW - 86_400_000;
- authorAt(since + 5_000, 100);
- await applyAction(h.deps, hideEnvelope(true, since));
- await applyAction(h.deps, envelope<'hide_profile'>({type: 'hide_profile', user_id: USER_ID, on: true}));
- expect(h.users.current().flags).toBe(UserFlags.PROFILE_HIDDEN);
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(since);
- await applyAction(h.deps, hideEnvelope(false));
- expect(h.users.current().flags).toBe(UserFlags.PROFILE_HIDDEN);
- expect(h.users.current().contentHiddenSince).toBeNull();
- await applyAction(h.deps, hideEnvelope(true, since));
- await applyAction(h.deps, envelope<'hide_profile'>({type: 'hide_profile', user_id: USER_ID, on: false}));
- expect(h.users.current().flags).toBe(0n);
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(since);
- });
-
- it('hides every message the account ever sent when the window starts at zero', async () => {
- const all = [authorAt(1_420_070_401_000, 100), authorAt(NOW - 400 * DAY_MS, 101), authorAt(NOW - 1_000, 102)];
- const outcome = await applyAction(h.deps, hideEnvelope(true, 0));
- expect(outcome).toMatchObject({status: 'applied', detail: 'messages=3'});
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(0);
- expect(removedIds()).toEqual([...all].sort((a, b) => (a < b ? -1 : 1)));
- expect((await applyAction(h.deps, hideEnvelope(true, NOW - DAY_MS))).status).toBe('noop');
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(0);
- expect((await applyAction(h.deps, hideEnvelope(false, 0))).status).toBe('applied');
- expect(h.users.current().contentHiddenSince).toBeNull();
- });
-
- it('hides the messages of an account whose deletion is only scheduled', async () => {
- authorAt(NOW - 1_000, 100);
- h.users.put({flags: UserFlags.DELETED | UserFlags.SPAMMER, pending_deletion_at: new Date(NOW + 60 * DAY_MS)});
- expect((await applyAction(h.deps, hideEnvelope(true, 0))).status).toBe('applied');
- expect(h.users.current().contentHiddenSince?.getTime()).toBe(0);
- });
-
- function purgeEnvelope(on = true) {
- return envelope<'delete_user_messages'>({type: 'delete_user_messages', user_id: USER_ID, on});
- }
-
- const userId = createUserID(BigInt(USER_ID));
-
- it('archives with attachments and schedules the deletion instead of deleting now', async () => {
- authorAt(NOW - 1_000, 100);
- const outcome = await applyAction(h.deps, purgeEnvelope());
- const scheduledAt = NOW + DELETION_DELAY_MS;
- expect(outcome).toEqual({
- action_id: 'a:07:4242:0',
- action_type: 'delete_user_messages',
- status: 'applied',
- detail: `archive=9000 reused=false scheduled_at=${new Date(scheduledAt).toISOString()}`,
- observed: {flags: '0', deleted: false},
- user_id: USER_ID,
- });
- expect(h.archiveRequests).toEqual([{userId, requestedBy: SYSTEM_USER_ID, includeAttachments: true}]);
- expect(h.users.current().pendingBulkMessageDeletionAt?.getTime()).toBe(scheduledAt);
- expect(h.queued.get(USER_ID)).toBe(scheduledAt);
- expect(h.removed).toEqual([]);
- expect(h.authored).toHaveLength(1);
- expect(h.presence).toEqual([userId]);
- });
-
- it('reuses an archive from the last day and makes a new one when it is older or failed', async () => {
- h.archives.push(archiveAt(NOW - DAY_MS + 60_000, userId, createUserID(42n), '777'));
- expect((await applyAction(h.deps, purgeEnvelope())).detail).toMatch(/^archive=777 reused=true /);
- expect(h.archiveRequests).toEqual([]);
- h.archives.length = 0;
- h.archives.push(archiveAt(NOW - DAY_MS - 60_000, userId, createUserID(42n), '778'));
- h.archives.push(archiveAt(NOW - 60_000, userId, createUserID(42n), '779', true));
- h.users.put();
- expect((await applyAction(h.deps, purgeEnvelope())).detail).toMatch(/^archive=9002 reused=false /);
- expect(h.archiveRequests).toHaveLength(1);
- });
-
- it('keeps an earlier schedule and pulls a later one forward', async () => {
- const earlier = NOW + DAY_MS;
- h.users.put({pending_bulk_message_deletion_at: new Date(earlier), pending_bulk_message_deletion_message_count: 4});
- const kept = await applyAction(h.deps, purgeEnvelope());
- expect(kept).toMatchObject({status: 'noop'});
- expect(kept.detail).toContain(`scheduled_at=${new Date(earlier).toISOString()}`);
- expect(h.users.current().pendingBulkMessageDeletionAt?.getTime()).toBe(earlier);
- expect(h.users.current().pendingBulkMessageDeletionMessageCount).toBe(4);
- expect(h.queued.get(USER_ID)).toBe(earlier);
- expect(h.presence).toHaveLength(0);
- h.users.put({pending_bulk_message_deletion_at: new Date(NOW + 30 * DAY_MS)});
- expect((await applyAction(h.deps, purgeEnvelope())).status).toBe('applied');
- expect(h.users.current().pendingBulkMessageDeletionAt?.getTime()).toBe(NOW + DELETION_DELAY_MS);
- expect(h.queued.get(USER_ID)).toBe(NOW + DELETION_DELAY_MS);
- expect(h.archiveRequests).toHaveLength(1);
- });
-
- it('schedules for accounts already scheduled for deletion and paid accounts', async () => {
- for (const overrides of [
- {flags: UserFlags.DELETED | UserFlags.SPAMMER, pending_deletion_at: new Date(NOW + 60 * DAY_MS)},
- {has_ever_purchased: true, premium_type: 2},
- ] satisfies Array<Partial<UserRow>>) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, purgeEnvelope())).status).toBe('applied');
- expect(h.users.current().pendingBulkMessageDeletionAt?.getTime()).toBe(NOW + DELETION_DELAY_MS);
- }
- });
-
- it('cancels the schedule on off and is a noop when nothing is scheduled', async () => {
- await applyAction(h.deps, purgeEnvelope());
- const cancelled = await applyAction(h.deps, purgeEnvelope(false));
- expect(cancelled).toMatchObject({status: 'applied', detail: null, observed: {flags: '0', deleted: false}});
- expect(h.users.current().pendingBulkMessageDeletionAt).toBeNull();
- expect(h.queued.has(USER_ID)).toBe(false);
- expect(h.presence).toHaveLength(2);
- expect((await applyAction(h.deps, purgeEnvelope(false))).status).toBe('noop');
- expect(h.archives).toHaveLength(1);
- h.users.put({flags: UserFlags.STAFF, pending_bulk_message_deletion_at: new Date(NOW + DAY_MS)});
- expect((await applyAction(h.deps, purgeEnvelope(false))).status).toBe('applied');
- h.users.rows.clear();
- expect(await applyAction(h.deps, purgeEnvelope(false))).toMatchObject({status: 'ineligible', observed: null});
- });
-
- it('never schedules for staff, trusted, system, bot, deleted or missing accounts', async () => {
- for (const overrides of [{flags: UserFlags.STAFF}, {flags: UserFlags.LIMIT_EXEMPT}, {system: true}] satisfies Array<
- Partial<UserRow>
- >) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, purgeEnvelope())).status).toBe('exempt');
- }
- for (const overrides of [{bot: true}, {flags: UserFlags.DELETED}] satisfies Array<Partial<UserRow>>) {
- h.users.put(overrides);
- expect((await applyAction(h.deps, purgeEnvelope())).status).toBe('ineligible');
- }
- h.users.rows.clear();
- expect(await applyAction(h.deps, purgeEnvelope())).toMatchObject({status: 'ineligible', observed: null});
- expect(h.archiveRequests).toEqual([]);
- expect(h.queued.size).toBe(0);
- });
-
- it('answers expired actions and unknown shapes without touching the account', async () => {
- const expired = await applyAction(h.deps, limitEnvelope({expires_at_ms: NOW}));
- expect(expired.status).toBe('expired');
- const future = await applyAction(h.deps, {...limitEnvelope(), v: 2});
- expect(future.status).toBe('unsupported');
- const unknown = await applyAction(h.deps, {...limitEnvelope(), type: 'future_type'} as unknown as ActionEnvelope);
- expect(unknown).toMatchObject({status: 'unsupported', action_type: 'future_type'});
- expect(h.users.current().flags).toBe(0n);
- });
-});
-
-interface FakeMsgState {
- acked: number;
- naks: Array<number | undefined>;
- terms: number;
-}
-
-function fakeMsg(data: string, deliveryCount: number): {msg: JsMsg; state: FakeMsgState} {
- const state: FakeMsgState = {acked: 0, naks: [], terms: 0};
- const msg = {
- data: new TextEncoder().encode(data),
- info: {deliveryCount},
- ackAck: async () => {
- state.acked++;
- return true;
- },
- nak: (delay?: number) => {
- state.naks.push(delay);
- },
- term: () => {
- state.terms++;
- },
- } as unknown as JsMsg;
- return {msg, state};
-}
-
-describe('account action messages', () => {
- it('publishes the outcome before acknowledging, and terminates undecodable envelopes', async () => {
- const h = harness();
- h.users.put();
- const outcomes: Array<ActionOutcome> = [];
- h.deps.publishOutcome = async (_key, outcome) => {
- outcomes.push(outcome);
- };
- const good = fakeMsg(JSON.stringify(limitEnvelope()), 1);
- await handleActionMessage(h.deps, good.msg);
- expect(outcomes.map((outcome) => outcome.status)).toEqual(['applied']);
- expect(good.state.acked).toBe(1);
- const bad = fakeMsg('{not json', 1);
- await handleActionMessage(h.deps, bad.msg);
- expect(bad.state.terms).toBe(1);
- expect(outcomes).toHaveLength(1);
- });
-
- it('retries a failing apply with backoff and reports failed after the last attempt', async () => {
- const h = harness();
- h.users.put();
- h.users.findUnique = async () => {
- throw new Error('datastore unavailable');
- };
- const outcomes: Array<ActionOutcome> = [];
- h.deps.publishOutcome = async (_key, outcome) => {
- outcomes.push(outcome);
- };
- const data = JSON.stringify(limitEnvelope());
- const early = fakeMsg(data, 3);
- await handleActionMessage(h.deps, early.msg);
- expect(early.state.naks).toEqual([3000]);
- expect(outcomes).toEqual([]);
- const last = fakeMsg(data, 10);
- await handleActionMessage(h.deps, last.msg);
- expect(outcomes).toMatchObject([{status: 'failed', detail: 'Error: datastore unavailable'}]);
- expect(last.state.acked).toBe(1);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts b/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts
index 8f1b694cc..dcf5c9d86 100644
--- a/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts
+++ b/fluxer_api/src/api/worker/tests/BulkScheduleUserDeletion.test.ts
@@ -47,7 +47,7 @@ import {emailLinkUrls, renderEmailTemplateText, reportResolvedSlots} from '@pkgs
import {getEmailTemplate} from '@pkgs/email/src/email_i18n/EmailI18n';
import type {WorkerTaskResult} from '@pkgs/worker/src/contracts/WorkerTask';
import type {WorkerJobPayload} from '@pkgs/worker/src/contracts/WorkerTypes';
-import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
+import {afterEach, beforeEach, describe, expect, test} from 'vitest';
interface ReportResponse {
report_id: string;
diff --git a/fluxer_api/src/api/worker/tests/CronScheduler.test.ts b/fluxer_api/src/api/worker/tests/CronScheduler.test.ts
deleted file mode 100644
index 703fbd50d..000000000
--- a/fluxer_api/src/api/worker/tests/CronScheduler.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {CronScheduler} from '@app/api/worker/CronScheduler';
-import type {WorkerService} from '@app/api/worker/WorkerService';
-import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
-import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
-import {afterEach, describe, expect, it, vi} from 'vitest';
-
-function createLogger(): LoggerInterface {
- const logger = {
- trace: vi.fn(),
- debug: vi.fn(),
- info: vi.fn(),
- warn: vi.fn(),
- error: vi.fn(),
- child: () => logger,
- };
- return logger as unknown as LoggerInterface;
-}
-
-function createScheduler(): {
- scheduler: CronScheduler;
- addJob: ReturnType<typeof vi.fn>;
- setnx: ReturnType<typeof vi.fn>;
-} {
- const addJob = vi.fn().mockResolvedValue(1n);
- const setnx = vi.fn().mockResolvedValue(true);
- const workerService = {addJob} as unknown as WorkerService;
- const kvClient = {setnx} as unknown as IKVProvider;
- return {scheduler: new CronScheduler(workerService, createLogger(), kvClient), addJob, setnx};
-}
-
-describe('CronScheduler', () => {
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('fires a schedule whose second was skipped by a stalled tick', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
- const {scheduler, addJob, setnx} = createScheduler();
- scheduler.upsert('expireAttachments', 'expireAttachments', {}, '5 * * * * *', {ledger: false});
-
- scheduler.start();
- await vi.advanceTimersByTimeAsync(3000);
- expect(addJob).not.toHaveBeenCalled();
-
- vi.setSystemTime(new Date('2026-01-01T00:00:10.400Z'));
- await vi.advanceTimersByTimeAsync(2000);
- scheduler.stop();
-
- const skippedSecond = Math.floor(Date.parse('2026-01-01T00:00:05.000Z') / 1000);
- expect(addJob).toHaveBeenCalledTimes(1);
- expect(addJob).toHaveBeenCalledWith(
- 'expireAttachments',
- {},
- {
- jobKey: `cron:expireAttachments:${skippedSecond}`,
- skipLedger: true,
- },
- );
- expect(setnx).toHaveBeenCalledTimes(1);
- });
-
- it('fires a skipped schedule once instead of once per skipped second', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
- const {scheduler, addJob} = createScheduler();
- scheduler.upsert('flushUserActivityBuffer', 'flushUserActivityBuffer', {}, '*/2 * * * * *', {ledger: false});
-
- scheduler.start();
- await vi.advanceTimersByTimeAsync(1000);
- addJob.mockClear();
-
- vi.setSystemTime(new Date('2026-01-01T00:00:20.400Z'));
- await vi.advanceTimersByTimeAsync(1000);
- scheduler.stop();
-
- expect(addJob).toHaveBeenCalledTimes(1);
- });
-
- it('does not replay schedules from before the scheduler started', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-01T00:00:30.000Z'));
- const {scheduler, addJob} = createScheduler();
- scheduler.upsert('expireAttachments', 'expireAttachments', {}, '5 * * * * *', {ledger: false});
-
- scheduler.start();
- await vi.advanceTimersByTimeAsync(2000);
- scheduler.stop();
-
- expect(addJob).not.toHaveBeenCalled();
- });
-
- it('skips the lease and the enqueue while the enabled predicate is false', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
- const {scheduler, addJob, setnx} = createScheduler();
- let enabled = false;
- scheduler.upsert('expireAttachments', 'expireAttachments', {}, '* * * * * *', {
- ledger: false,
- enabled: () => enabled,
- });
-
- scheduler.start();
- await vi.advanceTimersByTimeAsync(3000);
- expect(setnx).not.toHaveBeenCalled();
- expect(addJob).not.toHaveBeenCalled();
-
- enabled = true;
- await vi.advanceTimersByTimeAsync(1000);
- scheduler.stop();
-
- expect(setnx).toHaveBeenCalledTimes(1);
- expect(addJob).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/ExpireAttachments.test.ts b/fluxer_api/src/api/worker/tests/ExpireAttachments.test.ts
index 4db6c2202..1511df8e4 100644
--- a/fluxer_api/src/api/worker/tests/ExpireAttachments.test.ts
+++ b/fluxer_api/src/api/worker/tests/ExpireAttachments.test.ts
@@ -3,8 +3,8 @@
import {AttachmentDecayRepository} from '@app/api/attachment/AttachmentDecayRepository';
import {createAttachmentID, createChannelID, createMessageID} from '@app/api/BrandedTypes';
import {getConfig} from '@app/api/Config';
-import type {IAssetDeletionQueue, QueuedAssetDeletion} from '@app/api/infrastructure/IAssetDeletionQueue';
-import type {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
+import {AssetDeletionQueue} from '@app/api/infrastructure/AssetDeletionQueue';
+import {InstanceConfigRepository} from '@app/api/instance/InstanceConfigRepository';
import {getExpiryBucket} from '@app/api/utils/AttachmentDecay';
import {processExpiredAttachments} from '@app/api/worker/tasks/ExpireAttachments';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
@@ -20,26 +20,16 @@ const UPLOADED_AT = new Date('2026-01-01T00:00:00.000Z');
const FIRST_EXPIRY = new Date('2026-01-31T00:00:00.000Z');
const EXTENDED_EXPIRY = new Date('2026-02-25T00:00:00.000Z');
-function createQueue(): {queue: IAssetDeletionQueue; queued: Array<QueuedAssetDeletion>} {
- const queued: Array<QueuedAssetDeletion> = [];
- const queue = {
- async queueDeletion(item: Omit<QueuedAssetDeletion, 'queuedAt' | 'retryCount'>) {
- queued.push({...item});
- },
- } as unknown as IAssetDeletionQueue;
- return {queue, queued};
+async function installDependencies(kvClient = new MockKVProvider()): Promise<AssetDeletionQueue> {
+ const assetDeletionQueue = new AssetDeletionQueue(kvClient);
+ const instanceConfigRepository = new InstanceConfigRepository();
+ await instanceConfigRepository.setInstanceMediaConfig({attachment_decay: {enabled: true}});
+ setWorkerDependenciesForTest({assetDeletionQueue, kvClient, instanceConfigRepository});
+ return assetDeletionQueue;
}
-function installDependencies(queue: IAssetDeletionQueue, kvClient = new MockKVProvider()): void {
- setWorkerDependenciesForTest({
- assetDeletionQueue: queue,
- kvClient,
- instanceConfigRepository: {
- async getEffectiveAttachmentDecayConfig() {
- return {enabled: true};
- },
- } as unknown as InstanceConfigRepository,
- });
+async function queuedKeys(queue: AssetDeletionQueue): Promise<Array<string>> {
+ return (await queue.getBatch(100)).map((item) => item.s3Key);
}
async function writeDecayRecord(repository: AttachmentDecayRepository, expiresAt: Date): Promise<void> {
@@ -72,21 +62,19 @@ describe('processExpiredAttachments', () => {
])('pauses deletion during a reconcile run only when self-hosted (%s)', async (selfHosted, expectedKeys) => {
getConfig().instance.selfHosted = selfHosted;
const repository = new AttachmentDecayRepository();
- const {queue, queued} = createQueue();
const kvClient = new MockKVProvider();
await kvClient.setex('attachment_decay:reconcile_run', 60, 'run');
- installDependencies(queue, kvClient);
+ const queue = await installDependencies(kvClient);
await writeDecayRecord(repository, FIRST_EXPIRY);
await processExpiredAttachments(new Date(FIRST_EXPIRY.getTime() + ms('1 day')));
- expect(queued.map((item) => item.s3Key)).toEqual(expectedKeys);
+ expect(await queuedKeys(queue)).toEqual(expectedKeys);
});
it('keeps the decay record when it clears a superseded expiry row', async () => {
const repository = new AttachmentDecayRepository();
- const {queue} = createQueue();
- installDependencies(queue);
+ await installDependencies();
await writeDecayRecord(repository, FIRST_EXPIRY);
await writeDecayRecord(repository, EXTENDED_EXPIRY);
@@ -99,15 +87,14 @@ describe('processExpiredAttachments', () => {
it('still queues the asset once the extended expiry passes', async () => {
const repository = new AttachmentDecayRepository();
- const {queue, queued} = createQueue();
- installDependencies(queue);
+ const queue = await installDependencies();
await writeDecayRecord(repository, FIRST_EXPIRY);
await writeDecayRecord(repository, EXTENDED_EXPIRY);
await processExpiredAttachments(new Date(FIRST_EXPIRY.getTime() + ms('1 day')));
await processExpiredAttachments(new Date(EXTENDED_EXPIRY.getTime() + ms('1 day')));
- expect(queued.map((item) => item.s3Key)).toEqual([`attachments/${CHANNEL_ID}/${ATTACHMENT_ID}/${FILENAME}`]);
+ expect(await queuedKeys(queue)).toEqual([`attachments/${CHANNEL_ID}/${ATTACHMENT_ID}/${FILENAME}`]);
expect(await repository.fetchById(ATTACHMENT_ID)).toBeNull();
});
});
diff --git a/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts b/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts
index f36f22f4f..da7542212 100644
--- a/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts
+++ b/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts
@@ -16,7 +16,7 @@ import {ReportRepository} from '@app/api/report/ReportRepository';
import type {IReportSearchService} from '@app/api/search/IReportSearchService';
import {MockStorageService} from '@app/api/test/mocks/MockStorageService';
import {InMemorySearchProvider} from '@app/api/test/search/InMemorySearchProvider';
-import expireReportSnapshots, {
+import {
CHILD_SAFETY_REPORT_RETENTION_DAYS,
processReportRetention,
REPORT_COMPLAINT_WINDOW_DAYS,
@@ -30,7 +30,7 @@ import {DeletionReasons} from '@fluxer/constants/src/Core';
import type {ReportItemOutcome} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import {serializeReportProfileSnapshot} from '@fluxer/schema/src/domains/report/ReportProfileSnapshotSchemas';
import {ms} from 'itty-time';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {beforeEach, describe, expect, it} from 'vitest';
const NOW = new Date('2027-06-01T12:00:00.000Z');
const DAY_MS = ms('1 day');
diff --git a/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.ts b/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.ts
deleted file mode 100644
index f0e163862..000000000
--- a/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.ts
+++ /dev/null
@@ -1,401 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {JetStreamWorkerQueue} from '@app/api/worker/JetStreamWorkerQueue';
-import {WORKER_LANES} from '@app/api/worker/WorkerLaneConfig';
-import {WorkerQueueOverflowError} from '@app/api/worker/WorkerQueueOverflowError';
-import {DiscardPolicy, JetStreamApiError, RetentionPolicy, StorageType, type StreamConfig} from '@nats-io/jetstream';
-import type {JetStreamConnectionManager} from '@pkgs/nats/src/JetStreamConnectionManager';
-import {describe, expect, it} from 'vitest';
-
-const GIB = 1024 * 1024 * 1024;
-const MIB = 1024 * 1024;
-
-const EXPECTED_LIMITS = {
- max_msgs: 2_000_000,
- max_bytes: 8 * GIB,
- max_msgs_per_subject: 250_000,
- discard: DiscardPolicy.New,
- discard_new_per_subject: true,
-};
-
-const LEGACY_CONFIG = {
- name: 'JOBS',
- subjects: ['jobs.>'],
- retention: RetentionPolicy.Workqueue,
- storage: StorageType.File,
- max_age: 7 * 24 * 60 * 60 * 1_000_000_000,
- duplicate_window: 2 * 60 * 1_000_000_000,
- max_msgs: -1,
- max_bytes: -1,
- max_msgs_per_subject: -1,
- discard: DiscardPolicy.Old,
- discard_new_per_subject: false,
-} as unknown as StreamConfig;
-
-interface ConsumerAddConfig {
- durable_name: string;
- filter_subjects: Array<string>;
-}
-
-function withStreamDefaults(config: Partial<StreamConfig>): Partial<StreamConfig> {
- return {
- max_age: 0,
- duplicate_window: 2 * 60 * 1_000_000_000,
- max_msgs: -1,
- max_bytes: -1,
- max_msgs_per_subject: -1,
- max_msg_size: -1,
- discard: DiscardPolicy.Old,
- discard_new_per_subject: false,
- ...config,
- };
-}
-
-function missingResourceError(resource: 'stream' | 'consumer'): JetStreamApiError {
- return new JetStreamApiError({
- code: 404,
- err_code: resource === 'stream' ? 10059 : 10014,
- description: `${resource} not found`,
- });
-}
-
-function streamLimitError(description: string): JetStreamApiError {
- return new JetStreamApiError({code: 503, err_code: 10077, description});
-}
-
-function serverResourceError(): JetStreamApiError {
- return new JetStreamApiError({code: 503, err_code: 10023, description: 'insufficient resources'});
-}
-
-function noStorageError(): JetStreamApiError {
- return new JetStreamApiError({code: 503, err_code: 10047, description: 'insufficient storage resources available'});
-}
-
-function storageBudget(budget: number): (config: Partial<StreamConfig>) => Error | null {
- return (config) => ((config.max_bytes ?? 0) > budget ? noStorageError() : null);
-}
-
-function boundedPublisher(maxPerSubject: number): (subject: string) => {seq: number} {
- const counts = new Map<string, number>();
- let seq = 0;
- return (subject) => {
- const stored = counts.get(subject) ?? 0;
- if (stored >= maxPerSubject) {
- throw streamLimitError('maximum messages per subject exceeded');
- }
- counts.set(subject, stored + 1);
- seq += 1;
- return {seq};
- };
-}
-
-function createQueue(params: {
- existing?: StreamConfig | null;
- dlqExists?: boolean;
- reject?: (config: Partial<StreamConfig>) => Error | null;
- updateError?: Error;
- publish?: (subject: string, body: string, options: {msgID: string}) => {seq: number; duplicate?: boolean};
- subjectCounts?: Record<string, number>;
- subjectCountsError?: Error;
-}): {
- queue: JetStreamWorkerQueue;
- added: Array<Partial<StreamConfig>>;
- dlqAdded: Array<Partial<StreamConfig>>;
- updated: Array<Partial<StreamConfig>>;
- consumerAdds: Array<ConsumerAddConfig>;
-} {
- const added: Array<Partial<StreamConfig>> = [];
- const dlqAdded: Array<Partial<StreamConfig>> = [];
- const updated: Array<Partial<StreamConfig>> = [];
- const consumerAdds: Array<ConsumerAddConfig> = [];
- const connectionManager = {
- getJetStreamManager: () =>
- Promise.resolve({
- consumers: {
- add: (_stream: string, config: ConsumerAddConfig) => {
- consumerAdds.push(config);
- return Promise.resolve({config});
- },
- delete: () => Promise.resolve(true),
- info: () => Promise.reject(missingResourceError('consumer')),
- },
- streams: {
- info: (name: string, options?: {subjects_filter?: string}) => {
- if (name === 'JOBS' && options?.subjects_filter !== undefined) {
- if (params.subjectCountsError) {
- return Promise.reject(params.subjectCountsError);
- }
- return Promise.resolve({
- config: withStreamDefaults(params.existing ?? {}),
- state: {subjects: params.subjectCounts},
- });
- }
- if (name === 'JOBS_DLQ') {
- return params.dlqExists
- ? Promise.resolve({
- config: withStreamDefaults({
- name,
- subjects: ['dlq.>'],
- retention: RetentionPolicy.Limits,
- storage: StorageType.File,
- max_age: 30 * 24 * 60 * 60 * 1_000_000_000,
- max_bytes: 64 * MIB,
- }),
- })
- : Promise.reject(missingResourceError('stream'));
- }
- if (!params.existing) {
- return Promise.reject(missingResourceError('stream'));
- }
- return Promise.resolve({config: withStreamDefaults(params.existing), state: {}});
- },
- add: (config: Partial<StreamConfig>) => {
- (config.name === 'JOBS_DLQ' ? dlqAdded : added).push(config);
- const rejection = params.reject?.(config) ?? null;
- if (rejection !== null) {
- return Promise.reject(rejection);
- }
- return Promise.resolve({config: withStreamDefaults(config)});
- },
- update: (_name: string, config: Partial<StreamConfig>) => {
- if (params.updateError) {
- return Promise.reject(params.updateError);
- }
- updated.push(config);
- const rejection = params.reject?.(config) ?? null;
- if (rejection !== null) {
- return Promise.reject(rejection);
- }
- return Promise.resolve({config: withStreamDefaults(config)});
- },
- },
- }),
- getJetStreamClient: () => ({
- publish: (subject: string, body: string, options: {msgID: string}) => {
- const publish = params.publish ?? (() => ({seq: 1}));
- return Promise.resolve(publish(subject, body, options));
- },
- }),
- } as unknown as JetStreamConnectionManager;
- return {queue: new JetStreamWorkerQueue(connectionManager), added, dlqAdded, updated, consumerAdds};
-}
-
-describe('jobs stream limits', () => {
- it('creates the stream bounded and discarding new messages', async () => {
- const {queue, added, updated} = createQueue({existing: null});
- await queue.ensureStream();
- expect(updated).toHaveLength(0);
- expect(added).toHaveLength(1);
- expect(added[0]).toMatchObject(EXPECTED_LIMITS);
- expect(added[0]).toMatchObject({retention: RetentionPolicy.Workqueue, storage: StorageType.File});
- });
-
- it('lowers the new stream until the server storage budget accepts it', async () => {
- const {queue, added} = createQueue({existing: null, reject: storageBudget(2 * GIB)});
- await queue.ensureStream();
- expect(added.map((config) => config.max_bytes)).toEqual([8 * GIB, 4 * GIB, 2 * GIB]);
- expect(added[2]).toMatchObject({...EXPECTED_LIMITS, max_bytes: 2 * GIB});
- expect(added[2]).toMatchObject({retention: RetentionPolicy.Workqueue, storage: StorageType.File});
- });
-
- it('fails the boot when even the smallest jobs stream does not fit', async () => {
- const {queue, added} = createQueue({existing: null, reject: storageBudget(0)});
- await expect(queue.ensureStream()).rejects.toBeInstanceOf(JetStreamApiError);
- expect(added).toHaveLength(8);
- expect(added[7]?.max_bytes).toBe(64 * MIB);
- });
-
- it('rethrows stream creation failures that are not storage rejections', async () => {
- const failure = new Error('stream name already in use');
- const {queue, added} = createQueue({existing: null, reject: () => failure});
- await expect(queue.ensureStream()).rejects.toBe(failure);
- expect(added).toHaveLength(1);
- });
-
- it('applies the limits to an existing unbounded stream', async () => {
- const {queue, added, updated} = createQueue({existing: LEGACY_CONFIG});
- await queue.ensureStream();
- expect(added).toHaveLength(0);
- expect(updated).toHaveLength(1);
- expect(updated[0]).toEqual(EXPECTED_LIMITS);
- });
-
- it('lowers the limit update until the server storage budget accepts it', async () => {
- const {queue, updated} = createQueue({existing: LEGACY_CONFIG, reject: storageBudget(1 * GIB)});
- await queue.ensureStream();
- expect(updated.map((config) => config.max_bytes)).toEqual([8 * GIB, 4 * GIB, 2 * GIB, 1 * GIB]);
- });
-
- it('leaves an already bounded stream alone', async () => {
- const {queue, added, updated} = createQueue({existing: {...LEGACY_CONFIG, ...EXPECTED_LIMITS}});
- await queue.ensureStream();
- expect(added).toHaveLength(0);
- expect(updated).toHaveLength(0);
- });
-
- it('leaves a stream that was lowered to fit the server alone', async () => {
- const {queue, added, updated} = createQueue({
- existing: {...LEGACY_CONFIG, ...EXPECTED_LIMITS, max_bytes: 1536 * MIB},
- });
- await queue.ensureStream();
- expect(added).toHaveLength(0);
- expect(updated).toHaveLength(0);
- });
-
- it('keeps startup alive when the limit update is rejected', async () => {
- const {queue} = createQueue({existing: LEGACY_CONFIG, updateError: new Error('stream update rejected')});
- await expect(queue.ensureStream()).resolves.toBeUndefined();
- });
-
- it('keeps startup alive when no limit update fits the server', async () => {
- const {queue, updated} = createQueue({existing: LEGACY_CONFIG, reject: storageBudget(0)});
- await expect(queue.ensureStream()).resolves.toBeUndefined();
- expect(updated).toHaveLength(8);
- });
-
- it('leaves the limits alone while a subject holds more than the per-subject limit', async () => {
- const {queue, updated} = createQueue({
- existing: LEGACY_CONFIG,
- subjectCounts: {'jobs.extractEmbeds': 300_000, 'jobs.processAssetDeletionQueue': 10},
- });
- await expect(queue.ensureStream()).resolves.toBeUndefined();
- expect(updated).toHaveLength(0);
- });
-
- it('leaves the limits alone when the subject counts cannot be read', async () => {
- const {queue, updated} = createQueue({existing: LEGACY_CONFIG, subjectCountsError: new Error('no responders')});
- await expect(queue.ensureStream()).resolves.toBeUndefined();
- expect(updated).toHaveLength(0);
- });
-
- it('applies the limits to a drained stream that reports no subjects', async () => {
- const {queue, updated} = createQueue({existing: LEGACY_CONFIG, subjectCounts: undefined});
- await queue.ensureStream();
- expect(updated).toHaveLength(1);
- expect(updated[0]).toEqual(EXPECTED_LIMITS);
- });
-
- it('refuses a stream that is not the worker stream', async () => {
- const {queue} = createQueue({existing: {...LEGACY_CONFIG, retention: RetentionPolicy.Limits} as StreamConfig});
- await expect(queue.ensureStream()).rejects.toThrow(/incompatible retention/);
- });
-});
-
-describe('jobs stream max age', () => {
- it('reports the max age of a jobs stream it creates', async () => {
- const {queue, added} = createQueue({existing: null});
- await queue.ensureStream();
- expect(queue.getJobsStreamMaxAgeMs()).toBe(7 * 24 * 60 * 60 * 1000);
- expect(added[0]?.max_age).toBe(queue.getJobsStreamMaxAgeMs() * 1_000_000);
- });
-
- it('reports the max age an existing jobs stream really has and never changes it', async () => {
- for (const [maxAgeNanos, expectedMs] of [
- [30 * 24 * 60 * 60 * 1_000_000_000, 30 * 24 * 60 * 60 * 1000],
- [0, 0],
- ] as const) {
- const {queue, updated} = createQueue({existing: {...LEGACY_CONFIG, max_age: maxAgeNanos} as StreamConfig});
- await queue.ensureStream();
- expect(queue.getJobsStreamMaxAgeMs()).toBe(expectedMs);
- expect(updated.some((config) => 'max_age' in config)).toBe(false);
- }
- });
-});
-
-describe('dead-letter stream', () => {
- it('keeps startup alive when the dead-letter stream does not fit', async () => {
- const {queue, dlqAdded} = createQueue({dlqExists: false, reject: () => noStorageError()});
- await expect(queue.ensureDlqStream()).resolves.toBeUndefined();
- expect(dlqAdded).toHaveLength(4);
- });
-
- it('rethrows dead-letter creation failures that are not storage rejections', async () => {
- const failure = new Error('no responders');
- const {queue} = createQueue({dlqExists: false, reject: () => failure});
- await expect(queue.ensureDlqStream()).rejects.toBe(failure);
- });
-});
-
-describe('jobs stream enqueue shedding', () => {
- it('rejects enqueues once the stream is at its cap', async () => {
- const {queue} = createQueue({existing: LEGACY_CONFIG, publish: boundedPublisher(2)});
- await expect(queue.enqueue('extractEmbeds', {})).resolves.toEqual({seq: '1', duplicate: false});
- await expect(queue.enqueue('extractEmbeds', {})).resolves.toEqual({seq: '2', duplicate: false});
- await expect(queue.enqueue('extractEmbeds', {})).rejects.toBeInstanceOf(WorkerQueueOverflowError);
- });
-
- it('caps each task type independently', async () => {
- const {queue} = createQueue({existing: LEGACY_CONFIG, publish: boundedPublisher(1)});
- await expect(queue.enqueue('extractEmbeds', {})).resolves.toEqual({seq: '1', duplicate: false});
- await expect(queue.enqueue('extractEmbeds', {})).rejects.toBeInstanceOf(WorkerQueueOverflowError);
- await expect(queue.enqueue('handleMentions', {})).resolves.toEqual({seq: '2', duplicate: false});
- });
-
- it('sheds enqueues the server refuses for lack of resources', async () => {
- const {queue} = createQueue({
- existing: LEGACY_CONFIG,
- publish: () => {
- throw serverResourceError();
- },
- });
- await expect(queue.enqueue('handleMentions', {})).rejects.toBeInstanceOf(WorkerQueueOverflowError);
- });
-
- it('reports a publish the stream deduplicated under the same job key', async () => {
- const seen = new Map<string, number>();
- const {queue} = createQueue({
- existing: LEGACY_CONFIG,
- publish: (_subject, _body, options) => {
- const existing = seen.get(options.msgID);
- if (existing !== undefined) return {seq: existing, duplicate: true};
- seen.set(options.msgID, seen.size + 1);
- return {seq: seen.size, duplicate: false};
- },
- });
- const options = {jobKey: 'batch-audit-log-message-deletes:1'};
- await expect(queue.enqueue('batchGuildAuditLogMessageDeletes', {}, options)).resolves.toEqual({
- seq: '1',
- duplicate: false,
- });
- await expect(queue.enqueue('batchGuildAuditLogMessageDeletes', {}, options)).resolves.toEqual({
- seq: '1',
- duplicate: true,
- });
- await expect(queue.enqueue('batchGuildAuditLogMessageDeletes', {})).resolves.toEqual({seq: '2', duplicate: false});
- });
-
- it('rethrows publish failures that are not stream limits', async () => {
- const failure = new Error('no responders');
- const {queue} = createQueue({
- existing: LEGACY_CONFIG,
- publish: () => {
- throw failure;
- },
- });
- await expect(queue.enqueue('extractEmbeds', {})).rejects.toBe(failure);
- });
-});
-
-describe('lane consumer filters', () => {
- it('keeps consuming retired subjects so legacy jobs are drained instead of orphaned', async () => {
- const {queue, consumerAdds} = createQueue({existing: LEGACY_CONFIG});
- await queue.ensureConsumers(WORKER_LANES);
- const lifecycle = consumerAdds.find((config) => config.durable_name === 'workers_lifecycle');
- expect(lifecycle?.filter_subjects).toContain('jobs.sendSystemDm');
- expect(lifecycle?.filter_subjects).toContain('jobs.sendScheduledMessage');
- });
-
- it('leaves lanes without retired tasks filtering only their own subjects', async () => {
- const {queue, consumerAdds} = createQueue({existing: LEGACY_CONFIG});
- await queue.ensureConsumers(WORKER_LANES);
- const unfurl = consumerAdds.find((config) => config.durable_name === 'workers_unfurl');
- expect(unfurl?.filter_subjects).toEqual(['jobs.extractEmbeds']);
- });
-
- it('never claims the same subject from two lane consumers', async () => {
- const {queue, consumerAdds} = createQueue({existing: LEGACY_CONFIG});
- await queue.ensureConsumers(WORKER_LANES);
- const allSubjects = consumerAdds.flatMap((config) => config.filter_subjects);
- expect(new Set(allSubjects).size).toBe(allSubjects.length);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/ProcessAssetDeletionQueue.test.ts b/fluxer_api/src/api/worker/tests/ProcessAssetDeletionQueue.test.ts
index dccdedec1..c4c8f1444 100644
--- a/fluxer_api/src/api/worker/tests/ProcessAssetDeletionQueue.test.ts
+++ b/fluxer_api/src/api/worker/tests/ProcessAssetDeletionQueue.test.ts
@@ -1,28 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {AssetDeletionQueue} from '@app/api/infrastructure/AssetDeletionQueue';
import {NoopPurgeQueue} from '@app/api/infrastructure/CachePurgeQueue';
-import type {IStorageService} from '@app/api/infrastructure/IStorageService';
-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
+import {MockStorageService} from '@app/api/test/mocks/MockStorageService';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
+import {UserRepository} from '@app/api/user/repositories/UserRepository';
import processAssetDeletionQueue from '@app/api/worker/tasks/ProcessAssetDeletionQueue';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type {WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';
-import {afterEach, describe, expect, it, vi} from 'vitest';
+import {afterEach, describe, expect, it} from 'vitest';
-const HELPERS = {logger: new NoopLogger()} as unknown as WorkerTaskHelpers;
-
-function createHarness(deleteObject: IStorageService['deleteObject']) {
+function createHarness(storageService: MockStorageService) {
const kvClient = new MockKVProvider();
const assetDeletionQueue = new AssetDeletionQueue(kvClient);
setWorkerDependenciesForTest({
assetDeletionQueue,
purgeQueue: new NoopPurgeQueue(),
- storageService: {deleteObject} as unknown as IStorageService,
- userRepository: {findUnique: async () => null} as never,
- guildRepository: {findUnique: async () => null, getMember: async () => null} as never,
+ storageService,
+ userRepository: new UserRepository(kvClient),
+ guildRepository: new GuildRepository(),
});
- return {assetDeletionQueue, kvClient};
+ return {assetDeletionQueue};
}
async function queueAssets(assetDeletionQueue: AssetDeletionQueue, count: number): Promise<void> {
@@ -41,37 +40,32 @@ describe('processAssetDeletionQueue', () => {
});
it('attempts each queued asset once per run when storage is failing', async () => {
- const deleteObject = vi.fn().mockRejectedValue(new Error('s3 unavailable'));
- const {assetDeletionQueue} = createHarness(deleteObject);
+ const {assetDeletionQueue} = createHarness(new MockStorageService({shouldFailDelete: true}));
await queueAssets(assetDeletionQueue, 3);
- await expect(processAssetDeletionQueue({}, HELPERS)).rejects.toThrow(/3 failures/);
+ await expect(processAssetDeletionQueue({}, createTestWorkerHelpers())).rejects.toThrow(/3 failures/);
- expect(deleteObject).toHaveBeenCalledTimes(3);
- expect(await assetDeletionQueue.getQueueSize()).toBe(3);
const remaining = await assetDeletionQueue.getBatch(10);
expect(remaining.map((item) => item.retryCount)).toEqual([1, 1, 1]);
});
it('attempts each queued asset once per run across batch boundaries', async () => {
- const deleteObject = vi.fn().mockRejectedValue(new Error('s3 unavailable'));
- const {assetDeletionQueue} = createHarness(deleteObject);
+ const {assetDeletionQueue} = createHarness(new MockStorageService({shouldFailDelete: true}));
await queueAssets(assetDeletionQueue, 60);
- await expect(processAssetDeletionQueue({}, HELPERS)).rejects.toThrow(/60 failures/);
+ await expect(processAssetDeletionQueue({}, createTestWorkerHelpers())).rejects.toThrow(/60 failures/);
- expect(deleteObject).toHaveBeenCalledTimes(60);
- expect(await assetDeletionQueue.getQueueSize()).toBe(60);
+ const remaining = await assetDeletionQueue.getBatch(100);
+ expect(remaining).toHaveLength(60);
+ expect(remaining.every((item) => item.retryCount === 1)).toBe(true);
});
it('drains the queue when storage succeeds', async () => {
- const deleteObject = vi.fn().mockResolvedValue(undefined);
- const {assetDeletionQueue} = createHarness(deleteObject);
+ const {assetDeletionQueue} = createHarness(new MockStorageService());
await queueAssets(assetDeletionQueue, 60);
- await processAssetDeletionQueue({}, HELPERS);
+ await processAssetDeletionQueue({}, createTestWorkerHelpers());
- expect(deleteObject).toHaveBeenCalledTimes(60);
expect(await assetDeletionQueue.getQueueSize()).toBe(0);
});
});
diff --git a/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts b/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts
index 7ce7a7325..6194f5c07 100644
--- a/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts
+++ b/fluxer_api/src/api/worker/tests/ProcessCachePurgeQueue.test.ts
@@ -3,16 +3,14 @@
import {Config} from '@app/api/Config';
import type {APICachePurgeConfig} from '@app/api/config/APIConfig';
import {CachePurgeQueue} from '@app/api/infrastructure/CachePurgeQueue';
-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
import {server} from '@app/api/test/msw/server';
+import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import processCachePurgeQueue from '@app/api/worker/tasks/ProcessCachePurgeQueue';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type {WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';
-import {delay, HttpResponse, http} from 'msw';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {HttpResponse, http} from 'msw';
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
-const HELPERS = {logger: new NoopLogger()} as unknown as WorkerTaskHelpers;
const ENDPOINT = 'https://cache-purge.test/__cache/purge';
const MEDIA = 'https://media.test';
const QUEUE_KEY = 'cache_purge:queue';
@@ -72,7 +70,7 @@ describe('processCachePurgeQueue', () => {
previousMedia = Config.endpoints.media;
Config.endpoints.media = MEDIA;
Config.cachePurge.adapter = 'http';
- Config.cachePurge.http = {endpoint: ENDPOINT, token: 'test-token', timeoutMs: 50};
+ Config.cachePurge.http = {endpoint: ENDPOINT, token: 'test-token', timeoutMs: 5000};
});
afterEach(() => {
@@ -80,7 +78,6 @@ describe('processCachePurgeQueue', () => {
Config.cachePurge.http = previousCachePurge.http;
Config.endpoints.media = previousMedia;
clearWorkerDependencies();
- vi.useRealTimers();
});
it('sends host qualified prefixes in one request and drains the queue', async () => {
@@ -92,7 +89,7 @@ describe('processCachePurgeQueue', () => {
]);
const requests = recordPurges(() => new HttpResponse(null, {status: 204}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(requests[0]!.authorization).toBe('Bearer test-token');
@@ -113,7 +110,7 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls([`${MEDIA}/stickers/7.webp`, `${MEDIA}/stickers/7.gif`, `${MEDIA}/stickers/7.png`]);
const requests = recordPurges(() => new HttpResponse(null, {status: 204}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(requests[0]!.body.prefixes).toEqual(['media.test/stickers/7']);
@@ -124,7 +121,7 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`]);
const requests = recordPurges(() => new HttpResponse(null, {status}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(await members(kvClient, QUEUE_KEY)).toEqual([]);
@@ -136,7 +133,7 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls(['https://elsewhere.test/avatars/1/b35cc3d3', `${MEDIA}/avatars`, 'not-a-url']);
const requests = recordPurges(() => new HttpResponse(null, {status: 204}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toEqual([]);
expect(await members(kvClient, QUEUE_KEY)).toEqual([]);
@@ -147,7 +144,7 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`, `${MEDIA}/attachments/1/3/b.png`]);
const requests = recordPurges(() => new HttpResponse(null, {status: 503}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(await members(kvClient, QUEUE_KEY)).toEqual([
@@ -157,26 +154,12 @@ describe('processCachePurgeQueue', () => {
expect(await members(kvClient, REJECTED_KEY)).toEqual([]);
});
- it('requeues the batch when the endpoint does not answer in time', async () => {
- const {kvClient, queue} = createHarness();
- await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`]);
- const requests = recordPurges(async () => {
- await delay('infinite');
- return new HttpResponse(null, {status: 204});
- });
-
- await processCachePurgeQueue({}, HELPERS);
-
- expect(requests).toHaveLength(1);
- expect(await members(kvClient, QUEUE_KEY)).toEqual(['media.test/attachments/1/2/a']);
- });
-
it('requeues the batch when the endpoint is unreachable', async () => {
const {kvClient, queue} = createHarness();
await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`]);
const requests = recordPurges(() => HttpResponse.error());
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(await members(kvClient, QUEUE_KEY)).toEqual(['media.test/attachments/1/2/a']);
@@ -195,7 +178,7 @@ describe('processCachePurgeQueue', () => {
);
const requests = recordPurges(() => new HttpResponse(null, {status: 302, headers: {Location: redirectTarget}}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(redirectedRequests).toEqual([]);
@@ -207,7 +190,7 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`]);
const requests = recordPurges(() => new HttpResponse(null, {status: 401}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(await members(kvClient, QUEUE_KEY)).toEqual(['media.test/attachments/1/2/a']);
@@ -219,7 +202,7 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`, `${MEDIA}/emojis/9.webp`]);
const requests = recordPurges(() => new HttpResponse(null, {status}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toHaveLength(1);
expect(await members(kvClient, QUEUE_KEY)).toEqual([]);
@@ -232,26 +215,10 @@ describe('processCachePurgeQueue', () => {
await queue.addUrls([`${MEDIA}/attachments/1/2/a.png`]);
const requests = recordPurges(() => new HttpResponse(null, {status: 204}));
- await processCachePurgeQueue({}, HELPERS);
+ await processCachePurgeQueue({}, createTestWorkerHelpers());
expect(requests).toEqual([]);
expect(await members(kvClient, QUEUE_KEY)).toEqual(['media.test/attachments/1/2/a']);
expect(await kvClient.get(BUDGET_KEY)).toBeNull();
});
-
- it('sends no more than the token bucket allows and refills at the configured rate', async () => {
- vi.useFakeTimers({toFake: ['Date']});
- vi.setSystemTime(new Date('2026-09-16T00:00:00.000Z'));
- const {kvClient, queue} = createHarness();
- await queue.addUrls(Array.from({length: 200}, (_, index) => `${MEDIA}/attachments/1/${index}/a.png`));
- const requests = recordPurges(() => new HttpResponse(null, {status: 204}));
-
- await processCachePurgeQueue({}, HELPERS);
- await processCachePurgeQueue({}, HELPERS);
- vi.setSystemTime(Date.now() + 10_000);
- await processCachePurgeQueue({}, HELPERS);
-
- expect(requests.map((request) => request.body.prefixes.length)).toEqual([120, 50]);
- expect(await kvClient.scard(QUEUE_KEY)).toBe(30);
- });
});
diff --git a/fluxer_api/src/api/worker/tests/ProcessExpiredPremiumSweep.test.ts b/fluxer_api/src/api/worker/tests/ProcessExpiredPremiumSweep.test.ts
deleted file mode 100644
index 9752dd283..000000000
--- a/fluxer_api/src/api/worker/tests/ProcessExpiredPremiumSweep.test.ts
+++ /dev/null
@@ -1,241 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createUserID} from '@app/api/BrandedTypes';
-import {getConfig} from '@app/api/Config';
-import type {StorePurchaseRow} from '@app/api/database/types/StoreBillingTypes';
-import type {UserRow} from '@app/api/database/types/UserTypes';
-import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
-import {getCachedInstancePremiumMode, setCachedInstancePremiumMode} from '@app/api/limits/InstancePremiumModeCache';
-import {User} from '@app/api/models/User';
-import type {StoreEntitlementService} from '@app/api/store_billing/StoreEntitlementService';
-import {buildStorePurchaseRow} from '@app/api/store_billing/tests/StoreBillingTestUtils';
-import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import processExpiredPremiumSweep from '@app/api/worker/tasks/ProcessExpiredPremiumSweep';
-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
-import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
-import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';
-import {ms} from 'itty-time';
-import {afterEach, describe, expect, test} from 'vitest';
-
-function createHarness() {
- const scanLimits: Array<number> = [];
- const userRepository = {
- async scanAllUsersPage(limit: number): Promise<{users: []; pageState: null}> {
- scanLimits.push(limit);
- return {users: [], pageState: null};
- },
- } as unknown as UserRepository;
- setWorkerDependenciesForTest({userRepository});
- return {scanLimits};
-}
-
-const EXPIRED_USER_ID = createUserID(834271905123471362n);
-
-function createExpiredStoreUserHarness(storeRows: Array<StorePurchaseRow>) {
- const user = new User({
- ...EMPTY_USER_ROW,
- user_id: EXPIRED_USER_ID,
- username: 'storelapse',
- discriminator: 1,
- premium_type: UserPremiumTypes.SUBSCRIPTION,
- premium_since: new Date(Date.now() - ms('60 days')),
- premium_until: new Date(Date.now() - ms('10 days')),
- premium_grace_ends_at: new Date(Date.now() - ms('10 days')),
- });
- const patches: Array<Partial<UserRow>> = [];
- const jobs: Array<{task: string; payload: unknown; jobKey: string | undefined}> = [];
- const userRepository = {
- async scanAllUsersPage(): Promise<{users: Array<User>; pageState: null}> {
- return {users: [user], pageState: null};
- },
- async patchUpsert(_userId: unknown, patch: Partial<UserRow>): Promise<User> {
- patches.push(patch);
- return new User({...user.toRow(), ...patch});
- },
- async getUserGuildIds(): Promise<Array<never>> {
- return [];
- },
- } as unknown as UserRepository;
- const storeEntitlementService = {
- async listStorePurchases() {
- return storeRows;
- },
- } as unknown as StoreEntitlementService;
- const workerService = {
- async addJob(task: string, payload: unknown, options?: {jobKey?: string}) {
- jobs.push({task, payload, jobKey: options?.jobKey});
- return 0n;
- },
- } as unknown as IWorkerService<never>;
- setWorkerDependenciesForTest({
- userRepository,
- storeEntitlementService,
- workerService,
- userCacheService: {setUserPartialResponseFromUserInBackground: () => {}} as never,
- gatewayService: {dispatchPresence: async () => {}} as never,
- });
- return {patches, jobs};
-}
-
-async function withSelfHosted(
- selfHosted: boolean,
- callback: () => Promise<void>,
- premiumMode: 'mirror' | 'everyone' = 'everyone',
-): Promise<void> {
- const config = getConfig();
- const originalSelfHosted = config.instance.selfHosted;
- const originalPremiumMode = getCachedInstancePremiumMode();
- try {
- config.instance.selfHosted = selfHosted;
- setCachedInstancePremiumMode(premiumMode);
- await callback();
- } finally {
- config.instance.selfHosted = originalSelfHosted;
- setCachedInstancePremiumMode(originalPremiumMode);
- }
-}
-
-describe('processExpiredPremiumSweep', () => {
- afterEach(() => {
- clearWorkerDependencies();
- });
-
- test('scans no users on a self-hosted instance where everyone is premium', async () => {
- const harness = createHarness();
-
- await withSelfHosted(true, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
-
- expect(harness.scanLimits).toEqual([]);
- });
-
- test('scans users on a self-hosted instance in mirror mode', async () => {
- const harness = createHarness();
-
- await withSelfHosted(
- true,
- async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- },
- 'mirror',
- );
-
- expect(harness.scanLimits).toEqual([100]);
- });
-
- test('refreshes a stale store subscription instead of stripping premium', async () => {
- const row = buildStorePurchaseRow({
- user_id: EXPIRED_USER_ID,
- expires_at: new Date(Date.now() - ms('2 hours')),
- synced_at: new Date(Date.now() - ms('3 hours')),
- });
- const harness = createExpiredStoreUserHarness([row]);
-
- await withSelfHosted(false, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
-
- expect(harness.patches).toEqual([]);
- expect(harness.jobs).toEqual([
- {
- task: 'refreshStorePurchase',
- payload: {storeKey: row.store_key},
- jobKey: `refreshStorePurchase:${row.store_key}`,
- },
- ]);
- });
-
- test('strips premium when the store subscription was synced recently', async () => {
- const harness = createExpiredStoreUserHarness([
- buildStorePurchaseRow({
- user_id: EXPIRED_USER_ID,
- expires_at: new Date(Date.now() - ms('10 days')),
- synced_at: new Date(Date.now() - ms('5 minutes')),
- }),
- buildStorePurchaseRow({
- user_id: EXPIRED_USER_ID,
- state: 'expired',
- entitled: false,
- synced_at: new Date(Date.now() - ms('2 days')),
- }),
- ]);
-
- await withSelfHosted(false, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
-
- expect(harness.jobs).toEqual([]);
- expect(harness.patches[0]).toMatchObject({premium_type: null, premium_until: null});
- });
-
- test('strips premium once a sync after the access end confirmed the store state', async () => {
- const harness = createExpiredStoreUserHarness([
- buildStorePurchaseRow({
- user_id: EXPIRED_USER_ID,
- state: 'billing_retry',
- entitled: false,
- expires_at: new Date(Date.now() - ms('3 hours')),
- synced_at: new Date(Date.now() - ms('1 hour')),
- }),
- ]);
-
- await withSelfHosted(false, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
-
- expect(harness.jobs).toEqual([]);
- expect(harness.patches[0]).toMatchObject({premium_type: null, premium_until: null});
- });
-
- test('strips premium when the store access ended more than a day ago', async () => {
- const harness = createExpiredStoreUserHarness([
- buildStorePurchaseRow({
- user_id: EXPIRED_USER_ID,
- expires_at: new Date(Date.now() - ms('2 days')),
- synced_at: new Date(Date.now() - ms('3 days')),
- }),
- ]);
-
- await withSelfHosted(false, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
-
- expect(harness.jobs).toEqual([]);
- expect(harness.patches[0]).toMatchObject({premium_type: null, premium_until: null});
- });
-
- test('strips premium when the store provider is not configured', async () => {
- const harness = createExpiredStoreUserHarness([
- buildStorePurchaseRow({
- user_id: EXPIRED_USER_ID,
- expires_at: new Date(Date.now() - ms('2 hours')),
- synced_at: new Date(Date.now() - ms('3 hours')),
- }),
- ]);
- const config = getConfig();
- const originalEnabled = config.appStore.enabled;
- try {
- config.appStore.enabled = false;
- await withSelfHosted(false, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
- } finally {
- config.appStore.enabled = originalEnabled;
- }
-
- expect(harness.jobs).toEqual([]);
- expect(harness.patches[0]).toMatchObject({premium_type: null, premium_until: null});
- });
-
- test('scans users on a hosted instance', async () => {
- const harness = createHarness();
-
- await withSelfHosted(false, async () => {
- await processExpiredPremiumSweep({}, createTestWorkerHelpers());
- });
-
- expect(harness.scanLimits).toEqual([100]);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/ProcessPremiumStateReconciliationQueue.test.ts b/fluxer_api/src/api/worker/tests/ProcessPremiumStateReconciliationQueue.test.ts
index c5f3aea86..5dd48cbb7 100644
--- a/fluxer_api/src/api/worker/tests/ProcessPremiumStateReconciliationQueue.test.ts
+++ b/fluxer_api/src/api/worker/tests/ProcessPremiumStateReconciliationQueue.test.ts
@@ -1,209 +1,32 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createUserID, type UserID} from '@app/api/BrandedTypes';
-import type {UserRow} from '@app/api/database/types/UserTypes';
-import {EMPTY_USER_ROW} from '@app/api/database/types/UserTypes';
+import {createUserID} from '@app/api/BrandedTypes';
import {PremiumStateReconciliationQueueService} from '@app/api/infrastructure/PremiumStateReconciliationQueueService';
-import {User} from '@app/api/models/User';
import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {UserRepository} from '@app/api/user/repositories/UserRepository';
import processPremiumStateReconciliationQueue from '@app/api/worker/tasks/ProcessPremiumStateReconciliationQueue';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
-import {PremiumFlags} from '@fluxer/constants/src/UserConstants';
import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type Stripe from 'stripe';
+import Stripe from 'stripe';
import {afterEach, describe, expect, test} from 'vitest';
const USER_ID = createUserID(834271905123471361n);
const ONE_HOUR_MS = 60 * 60 * 1000;
-const ONE_DAY_MS = 24 * ONE_HOUR_MS;
-
-function createPremiumUser(overrides: Partial<UserRow> = {}): User {
- return new User({
- ...EMPTY_USER_ROW,
- user_id: USER_ID,
- username: 'paidlate',
- discriminator: 1,
- premium_type: 1,
- premium_since: new Date(Date.now() - 200 * ONE_DAY_MS),
- premium_until: new Date(Date.now() + 20 * ONE_DAY_MS),
- stripe_customer_id: 'cus_test',
- stripe_subscription_id: 'sub_test',
- ...overrides,
- });
-}
-
-function createCancelledSubscription(endedAtMs: number): Stripe.Subscription {
- return {
- id: 'sub_test',
- status: 'canceled',
- customer: 'cus_test',
- ended_at: Math.floor(endedAtMs / 1000),
- canceled_at: Math.floor(endedAtMs / 1000),
- cancel_at: null,
- cancel_at_period_end: false,
- trial_end: null,
- start_date: Math.floor((Date.now() - 200 * ONE_DAY_MS) / 1000),
- items: {data: []},
- } as unknown as Stripe.Subscription;
-}
-
-function createActiveSubscription(periodEndMs: number): Stripe.Subscription {
- return {
- id: 'sub_test',
- status: 'active',
- customer: 'cus_test',
- ended_at: null,
- canceled_at: null,
- cancel_at: null,
- cancel_at_period_end: false,
- trial_end: null,
- start_date: Math.floor((Date.now() - 200 * ONE_DAY_MS) / 1000),
- items: {
- data: [
- {
- current_period_end: Math.floor(periodEndMs / 1000),
- price: {recurring: {interval: 'month'}},
- },
- ],
- },
- } as unknown as Stripe.Subscription;
-}
-
-function createPastDueSubscription(): Stripe.Subscription {
- return {
- id: 'sub_test',
- status: 'past_due',
- customer: 'cus_test',
- ended_at: null,
- canceled_at: null,
- cancel_at: null,
- cancel_at_period_end: false,
- trial_end: null,
- start_date: Math.floor((Date.now() - 200 * ONE_DAY_MS) / 1000),
- items: {
- data: [
- {
- current_period_end: Math.floor((Date.now() + 29 * ONE_DAY_MS) / 1000),
- price: {recurring: {interval: 'month'}},
- },
- ],
- },
- } as unknown as Stripe.Subscription;
-}
-
-function createPaidInvoice(periodEndMs: number): Stripe.Invoice {
- return {
- id: 'in_test',
- status: 'paid',
- lines: {data: [{period: {start: 0, end: Math.floor(periodEndMs / 1000)}}]},
- } as unknown as Stripe.Invoice;
-}
-
-function createStripeStub(subscription: Stripe.Subscription, invoices: Array<Stripe.Invoice>): Stripe {
- return {
- subscriptions: {
- retrieve: async () => subscription,
- list: async () => ({data: [subscription]}),
- },
- invoices: {
- list: async () => ({data: invoices}),
- },
- } as unknown as Stripe;
-}
-
-function createCapturingDeps(
- user: User,
- storeEntitlement: {expiresAt: Date} | null = null,
-): {
- userRepository: UserRepository;
- patches: Array<Partial<UserRow>>;
- storeApplications: Array<UserID>;
- extras: Record<string, unknown>;
-} {
- const storeApplications: Array<UserID> = [];
- const patches: Array<Partial<UserRow>> = [];
- const userRepository = {
- findUnique: async () => user,
- patchUpsert: async (_id: unknown, patch: Partial<UserRow>) => {
- patches.push(patch);
- return new User({...user.toRow(), ...patch});
- },
- } as unknown as UserRepository;
- const extras = {
- userCacheService: {setUserPartialResponseFromUserInBackground: () => {}},
- gatewayService: {dispatchPresence: async () => {}},
- storeEntitlementService: {
- getActiveStoreEntitlement: async () =>
- storeEntitlement
- ? {
- provider: 'app_store',
- storePurchaseId: 1n,
- entitledUntil: storeEntitlement.expiresAt,
- expiresAt: storeEntitlement.expiresAt,
- graceEndsAt: null,
- autoRenew: true,
- slot: 'monthly',
- }
- : null,
- applyStoreEntitlementToUser: async (userId: UserID) => {
- storeApplications.push(userId);
- },
- },
- };
- return {userRepository, patches, storeApplications, extras};
-}
-
-function createQueueService(): PremiumStateReconciliationQueueService {
- return new PremiumStateReconciliationQueueService(new MockKVProvider());
-}
describe('processPremiumStateReconciliationQueue', () => {
afterEach(() => {
clearWorkerDependencies();
});
- test('keeps the user in the queue when the worker dies mid-reconciliation', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- let signalReconcileStarted: () => void = () => {};
- const reconcileStarted = new Promise<void>((resolve) => {
- signalReconcileStarted = resolve;
- });
- const userRepository = {
- findUnique: async () => {
- signalReconcileStarted();
- return await new Promise<never>(() => {});
- },
- } as unknown as UserRepository;
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: {} as Stripe,
- userRepository,
- });
-
- void processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
- await reconcileStarted;
-
- expect(await queueService.getQueueSize()).toBe(1);
- expect(await queueService.getReadyUserIds(Date.now(), 10)).toEqual([]);
- expect(await queueService.getReadyUserIds(Date.now() + ONE_HOUR_MS, 10)).toEqual([USER_ID]);
- });
-
test('removes the user from the queue once reconciliation commits', async () => {
- const queueService = createQueueService();
+ const kvClient = new MockKVProvider();
+ const queueService = new PremiumStateReconciliationQueueService(kvClient);
await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
- const userRepository = {
- findUnique: async () => null,
- } as unknown as UserRepository;
-
setWorkerDependenciesForTest({
premiumStateReconciliationQueueService: queueService,
- stripe: {} as Stripe,
- userRepository,
+ stripe: new Stripe('sk_test_reconcile'),
+ userRepository: new UserRepository(kvClient),
});
await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
@@ -213,7 +36,7 @@ describe('processPremiumStateReconciliationQueue', () => {
});
test('rejects a second claim until the lease expires', async () => {
- const queueService = createQueueService();
+ const queueService = new PremiumStateReconciliationQueueService(new MockKVProvider());
await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
const now = Date.now();
@@ -221,337 +44,4 @@ describe('processPremiumStateReconciliationQueue', () => {
expect(await queueService.claimUser(USER_ID, now, now + ONE_HOUR_MS)).toBe(false);
expect(await queueService.claimUser(USER_ID, now + ONE_HOUR_MS, now + 2 * ONE_HOUR_MS)).toBe(true);
});
-
- test('reconciles the user once when two runs claim the same entry', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- let signalFirstClaimEntered: () => void = () => {};
- const firstClaimEntered = new Promise<void>((resolve) => {
- signalFirstClaimEntered = resolve;
- });
- let releaseFirstClaim: () => void = () => {};
- const firstClaimReleased = new Promise<void>((resolve) => {
- releaseFirstClaim = resolve;
- });
- const claimUser = queueService.claimUser.bind(queueService);
- let firstClaim = true;
- queueService.claimUser = async (userId, nowMs, leaseUntilMs) => {
- if (firstClaim) {
- firstClaim = false;
- signalFirstClaimEntered();
- await firstClaimReleased;
- }
- return await claimUser(userId, nowMs, leaseUntilMs);
- };
-
- let signalReconcileStarted: () => void = () => {};
- const reconcileStarted = new Promise<void>((resolve) => {
- signalReconcileStarted = resolve;
- });
- let releaseReconcile: () => void = () => {};
- const reconcileReleased = new Promise<void>((resolve) => {
- releaseReconcile = resolve;
- });
- let findUniqueCalls = 0;
- const userRepository = {
- findUnique: async () => {
- findUniqueCalls += 1;
- signalReconcileStarted();
- await reconcileReleased;
- return null;
- },
- } as unknown as UserRepository;
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: {} as Stripe,
- userRepository,
- });
-
- const firstRun = processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
- await firstClaimEntered;
- const secondRun = processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
- await reconcileStarted;
- releaseFirstClaim();
- releaseReconcile();
- await Promise.all([firstRun, secondRun]);
-
- expect(findUniqueCalls).toBe(1);
- expect(await queueService.getQueueSize()).toBe(0);
- });
-
- test('keeps premium when a paid invoice covers a period beyond the cancellation', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const endedAtMs = Date.now() - 3 * ONE_DAY_MS;
- const paidThroughMs = Math.floor((Date.now() + 20 * ONE_DAY_MS) / 1000) * 1000;
- const user = createPremiumUser({premium_until: new Date(paidThroughMs)});
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createCancelledSubscription(endedAtMs), [createPaidInvoice(paidThroughMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(1);
- const patch = patches[0];
- expect(patch.premium_type).toBeUndefined();
- expect(patch.premium_since).toBeUndefined();
- expect(patch.premium_until).toBeUndefined();
- expect(patch.premium_will_cancel).toBe(true);
- });
-
- test('extends premium to the paid period instead of the cancellation date', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const endedAtMs = Date.now() - 3 * ONE_DAY_MS;
- const paidThroughMs = Date.now() + 20 * ONE_DAY_MS;
- const user = createPremiumUser({premium_until: new Date(Date.now() + 5 * ONE_DAY_MS)});
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createCancelledSubscription(endedAtMs), [createPaidInvoice(paidThroughMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(1);
- expect(patches[0].premium_until).toEqual(new Date(Math.floor(paidThroughMs / 1000) * 1000));
- expect(patches[0].premium_will_cancel).toBe(true);
- expect(patches[0].premium_type).toBeUndefined();
- });
-
- test('still strips premium when no paid invoice covers a future period', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const endedAtMs = Date.now() - 3 * ONE_DAY_MS;
- const paidThroughMs = Date.now() - 3 * ONE_DAY_MS;
- const user = createPremiumUser();
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createCancelledSubscription(endedAtMs), [createPaidInvoice(paidThroughMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(1);
- expect(patches[0].premium_type).toBeNull();
- expect(patches[0].premium_until).toBeNull();
- expect(patches[0].premium_since).toBeNull();
- });
- test('keeps premium for a past_due subscription until the recorded payment recovery deadline', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const lapseStartMs = Math.floor((Date.now() - ONE_HOUR_MS) / 1000) * 1000;
- const user = createPremiumUser({
- premium_until: new Date(lapseStartMs),
- premium_will_cancel: true,
- premium_billing_cycle: 'monthly',
- premium_grace_ends_at: new Date(lapseStartMs + 7 * ONE_DAY_MS),
- });
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createPastDueSubscription(), [createPaidInvoice(lapseStartMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(0);
- expect(await queueService.getQueueSize()).toBe(0);
- });
-
- test('keeps the recovery deadline when an older cancelled subscription shares the customer', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const lapseStartMs = Math.floor((Date.now() - ONE_HOUR_MS) / 1000) * 1000;
- const recoveryDeadline = new Date(lapseStartMs + 7 * ONE_DAY_MS);
- const user = createPremiumUser({
- premium_until: new Date(lapseStartMs),
- premium_will_cancel: true,
- premium_billing_cycle: 'monthly',
- premium_grace_ends_at: recoveryDeadline,
- stripe_subscription_id: 'sub_current',
- });
- const {userRepository, patches, extras} = createCapturingDeps(user);
- const currentSubscription = {...createPastDueSubscription(), id: 'sub_current'} as Stripe.Subscription;
- const olderSubscription = {
- ...createCancelledSubscription(Date.now() - 90 * ONE_DAY_MS),
- id: 'sub_older',
- } as Stripe.Subscription;
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: {
- subscriptions: {
- retrieve: async () => currentSubscription,
- list: async () => ({data: [olderSubscription, currentSubscription]}),
- },
- invoices: {
- list: async () => ({data: [createPaidInvoice(Date.now() - 90 * ONE_DAY_MS)]}),
- },
- } as unknown as Stripe,
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(0);
- });
-
- test('clears a leftover recovery deadline once the subscription is active again', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const periodEndMs = Math.floor((Date.now() + 29 * ONE_DAY_MS) / 1000) * 1000;
- const user = createPremiumUser({
- premium_until: new Date(periodEndMs),
- premium_billing_cycle: 'monthly',
- premium_grace_ends_at: new Date(Date.now() + 6 * ONE_DAY_MS),
- });
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createActiveSubscription(periodEndMs), []),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(1);
- expect(patches[0].premium_grace_ends_at).toBeNull();
- expect(patches[0].premium_until).toBeUndefined();
- });
-
- test('strips a past_due subscription once the recovery deadline has passed', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const lapseStartMs = Math.floor((Date.now() - 7 * ONE_DAY_MS - 60_000) / 1000) * 1000;
- const user = createPremiumUser({
- premium_until: new Date(lapseStartMs),
- premium_will_cancel: true,
- premium_billing_cycle: 'monthly',
- premium_grace_ends_at: new Date(lapseStartMs + 7 * ONE_DAY_MS),
- });
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createPastDueSubscription(), [createPaidInvoice(lapseStartMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(1);
- expect(patches[0].premium_type).toBeNull();
- expect(patches[0].premium_grace_ends_at).toBeNull();
- });
-
- test('honours the voluntary-cancel grace written by the delete webhook', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const endedAtMs = Math.floor((Date.now() - 60_000) / 1000) * 1000;
- const user = createPremiumUser({
- premium_until: new Date(endedAtMs),
- premium_will_cancel: false,
- premium_billing_cycle: null,
- stripe_subscription_id: null,
- premium_grace_ends_at: new Date(endedAtMs + 3 * ONE_DAY_MS),
- });
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createCancelledSubscription(endedAtMs), [createPaidInvoice(endedAtMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches.every((patch) => patch.premium_type === undefined)).toBe(true);
- expect(patches.every((patch) => patch.premium_until === undefined)).toBe(true);
- expect(patches.every((patch) => patch.premium_grace_ends_at === undefined)).toBe(true);
- });
-
- test('hands a user with an active App Store subscription and a stale Stripe customer to the store', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const endedAtMs = Date.now() - 40 * ONE_DAY_MS;
- const storeExpiresAt = new Date(Date.now() + 20 * ONE_DAY_MS);
- const user = createPremiumUser({
- premium_until: storeExpiresAt,
- premium_billing_cycle: null,
- premium_will_cancel: false,
- stripe_subscription_id: null,
- });
- const {userRepository, patches, storeApplications, extras} = createCapturingDeps(user, {
- expiresAt: storeExpiresAt,
- });
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createCancelledSubscription(endedAtMs), [createPaidInvoice(endedAtMs)]),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toEqual([]);
- expect(storeApplications).toEqual([USER_ID]);
- expect(await queueService.getQueueSize()).toBe(0);
- });
-
- test('clears the perks-sanitized latch once the subscription is active again', async () => {
- const queueService = createQueueService();
- await queueService.enqueueUser(USER_ID, new Date(Date.now() - 1000));
-
- const periodEndMs = Math.floor((Date.now() + 20 * ONE_DAY_MS) / 1000) * 1000;
- const user = createPremiumUser({
- premium_until: new Date(periodEndMs),
- premium_flags: PremiumFlags.PERKS_SANITIZED,
- });
- const {userRepository, patches, extras} = createCapturingDeps(user);
-
- setWorkerDependenciesForTest({
- premiumStateReconciliationQueueService: queueService,
- stripe: createStripeStub(createActiveSubscription(periodEndMs), []),
- userRepository,
- ...extras,
- });
-
- await processPremiumStateReconciliationQueue({}, createTestWorkerHelpers());
-
- expect(patches).toHaveLength(1);
- expect(patches[0].premium_flags).toBe(0);
- });
});
diff --git a/fluxer_api/src/api/worker/tests/SeedThreadPermissions.test.ts b/fluxer_api/src/api/worker/tests/SeedThreadPermissions.test.ts
index 3d0c24733..ade232a9d 100644
--- a/fluxer_api/src/api/worker/tests/SeedThreadPermissions.test.ts
+++ b/fluxer_api/src/api/worker/tests/SeedThreadPermissions.test.ts
@@ -8,28 +8,23 @@ import {fetchOne, upsertOne} from '@app/api/database/CassandraQueryExecution';
import type {GuildThreadStateRow} from '@app/api/database/types/ThreadTypes';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
import {addMemberRole, createGuild, createRole} from '@app/api/guild/tests/GuildTestUtils';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import {
- getChannelRepository,
- getGuildRepository,
- getInstanceConfigRepository,
- getUserCacheService,
-} from '@app/api/middleware/ServiceSingletons';
+import {getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
+import {getChannelRepository, getGuildRepository} from '@app/api/middleware/ServiceSingletons';
import {GuildThreadState} from '@app/api/Tables';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import seedThreadPermissions from '@app/api/worker/tasks/SeedThreadPermissions';
-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
+import {clearWorkerDependencies, setWorkerDependencies} from '@app/api/worker/WorkerContext';
+import {initializeWorkerDependencies} from '@app/api/worker/WorkerDependencies';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {ChannelTypes, DEFAULT_PERMISSIONS, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {DEFAULT_THREAD_PERMISSIONS, ThreadPermissionFlags} from '@fluxer/constants/src/ThreadPermissionUtils';
import type {ChannelResponse} from '@fluxer/schema/src/domains/channel/ChannelSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('seedThreadPermissions', () => {
let harness: ApiTestHarness;
- let dispatchGuild: ReturnType<typeof vi.fn>;
beforeAll(async () => {
harness = await createApiTestHarness();
@@ -38,14 +33,7 @@ describe('seedThreadPermissions', () => {
beforeEach(async () => {
await harness.reset();
clearChannelThreadsTaintCacheForTesting();
- dispatchGuild = vi.fn(async () => {});
- setWorkerDependenciesForTest({
- channelRepository: getChannelRepository(),
- guildRepository: getGuildRepository(),
- userCacheService: getUserCacheService(),
- instanceConfigRepository: getInstanceConfigRepository(),
- gatewayService: {dispatchGuild} as unknown as IGatewayService,
- });
+ setWorkerDependencies(await initializeWorkerDependencies(getSnowflakeService()));
});
afterEach(() => {
@@ -99,10 +87,6 @@ describe('seedThreadPermissions', () => {
))!.permissionOverwrites.get(createRoleID(BigInt(guild.id)));
expect(seeded?.allow).toBe(0n);
expect(seeded?.deny).toBe(Permissions.SEND_MESSAGES | DEFAULT_THREAD_PERMISSIONS);
- expect(dispatchGuild.mock.calls.map(([params]) => params.event)).toEqual([
- 'GUILD_ROLE_UPDATE_BULK',
- 'CHANNEL_UPDATE_BULK',
- ]);
const marker = await fetchOne<GuildThreadStateRow>(
GuildThreadState.selectCql({where: GuildThreadState.where.eq('guild_id'), limit: 1}),
{guild_id: guildId},
@@ -111,7 +95,6 @@ describe('seedThreadPermissions', () => {
await getGuildRepository().upsertRole({...everyone!.toRow(), permissions: DEFAULT_PERMISSIONS});
await seedThreadPermissions({guildId: guild.id}, createTestWorkerHelpers());
- expect(dispatchGuild).toHaveBeenCalledTimes(2);
expect((await getGuildRepository().getRole(createRoleID(BigInt(guild.id)), guildId))?.permissions).toBe(
DEFAULT_PERMISSIONS,
);
diff --git a/fluxer_api/src/api/worker/tests/SendSystemDmCancel.test.ts b/fluxer_api/src/api/worker/tests/SendSystemDmCancel.test.ts
deleted file mode 100644
index 874c43b92..000000000
--- a/fluxer_api/src/api/worker/tests/SendSystemDmCancel.test.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {ChannelService} from '@app/api/channel/services/ChannelService';
-import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {sendSystemDm} from '@app/api/worker/tasks/SendSystemDm';
-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
-import {WorkerRunner} from '@app/api/worker/WorkerRunner';
-import {UserFlags} from '@fluxer/constants/src/UserConstants';
-import type {JsMsg} from '@nats-io/jetstream';
-import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
-
-const TASK_TYPE = 'sendSystemDm';
-const LEDGER_JOB_ID = 88n;
-
-const queueStub = {
- getConnectionManager: () => {
- throw new Error('WorkerRunner tests never consume messages');
- },
- getStreamName: () => 'JOBS',
- publishToDlq: vi.fn(),
-};
-
-class TestWorkerRunner extends WorkerRunner {
- async runJob(taskType: string, msg: JsMsg): Promise<boolean> {
- return await this.processJob(taskType, msg);
- }
-}
-
-function createLedgerStub(cancelAfter: number) {
- const cancelChecks = {count: 0};
- const markCancelled = vi.fn(async () => {});
- const markSucceeded = vi.fn(async () => {});
- const ledger = {
- markRunning: async () => {},
- markSucceeded,
- markCancelled,
- markDeadletter: async () => {},
- reportProgress: async () => {},
- setContextLink: async () => {},
- isCancelRequested: async () => {
- cancelChecks.count += 1;
- return cancelChecks.count > cancelAfter;
- },
- } as unknown as JobLedgerRepository;
- return {ledger, markCancelled, markSucceeded};
-}
-
-function createWorkerDependencies() {
- const sentChannelIds: Array<bigint> = [];
- const sentUserIds: Array<bigint> = [];
- const systemUser = {id: 0n, username: 'Fluxer', bot: true, system: true};
- const userRepository = {
- findUnique: async () => systemUser,
- findUniqueAssert: async () => systemUser,
- findExistingDmState: async () => ({id: 500n}),
- isDmChannelOpen: async () => true,
- } as unknown as UserRepository;
- const channelService = {
- messages: {
- send: {
- sendMessage: async ({channelId, user}: {channelId: bigint; user: {id: bigint}}) => {
- sentChannelIds.push(channelId);
- sentUserIds.push(user.id);
- },
- },
- },
- } as unknown as ChannelService;
- setWorkerDependenciesForTest({userRepository, channelService});
- return {sentChannelIds, sentUserIds};
-}
-
-function createJobMessage(recipients: Record<string, unknown> = {user_ids: ['11', '12', '13']}) {
- const envelope = {
- payload: {
- content: 'scheduled maintenance tonight',
- ...recipients,
- __jobId: LEDGER_JOB_ID.toString(),
- },
- max_attempts: 5,
- priority: 0,
- created_at: new Date().toISOString(),
- };
- return {
- seq: 1,
- subject: `jobs.${TASK_TYPE}`,
- redelivered: false,
- data: new TextEncoder().encode(JSON.stringify(envelope)),
- info: {deliveryCount: 1},
- ack: vi.fn(),
- nak: vi.fn(),
- term: vi.fn(),
- working: vi.fn(),
- };
-}
-
-describe('System DM cancellation', () => {
- beforeAll(() => {
- setInjectedWorkerService(new NoopWorkerService());
- });
-
- afterEach(() => {
- clearWorkerDependencies();
- queueStub.publishToDlq.mockClear();
- });
-
- it('settles the ledger row as cancelled after stopping mid-broadcast', async () => {
- const deps = createWorkerDependencies();
- const {ledger, markCancelled, markSucceeded} = createLedgerStub(1);
- const runner = new TestWorkerRunner({
- tasks: {[TASK_TYPE]: sendSystemDm},
- queue: queueStub,
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger,
- concurrency: 1,
- });
- const msg = createJobMessage();
-
- await expect(runner.runJob(TASK_TYPE, msg as unknown as JsMsg)).resolves.toBe(false);
-
- expect(deps.sentChannelIds).toHaveLength(1);
- expect(markCancelled).toHaveBeenCalledWith(LEDGER_JOB_ID);
- expect(markSucceeded).not.toHaveBeenCalled();
- expect(msg.ack).toHaveBeenCalledTimes(1);
- expect(msg.nak).not.toHaveBeenCalled();
- });
-
- it('sends every message as the synthetic system account', async () => {
- const deps = createWorkerDependencies();
- const {ledger} = createLedgerStub(Number.POSITIVE_INFINITY);
- const runner = new TestWorkerRunner({
- tasks: {[TASK_TYPE]: sendSystemDm},
- queue: queueStub,
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger,
- concurrency: 1,
- });
- const msg = createJobMessage();
-
- await expect(runner.runJob(TASK_TYPE, msg as unknown as JsMsg)).resolves.toBe(true);
-
- expect(deps.sentUserIds).toEqual([0n, 0n, 0n]);
- });
-
- it('broadcasts to every eligible user when all_users is set', async () => {
- const user = (id: bigint, extra: Record<string, unknown> = {}) => ({
- id,
- isBot: false,
- isSystem: false,
- flags: 0n,
- ...extra,
- });
- const pages = [
- {users: [user(0n, {isSystem: true}), user(21n), user(22n, {isBot: true})], pageState: 'page-2'},
- {
- users: [user(23n, {flags: UserFlags.DELETED}), user(24n), user(25n, {flags: UserFlags.DISABLED})],
- pageState: null,
- },
- ];
- const kv = new Map<string, string>();
- const kvClient = {
- get: async (key: string) => kv.get(key) ?? null,
- setex: async (key: string, _ttl: number, value: string) => {
- kv.set(key, value);
- },
- del: async (key: string) => (kv.delete(key) ? 1 : 0),
- };
- const recipientIds: Array<bigint> = [];
- const systemUser = {id: 0n, username: 'Fluxer', bot: true, system: true};
- const userRepository = {
- findUnique: async () => systemUser,
- findUniqueAssert: async () => systemUser,
- findExistingDmState: async (_userId: bigint, recipientId: bigint) => {
- recipientIds.push(recipientId);
- return {id: 500n};
- },
- isDmChannelOpen: async () => true,
- scanAllUsersPage: async (_limit: number, pageState: string | null) =>
- pageState === 'page-2' ? pages[1] : pages[0],
- } as unknown as UserRepository;
- const channelService = {
- messages: {send: {sendMessage: async () => {}}},
- } as unknown as ChannelService;
- setWorkerDependenciesForTest({userRepository, channelService, kvClient} as never);
- const {ledger, markSucceeded} = createLedgerStub(Number.POSITIVE_INFINITY);
- const runner = new TestWorkerRunner({
- tasks: {[TASK_TYPE]: sendSystemDm},
- queue: queueStub,
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger,
- concurrency: 1,
- });
-
- await expect(runner.runJob(TASK_TYPE, createJobMessage({all_users: true}) as unknown as JsMsg)).resolves.toBe(true);
-
- expect(recipientIds).toEqual([21n, 24n]);
- expect(markSucceeded).toHaveBeenCalledWith(LEDGER_JOB_ID, {sent_count: 2, failed_count: 0});
- expect(kv.size).toBe(0);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/ThreadMaintenanceTasks.test.ts b/fluxer_api/src/api/worker/tests/ThreadMaintenanceTasks.test.ts
index ebff64043..0b12b785f 100644
--- a/fluxer_api/src/api/worker/tests/ThreadMaintenanceTasks.test.ts
+++ b/fluxer_api/src/api/worker/tests/ThreadMaintenanceTasks.test.ts
@@ -5,15 +5,13 @@ import {createChannelID, createGuildID, createUserID} from '@app/api/BrandedType
import {acceptInvite, createChannel, createChannelInvite, createGuild} from '@app/api/channel/tests/ChannelTestUtils';
import {threadsRequest} from '@app/api/channel/tests/ThreadTestUtils';
import {clearChannelThreadsTaintCacheForTesting} from '@app/api/experiment/ChannelThreadsGate';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import {threadArchiveQueueKey} from '@app/api/infrastructure/KVThreadAutoArchiveQueueService';
-import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
-import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import {
- getChannelRepository,
- getGuildRepository,
- getInstanceConfigRepository,
-} from '@app/api/middleware/ServiceSingletons';
+ KVThreadAutoArchiveQueueService,
+ threadArchiveQueueKey,
+} from '@app/api/infrastructure/KVThreadAutoArchiveQueueService';
+import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
+import {getKVClient, getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
+import {getChannelRepository, getGuildRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
import {
@@ -21,18 +19,17 @@ import {
deleteChannelThreads,
removeThreadMembershipsForGuildMember,
} from '@app/api/worker/tasks/ThreadMaintenanceTasks';
-import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
-import type {WorkerDependencies} from '@app/api/worker/WorkerDependencies';
+import {clearWorkerDependencies, setWorkerDependencies} from '@app/api/worker/WorkerContext';
+import {initializeWorkerDependencies} from '@app/api/worker/WorkerDependencies';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import {ChannelFlags, DEFAULT_THREAD_AUTO_ARCHIVE_DURATION} from '@fluxer/constants/src/ThreadConstants';
import type {ThreadChannelResponse} from '@fluxer/schema/src/domains/channel/ThreadRequestSchemas';
-import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
const PAST_ARCHIVE_WINDOW_MS = (DEFAULT_THREAD_AUTO_ARCHIVE_DURATION + 1) * 60_000;
describe('thread maintenance tasks', () => {
let harness: ApiTestHarness;
- let dispatchGuild: ReturnType<typeof vi.fn>;
beforeAll(async () => {
harness = await createApiTestHarness();
@@ -41,21 +38,7 @@ describe('thread maintenance tasks', () => {
beforeEach(async () => {
await harness.reset();
clearChannelThreadsTaintCacheForTesting();
- dispatchGuild = vi.fn(async () => {});
- setWorkerDependenciesForTest({
- kvClient: getKVClient(),
- channelRepository: getChannelRepository(),
- guildRepository: getGuildRepository(),
- instanceConfigRepository: getInstanceConfigRepository(),
- gatewayService: {dispatchGuild, dispatchGuildMany: vi.fn(async () => {})} as unknown as IGatewayService,
- channelService: {
- attachments: {purgeChannelAttachments: vi.fn(async () => {})},
- } as unknown as WorkerDependencies['channelService'],
- });
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
+ setWorkerDependencies(await initializeWorkerDependencies(getSnowflakeService()));
});
afterAll(async () => {
@@ -94,13 +77,14 @@ describe('thread maintenance tasks', () => {
await getChannelRepository().threads.updateState(createChannelID(BigInt(fresh.id)), () => ({
flags: ChannelFlags.PINNED,
}));
- const now = Date.now();
- vi.spyOn(Date, 'now').mockReturnValue(now + PAST_ARCHIVE_WINDOW_MS);
+ const backdated = await getChannelRepository().threads.updateState(createChannelID(BigInt(thread.id)), () => ({
+ archive_timestamp: new Date(Date.now() - PAST_ARCHIVE_WINDOW_MS),
+ }));
+ await new KVThreadAutoArchiveQueueService(getKVClient()).schedule(backdated!.state, null);
await archiveInactiveThreads({}, createTestWorkerHelpers());
expect((await state(thread.id))?.archived).toBe(true);
expect((await state(fresh.id))?.archived).toBe(false);
- expect(dispatchGuild.mock.calls.some(([params]) => params.event === 'THREAD_UPDATE')).toBe(true);
const queued = await getKVClient().zrangebyscore(
threadArchiveQueueKey(createGuildID(BigInt(s.guildId))),
'-inf',
diff --git a/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts b/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts
index f9080a948..8be598c75 100644
--- a/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts
+++ b/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts
@@ -3,102 +3,101 @@
import {createUserID, type UserID} from '@app/api/BrandedTypes';
import {EMPTY_USER_ROW, type UserRow} from '@app/api/database/types/UserTypes';
import {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
-import {User} from '@app/api/models/User';
+import {getKVClient} from '@app/api/middleware/ServiceRegistry';
+import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {RecordingWorkerService} from '@app/api/test/RecordingWorkerService';
import {createTestWorkerHelpers} from '@app/api/test/SyncTaskWorkerService';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import userProcessPendingDeletions from '@app/api/worker/tasks/UserProcessPendingDeletions';
import {clearWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
-import {MockKVProvider} from '@pkgs/kv_client/src/testing/MockKVProvider';
-import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';
-import {afterEach, describe, expect, test} from 'vitest';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';
-function createFakeUser(
- userId: UserID,
- pendingDeletionAt: Date,
- options: Partial<Pick<UserRow, 'bot' | 'flags'>> = {},
-): User {
- return new User({
- ...EMPTY_USER_ROW,
- user_id: userId,
- pending_deletion_at: pendingDeletionAt,
- deletion_reason_code: 1,
- bot: options.bot ?? false,
- flags: options.flags ?? 0n,
- });
+interface PendingUser {
+ userId: UserID;
+ pendingDeletionAt: Date;
+ bot?: boolean;
+ flags?: bigint;
}
-async function createHarness(users: Array<User>) {
- const kvClient = new MockKVProvider();
-
- const scheduledJobs: Array<string> = [];
- const usersById = new Map<string, User>();
- for (const user of users) {
- usersById.set(user.id.toString(), user);
- }
- const userRepository = {
- async findUnique(userId: UserID): Promise<User | null> {
- return usersById.get(userId.toString()) ?? null;
- },
- } as unknown as UserRepository;
- const workerService = {
- async addJob(name: string, payload: {userId: string; pendingDeletionAt: string}): Promise<bigint> {
- scheduledJobs.push(`${name}:${payload.userId}:${payload.pendingDeletionAt}`);
- return 0n;
- },
- } as unknown as IWorkerService;
- const deletionQueueService = new KVAccountDeletionQueueService(kvClient, userRepository);
- await kvClient.set('deletion_queue:state_version', Date.now().toString());
+async function setupQueue(users: Array<PendingUser>) {
+ const userRepository = getUserRepository();
+ const workerService = new RecordingWorkerService();
+ const deletionQueueService = new KVAccountDeletionQueueService(getKVClient(), userRepository);
+ await getKVClient().set('deletion_queue:state_version', Date.now().toString());
for (const user of users) {
- if (user.pendingDeletionAt) {
- await deletionQueueService.scheduleDeletion(user.id, user.pendingDeletionAt, 1);
- }
+ const row: UserRow = {...EMPTY_USER_ROW, user_id: user.userId, bot: user.bot ?? false, flags: user.flags ?? 0n};
+ const created = await userRepository.create(row);
+ await userRepository.updateDeletionSchedule(created, {
+ pending_deletion_at: user.pendingDeletionAt,
+ deletion_reason_code: 1,
+ });
+ await deletionQueueService.scheduleDeletion(user.userId, user.pendingDeletionAt, 1);
}
setWorkerDependenciesForTest({userRepository, workerService, deletionQueueService});
- return {deletionQueueService, scheduledJobs};
+ return {deletionQueueService, workerService};
+}
+
+function scheduledDeletions(workerService: RecordingWorkerService): Array<string> {
+ return workerService
+ .byTask('userProcessPendingDeletion')
+ .map((job) => `${job.payload['userId']}:${job.payload['pendingDeletionAt']}`);
}
describe('userProcessPendingDeletions', () => {
+ let harness: ApiTestHarness;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ });
+
afterEach(() => {
clearWorkerDependencies();
});
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+
test('drains skipped accounts so a genuine deletion behind them is not starved', async () => {
const skippedAt = new Date(Date.now() - 10_000_000);
const genuineAt = new Date(Date.now() - 1_000);
- const users: Array<User> = [];
+ const users: Array<PendingUser> = [];
for (let i = 0; i < 1000; i++) {
const userId = createUserID(BigInt(100_000 + i));
- users.push(createFakeUser(userId, skippedAt, i % 2 === 0 ? {bot: true} : {flags: UserFlags.APP_STORE_REVIEWER}));
+ users.push(
+ i % 2 === 0
+ ? {userId, pendingDeletionAt: skippedAt, bot: true}
+ : {userId, pendingDeletionAt: skippedAt, flags: UserFlags.APP_STORE_REVIEWER},
+ );
}
const genuineUserId = createUserID(999_999n);
- users.push(createFakeUser(genuineUserId, genuineAt));
- const harness = await createHarness(users);
+ users.push({userId: genuineUserId, pendingDeletionAt: genuineAt});
+ const {deletionQueueService, workerService} = await setupQueue(users);
await userProcessPendingDeletions({}, createTestWorkerHelpers());
- const queueSizeAfterFirstPass = await harness.deletionQueueService.getQueueSize();
+ const queueSizeAfterFirstPass = await deletionQueueService.getQueueSize();
await userProcessPendingDeletions({}, createTestWorkerHelpers());
- expect(harness.scheduledJobs).toEqual([
- `userProcessPendingDeletion:${genuineUserId.toString()}:${genuineAt.toISOString()}`,
- ]);
-
+ expect(scheduledDeletions(workerService)).toEqual([`${genuineUserId.toString()}:${genuineAt.toISOString()}`]);
expect(queueSizeAfterFirstPass).toBe(1);
- expect(await harness.deletionQueueService.getQueueSize()).toBe(0);
+ expect(await deletionQueueService.getQueueSize()).toBe(0);
});
test('keeps skipped accounts out of the queue while the skip condition holds', async () => {
const pendingAt = new Date(Date.now() - 10_000);
- const botId = createUserID(1n);
- const reviewerId = createUserID(2n);
- const harness = await createHarness([
- createFakeUser(botId, pendingAt, {bot: true}),
- createFakeUser(reviewerId, pendingAt, {flags: UserFlags.APP_STORE_REVIEWER}),
+ const {deletionQueueService, workerService} = await setupQueue([
+ {userId: createUserID(500_001n), pendingDeletionAt: pendingAt, bot: true},
+ {userId: createUserID(500_002n), pendingDeletionAt: pendingAt, flags: UserFlags.APP_STORE_REVIEWER},
]);
await userProcessPendingDeletions({}, createTestWorkerHelpers());
- expect(await harness.deletionQueueService.getQueueSize()).toBe(0);
- expect(harness.scheduledJobs).toEqual([]);
+ expect(await deletionQueueService.getQueueSize()).toBe(0);
+ expect(scheduledDeletions(workerService)).toEqual([]);
});
});
diff --git a/fluxer_api/src/api/worker/tests/WorkerAckHeartbeat.test.ts b/fluxer_api/src/api/worker/tests/WorkerAckHeartbeat.test.ts
deleted file mode 100644
index 7a38bbdab..000000000
--- a/fluxer_api/src/api/worker/tests/WorkerAckHeartbeat.test.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {WorkerRunner} from '@app/api/worker/WorkerRunner';
-import type {JsMsg} from '@nats-io/jetstream';
-import {JobCancelledError} from '@pkgs/worker/src/contracts/WorkerTask';
-import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
-
-const LANE_ACK_WAIT_MS = 120000;
-const LANE_MAX_DELIVER = 25;
-const TASK_TYPE = 'processInactivityDeletions';
-
-const queueStub = {
- getConnectionManager: () => {
- throw new Error('WorkerRunner tests never consume messages');
- },
- getStreamName: () => 'JOBS',
- publishToDlq: vi.fn(),
-};
-
-class TestWorkerRunner extends WorkerRunner {
- async runJob(taskType: string, msg: JsMsg): Promise<boolean> {
- return await this.processJob(taskType, msg);
- }
-}
-
-function createRunner(task: () => Promise<void>): TestWorkerRunner {
- return new TestWorkerRunner({
- tasks: {[TASK_TYPE]: task},
- queue: queueStub,
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger: {} as JobLedgerRepository,
- concurrency: 12,
- maxDeliver: LANE_MAX_DELIVER,
- ackWaitMs: LANE_ACK_WAIT_MS,
- });
-}
-
-function createJobMessage() {
- const envelope = {
- payload: {},
- max_attempts: 5,
- priority: 0,
- created_at: new Date().toISOString(),
- };
- return {
- seq: 1,
- subject: `jobs.${TASK_TYPE}`,
- redelivered: false,
- data: new TextEncoder().encode(JSON.stringify(envelope)),
- info: {deliveryCount: 1},
- ack: vi.fn(),
- nak: vi.fn(),
- term: vi.fn(),
- working: vi.fn(),
- };
-}
-
-function createDeferredTask(): {task: () => Promise<void>; settle: (error?: Error) => void} {
- let settle: (error?: Error) => void = () => {};
- const pending = new Promise<void>((resolve, reject) => {
- settle = (error?: Error) => {
- if (error) {
- reject(error);
- } else {
- resolve();
- }
- };
- });
- return {task: () => pending, settle: (error?: Error) => settle(error)};
-}
-
-describe('Worker ack heartbeat', () => {
- beforeAll(() => {
- setInjectedWorkerService(new NoopWorkerService());
- });
-
- afterEach(() => {
- vi.useRealTimers();
- queueStub.publishToDlq.mockClear();
- });
-
- it('holds the ack for a task running past the lane ack wait', async () => {
- vi.useFakeTimers();
- const {task, settle} = createDeferredTask();
- const runner = createRunner(task);
- const msg = createJobMessage();
-
- const job = runner.runJob(TASK_TYPE, msg as unknown as JsMsg);
- await vi.advanceTimersByTimeAsync(LANE_ACK_WAIT_MS * 3);
-
- expect(msg.working.mock.calls.length).toBeGreaterThanOrEqual(1);
- expect(msg.ack).not.toHaveBeenCalled();
- expect(msg.nak).not.toHaveBeenCalled();
-
- settle();
- await expect(job).resolves.toBe(true);
-
- expect(msg.ack).toHaveBeenCalledTimes(1);
- const heartbeatsAtCompletion = msg.working.mock.calls.length;
- await vi.advanceTimersByTimeAsync(LANE_ACK_WAIT_MS * 3);
- expect(msg.working.mock.calls.length).toBe(heartbeatsAtCompletion);
- });
-
- it('stops the heartbeat when the task throws', async () => {
- vi.useFakeTimers();
- const {task, settle} = createDeferredTask();
- const runner = createRunner(task);
- const msg = createJobMessage();
-
- const job = runner.runJob(TASK_TYPE, msg as unknown as JsMsg);
- await vi.advanceTimersByTimeAsync(LANE_ACK_WAIT_MS);
- expect(msg.working.mock.calls.length).toBeGreaterThanOrEqual(1);
-
- settle(new Error('scan failed'));
- await expect(job).resolves.toBe(false);
-
- expect(msg.nak).toHaveBeenCalledTimes(1);
- const heartbeatsAtCompletion = msg.working.mock.calls.length;
- await vi.advanceTimersByTimeAsync(LANE_ACK_WAIT_MS * 3);
- expect(msg.working.mock.calls.length).toBe(heartbeatsAtCompletion);
- });
-
- it('stops the heartbeat when the task is cancelled', async () => {
- vi.useFakeTimers();
- const {task, settle} = createDeferredTask();
- const runner = createRunner(task);
- const msg = createJobMessage();
-
- const job = runner.runJob(TASK_TYPE, msg as unknown as JsMsg);
- await vi.advanceTimersByTimeAsync(LANE_ACK_WAIT_MS);
- expect(msg.working.mock.calls.length).toBeGreaterThanOrEqual(1);
-
- settle(new JobCancelledError('cancelled by admin'));
- await expect(job).resolves.toBe(false);
-
- expect(msg.ack).toHaveBeenCalledTimes(1);
- const heartbeatsAtCompletion = msg.working.mock.calls.length;
- await vi.advanceTimersByTimeAsync(LANE_ACK_WAIT_MS * 3);
- expect(msg.working.mock.calls.length).toBe(heartbeatsAtCompletion);
- });
-
- it('does not heartbeat a job deferred to the future', async () => {
- const runner = new TestWorkerRunner({
- tasks: {[TASK_TYPE]: async () => {}},
- queue: queueStub,
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger: {} as JobLedgerRepository,
- concurrency: 12,
- maxDeliver: LANE_MAX_DELIVER,
- ackWaitMs: LANE_ACK_WAIT_MS,
- });
- const runAt = new Date(Date.now() + 60 * 60 * 1000);
- const envelope = {
- payload: {},
- run_at: runAt.toISOString(),
- max_attempts: 5,
- priority: 0,
- created_at: new Date().toISOString(),
- };
- const msg = {
- ...createJobMessage(),
- data: new TextEncoder().encode(JSON.stringify(envelope)),
- };
-
- await runner.runJob(TASK_TYPE, msg as unknown as JsMsg);
-
- expect(msg.ack).not.toHaveBeenCalled();
- expect(msg.nak).toHaveBeenCalledTimes(1);
- expect(msg.working).not.toHaveBeenCalled();
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.ts b/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.ts
deleted file mode 100644
index 9d0d01687..000000000
--- a/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {CronScheduler} from '@app/api/worker/CronScheduler';
-import {
- WORKER_CRON_STALE_AFTER_MS,
- WORKER_HEARTBEAT_WRITE_INTERVAL_MS,
- WORKER_LANE_STALE_AFTER_MS,
- WorkerHeartbeat,
-} from '@app/api/worker/WorkerHeartbeat';
-import {WorkerRunner} from '@app/api/worker/WorkerRunner';
-import type {WorkerService} from '@app/api/worker/WorkerService';
-import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';
-import type {ConsumerMessages, JsMsg} from '@nats-io/jetstream';
-import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
-import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
-
-const HEARTBEAT_PATH = '/tmp/fluxer-worker-heartbeat-test';
-const TASK_TYPE = 'processInactivityDeletions';
-
-function createHeartbeat(): {
- heartbeat: WorkerHeartbeat;
- write: ReturnType<typeof vi.fn>;
- logger: {info: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn>};
-} {
- const logger = {info: vi.fn(), error: vi.fn()};
- const write = vi.fn();
- const heartbeat = new WorkerHeartbeat({logger, path: HEARTBEAT_PATH, write});
- return {heartbeat, write, logger};
-}
-
-class FakeConsumerMessages {
- private notify: (() => void) | null = null;
- private closed = false;
-
- async close(): Promise<void> {
- this.stop();
- }
-
- stop(): void {
- this.closed = true;
- const notify = this.notify;
- this.notify = null;
- notify?.();
- }
-
- async *[Symbol.asyncIterator](): AsyncGenerator<JsMsg> {
- while (!this.closed) {
- await new Promise<void>((resolve) => {
- this.notify = resolve;
- });
- }
- }
-}
-
-function createRunner(messages: FakeConsumerMessages, heartbeat: WorkerHeartbeat): WorkerRunner {
- return new WorkerRunner({
- tasks: {[TASK_TYPE]: async () => {}},
- queue: {
- getConnectionManager: () => ({
- getJetStreamClient: () => ({
- consumers: {
- get: async () => ({
- fetch: async () => messages as unknown as ConsumerMessages,
- }),
- },
- }),
- }),
- getStreamName: () => 'JOBS',
- publishToDlq: vi.fn(),
- },
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger: {} as JobLedgerRepository,
- concurrency: 12,
- maxDeliver: 25,
- ackWaitMs: 120000,
- heartbeat,
- });
-}
-
-function createCronLogger(): LoggerInterface {
- const logger = {
- trace: vi.fn(),
- debug: vi.fn(),
- info: vi.fn(),
- warn: vi.fn(),
- error: vi.fn(),
- child: () => logger,
- };
- return logger as unknown as LoggerInterface;
-}
-
-function createScheduler(heartbeat: WorkerHeartbeat): CronScheduler {
- const workerService = {addJob: vi.fn().mockResolvedValue(1n)} as unknown as WorkerService;
- const kvClient = {setnx: vi.fn().mockResolvedValue(true)} as unknown as IKVProvider;
- return new CronScheduler(workerService, createCronLogger(), kvClient, heartbeat);
-}
-
-describe('Worker heartbeat', () => {
- beforeAll(() => {
- setInjectedWorkerService(new NoopWorkerService());
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('keeps rewriting the file while every component reports', async () => {
- vi.useFakeTimers();
- const {heartbeat, write} = createHeartbeat();
- const lane = heartbeat.register('lane:realtime', WORKER_LANE_STALE_AFTER_MS);
-
- heartbeat.start();
- expect(write).toHaveBeenCalledTimes(1);
- write.mockClear();
- for (let elapsed = 0; elapsed < WORKER_LANE_STALE_AFTER_MS * 3; elapsed += WORKER_HEARTBEAT_WRITE_INTERVAL_MS) {
- lane.report();
- await vi.advanceTimersByTimeAsync(WORKER_HEARTBEAT_WRITE_INTERVAL_MS);
- }
- heartbeat.stop();
-
- expect(write).toHaveBeenCalledTimes((WORKER_LANE_STALE_AFTER_MS * 3) / WORKER_HEARTBEAT_WRITE_INTERVAL_MS);
- expect(write.mock.calls[0]?.[0]).toBe(HEARTBEAT_PATH);
- expect(heartbeat.stalledComponents()).toEqual([]);
- });
-
- it('stops rewriting the file once a component goes stale', async () => {
- vi.useFakeTimers();
- const {heartbeat, write, logger} = createHeartbeat();
- heartbeat.register('lane:realtime', WORKER_LANE_STALE_AFTER_MS);
-
- heartbeat.start();
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS);
- const writesBeforeStall = write.mock.calls.length;
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS * 3);
- heartbeat.stop();
-
- expect(write).toHaveBeenCalledTimes(writesBeforeStall);
- expect(heartbeat.stalledComponents()).toEqual(['lane:realtime']);
- expect(logger.error).toHaveBeenCalledTimes(1);
- expect(logger.error.mock.calls[0]?.[1]).toBe('Worker heartbeat stalled, the container will report unhealthy');
- });
-
- it('resumes rewriting the file when a stalled component reports again', async () => {
- vi.useFakeTimers();
- const {heartbeat, write, logger} = createHeartbeat();
- const lane = heartbeat.register('lane:realtime', WORKER_LANE_STALE_AFTER_MS);
-
- heartbeat.start();
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS * 3);
- const writesBeforeRecovery = write.mock.calls.length;
- lane.report();
- await vi.advanceTimersByTimeAsync(WORKER_HEARTBEAT_WRITE_INTERVAL_MS);
- heartbeat.stop();
-
- expect(write).toHaveBeenCalledTimes(writesBeforeRecovery + 1);
- expect(heartbeat.stalledComponents()).toEqual([]);
- expect(logger.info).toHaveBeenCalledWith({path: HEARTBEAT_PATH}, 'Worker heartbeat recovered');
- });
-
- it('ignores a released component', async () => {
- vi.useFakeTimers();
- const {heartbeat, write} = createHeartbeat();
- const lane = heartbeat.register('lane:realtime', WORKER_LANE_STALE_AFTER_MS);
-
- heartbeat.start();
- lane.release();
- write.mockClear();
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS * 3);
- heartbeat.stop();
-
- expect(write).toHaveBeenCalledTimes((WORKER_LANE_STALE_AFTER_MS * 3) / WORKER_HEARTBEAT_WRITE_INTERVAL_MS);
- expect(heartbeat.stalledComponents()).toEqual([]);
- });
-
- it('reports a lane for as long as the runner is running and releases it on stop', async () => {
- vi.useFakeTimers();
- const {heartbeat, write} = createHeartbeat();
- const messages = new FakeConsumerMessages();
- const runner = createRunner(messages, heartbeat);
-
- heartbeat.start();
- await runner.start();
- write.mockClear();
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS * 3);
-
- expect(heartbeat.stalledComponents()).toEqual([]);
- expect(write).toHaveBeenCalledTimes((WORKER_LANE_STALE_AFTER_MS * 3) / WORKER_HEARTBEAT_WRITE_INTERVAL_MS);
-
- await runner.stop();
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS * 3);
- heartbeat.stop();
-
- expect(heartbeat.stalledComponents()).toEqual([]);
- });
-
- it('stalls when a running lane stops ticking, which is what a frozen worker looks like', async () => {
- vi.useFakeTimers();
- const {heartbeat, write} = createHeartbeat();
- const messages = new FakeConsumerMessages();
- const runner = createRunner(messages, heartbeat);
-
- heartbeat.start();
- await runner.start();
- vi.clearAllTimers();
- write.mockClear();
- await vi.advanceTimersByTimeAsync(WORKER_LANE_STALE_AFTER_MS * 3);
-
- expect(write).not.toHaveBeenCalled();
- expect(heartbeat.stalledComponents()).toEqual(['lane:batch']);
- expect(heartbeat.writeOnce()).toBe(false);
-
- await runner.stop();
- heartbeat.stop();
- });
-
- it('reports the cron scheduler on every tick and releases it on stop', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
- const {heartbeat} = createHeartbeat();
- const scheduler = createScheduler(heartbeat);
- scheduler.upsert('flushUserActivityBuffer', 'flushUserActivityBuffer', {}, '*/10 * * * * *', {ledger: false});
-
- scheduler.start();
- await vi.advanceTimersByTimeAsync(WORKER_CRON_STALE_AFTER_MS * 2);
- expect(heartbeat.stalledComponents()).toEqual([]);
-
- scheduler.stop();
- await vi.advanceTimersByTimeAsync(WORKER_CRON_STALE_AFTER_MS * 2);
- expect(heartbeat.stalledComponents()).toEqual([]);
- });
-
- it('stalls when the cron scheduler stops ticking while it is still registered', async () => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
- const {heartbeat} = createHeartbeat();
- const scheduler = createScheduler(heartbeat);
- scheduler.upsert('flushUserActivityBuffer', 'flushUserActivityBuffer', {}, '*/10 * * * * *', {ledger: false});
-
- scheduler.start();
- await vi.advanceTimersByTimeAsync(1000);
- vi.clearAllTimers();
- await vi.advanceTimersByTimeAsync(WORKER_CRON_STALE_AFTER_MS * 2);
-
- expect(heartbeat.stalledComponents()).toEqual(['cron']);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/WorkerProcessErrorHandler.test.ts b/fluxer_api/src/api/worker/tests/WorkerProcessErrorHandler.test.ts
index 3d4701856..e95c8b049 100644
--- a/fluxer_api/src/api/worker/tests/WorkerProcessErrorHandler.test.ts
+++ b/fluxer_api/src/api/worker/tests/WorkerProcessErrorHandler.test.ts
@@ -1,22 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {NoopLogger} from '@app/api/test/mocks/NoopLogger';
import {
createWorkerProcessErrorHandler,
type WorkerProcessErrorSource,
} from '@app/api/worker/WorkerProcessErrorHandler';
-import {describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
-function createHarness(overrides: {shutdown?: () => Promise<void>; forceExitDelayMs?: number} = {}) {
- const logger = {error: vi.fn(), warn: vi.fn()};
- const exit = vi.fn();
- const shutdown = vi.fn(overrides.shutdown ?? (async () => {}));
+function createHarness(shutdown: () => Promise<void> = async () => {}) {
+ const exitCodes: Array<number> = [];
+ const calls = {shutdown: 0};
const handle = createWorkerProcessErrorHandler({
- logger,
- shutdown,
- exit,
- forceExitDelayMs: overrides.forceExitDelayMs ?? 5,
+ logger: new NoopLogger(),
+ shutdown: async () => {
+ calls.shutdown += 1;
+ await shutdown();
+ },
+ exit: (code) => {
+ exitCodes.push(code);
+ },
});
- return {logger, exit, shutdown, handle};
+ return {exitCodes, calls, handle};
}
function pooledClientError(fields: Record<string, unknown>): Error {
@@ -37,141 +41,78 @@ function adminShutdownError(): Error {
}
describe('Worker process error handler', () => {
- it('keeps the worker running when Postgres terminates a pooled connection', async () => {
- const {logger, exit, shutdown, handle} = createHarness();
-
- await handle('uncaughtException', adminShutdownError());
-
- expect(shutdown).not.toHaveBeenCalled();
- expect(exit).not.toHaveBeenCalled();
- expect(logger.error).not.toHaveBeenCalled();
- expect(logger.warn).toHaveBeenCalledTimes(1);
- const [context, message] = logger.warn.mock.calls[0]!;
- expect(message).toBe('Transient database connection error reached the worker process, keeping the worker running');
- expect(context).toMatchObject({source: 'uncaughtException'});
- });
-
it.each([
['57P01 admin_shutdown', '57P01'],
['57P02 crash_shutdown', '57P02'],
['57P03 cannot_connect_now', '57P03'],
['08006 connection_failure', '08006'],
['08003 connection_does_not_exist', '08003'],
- ])('survives %s', async (_label, code) => {
- const {exit, shutdown, handle} = createHarness();
+ ['a pooled client socket reset', 'ECONNRESET'],
+ ])('keeps running on %s', async (_label, code) => {
+ const {exitCodes, calls, handle} = createHarness();
await handle('uncaughtException', pooledClientError({message: 'connection lost', code}));
- expect(shutdown).not.toHaveBeenCalled();
- expect(exit).not.toHaveBeenCalled();
+ expect(calls.shutdown).toBe(0);
+ expect(exitCodes).toEqual([]);
});
it.each([['uncaughtException' as WorkerProcessErrorSource], ['unhandledRejection' as WorkerProcessErrorSource]])(
- 'survives a transient error arriving as %s',
+ 'keeps running on a transient error arriving as %s',
async (source) => {
- const {exit, shutdown, handle} = createHarness();
+ const {exitCodes, calls, handle} = createHarness();
await handle(source, adminShutdownError());
- expect(shutdown).not.toHaveBeenCalled();
- expect(exit).not.toHaveBeenCalled();
+ expect(calls.shutdown).toBe(0);
+ expect(exitCodes).toEqual([]);
},
);
- it('survives a socket error raised by a pooled Postgres client', async () => {
- const {exit, shutdown, handle} = createHarness();
-
- await handle('uncaughtException', pooledClientError({message: 'read ECONNRESET', code: 'ECONNRESET'}));
-
- expect(shutdown).not.toHaveBeenCalled();
- expect(exit).not.toHaveBeenCalled();
- });
-
- it('survives a transient error wrapped in a cause chain', async () => {
- const {exit, shutdown, handle} = createHarness();
- const wrapped = new Error('Connection terminated due to connection timeout', {cause: adminShutdownError()});
-
- await handle('uncaughtException', wrapped);
-
- expect(shutdown).not.toHaveBeenCalled();
- expect(exit).not.toHaveBeenCalled();
- });
-
- it('survives the pg driver telling us the client is no longer queryable', async () => {
- const {exit, shutdown, handle} = createHarness();
-
- await handle('uncaughtException', new Error('Client has encountered a connection error and is not queryable'));
-
- expect(shutdown).not.toHaveBeenCalled();
- expect(exit).not.toHaveBeenCalled();
- });
-
- it('still tears the worker down on a programming error', async () => {
- const {logger, exit, shutdown, handle} = createHarness();
- const bug = new TypeError('cannot read properties of undefined');
-
- await handle('uncaughtException', bug);
-
- expect(logger.warn).not.toHaveBeenCalled();
- expect(logger.error).toHaveBeenCalledWith({err: bug, source: 'uncaughtException'}, 'Uncaught Exception');
- expect(shutdown).toHaveBeenCalledTimes(1);
- expect(exit).toHaveBeenCalledWith(1);
- });
-
- it('still tears the worker down on a Postgres error that is not connection level', async () => {
- const {exit, shutdown, handle} = createHarness();
+ it('keeps running on a transient error wrapped in a cause chain', async () => {
+ const {exitCodes, calls, handle} = createHarness();
await handle(
'uncaughtException',
- pooledClientError({message: 'duplicate key value violates unique constraint', code: '23505'}),
+ new Error('Connection terminated due to connection timeout', {cause: adminShutdownError()}),
);
- expect(shutdown).toHaveBeenCalledTimes(1);
- expect(exit).toHaveBeenCalledWith(1);
+ expect(calls.shutdown).toBe(0);
+ expect(exitCodes).toEqual([]);
});
- it('does not treat a socket error from a non-Postgres source as transient', async () => {
- const {exit, shutdown, handle} = createHarness();
- const socketError = Object.assign(new Error('read ECONNRESET'), {code: 'ECONNRESET'});
-
- await handle('uncaughtException', socketError);
+ it('keeps running when the pg driver says the client is no longer queryable', async () => {
+ const {exitCodes, calls, handle} = createHarness();
- expect(shutdown).toHaveBeenCalledTimes(1);
- expect(exit).toHaveBeenCalledWith(1);
- });
-
- it('labels an unhandled rejection distinctly when it is fatal', async () => {
- const {logger, exit, shutdown, handle} = createHarness();
- const bug = new Error('boom');
-
- await handle('unhandledRejection', bug);
+ await handle('uncaughtException', new Error('Client has encountered a connection error and is not queryable'));
- expect(logger.error).toHaveBeenCalledWith(
- {err: bug, source: 'unhandledRejection'},
- 'Unhandled Rejection at Promise',
- );
- expect(shutdown).toHaveBeenCalledTimes(1);
- expect(exit).toHaveBeenCalledWith(1);
+ expect(calls.shutdown).toBe(0);
+ expect(exitCodes).toEqual([]);
});
- it('force exits when shutdown hangs on a fatal error', async () => {
- const {exit, handle} = createHarness({shutdown: () => new Promise<void>(() => {}), forceExitDelayMs: 5});
+ it.each([
+ ['a programming error', new TypeError('cannot read properties of undefined')],
+ [
+ 'a Postgres error that is not connection level',
+ pooledClientError({message: 'duplicate key value violates unique constraint', code: '23505'}),
+ ],
+ ['a socket error from a non-Postgres source', Object.assign(new Error('read ECONNRESET'), {code: 'ECONNRESET'})],
+ ])('shuts down and exits on %s', async (_label, error) => {
+ const {exitCodes, calls, handle} = createHarness();
- void handle('uncaughtException', new Error('boom'));
+ await handle('uncaughtException', error);
- await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(1));
+ expect(calls.shutdown).toBe(1);
+ expect(exitCodes).toEqual([1]);
});
it('exits even when shutdown itself throws', async () => {
- const {logger, exit, handle} = createHarness({
- shutdown: async () => {
- throw new Error('shutdown failed');
- },
+ const {exitCodes, handle} = createHarness(async () => {
+ throw new Error('shutdown failed');
});
await handle('uncaughtException', new Error('boom'));
- expect(exit).toHaveBeenCalledWith(1);
- expect(logger.error).toHaveBeenCalledTimes(2);
+ expect(exitCodes).toEqual([1]);
});
});
diff --git a/fluxer_api/src/api/worker/tests/WorkerRetiredTask.test.ts b/fluxer_api/src/api/worker/tests/WorkerRetiredTask.test.ts
deleted file mode 100644
index 3d4281f59..000000000
--- a/fluxer_api/src/api/worker/tests/WorkerRetiredTask.test.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {WorkerRunner} from '@app/api/worker/WorkerRunner';
-import type {JsMsg} from '@nats-io/jetstream';
-import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
-
-const RETIRED_TASK_TYPE = 'sendScheduledMessage';
-const RETIRED_REASON = 'task type retired';
-const LEDGER_JOB_ID = '1509197195776110592';
-
-const queueStub = {
- getConnectionManager: () => {
- throw new Error('WorkerRunner tests never consume messages');
- },
- getStreamName: () => 'JOBS',
- publishToDlq: vi.fn(),
-};
-
-const ledgerStub = {
- markDeadletter: vi.fn(),
-};
-
-class TestWorkerRunner extends WorkerRunner {
- async runJob(taskType: string, msg: JsMsg): Promise<boolean> {
- return await this.processJob(taskType, msg);
- }
-}
-
-function createRunner(): TestWorkerRunner {
- return new TestWorkerRunner({
- tasks: {},
- retiredTaskTypes: [RETIRED_TASK_TYPE],
- queue: queueStub,
- consumerName: 'workers_lifecycle',
- laneName: 'lifecycle',
- ledger: ledgerStub as unknown as JobLedgerRepository,
- concurrency: 8,
- maxDeliver: 25,
- ackWaitMs: 60000,
- });
-}
-
-function createJobMessage(taskType: string, payload: Record<string, unknown>) {
- const envelope = {
- payload,
- run_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
- max_attempts: 5,
- priority: 0,
- created_at: new Date().toISOString(),
- };
- return {
- seq: 7,
- subject: `jobs.${taskType}`,
- redelivered: false,
- data: new TextEncoder().encode(JSON.stringify(envelope)),
- info: {deliveryCount: 1},
- ack: vi.fn(),
- nak: vi.fn(),
- term: vi.fn(),
- working: vi.fn(),
- };
-}
-
-describe('Retired worker task types', () => {
- beforeAll(() => {
- setInjectedWorkerService(new NoopWorkerService());
- });
-
- afterEach(() => {
- queueStub.publishToDlq.mockReset();
- ledgerStub.markDeadletter.mockReset();
- });
-
- it('dead-letters a legacy job and closes its ledger row instead of redelivering it', async () => {
- const runner = createRunner();
- const msg = createJobMessage(RETIRED_TASK_TYPE, {
- userId: '1',
- scheduledMessageId: '2',
- __jobId: LEDGER_JOB_ID,
- });
-
- await expect(runner.runJob(RETIRED_TASK_TYPE, msg as unknown as JsMsg)).resolves.toBe(false);
-
- expect(queueStub.publishToDlq).toHaveBeenCalledTimes(1);
- expect(queueStub.publishToDlq).toHaveBeenCalledWith(
- RETIRED_TASK_TYPE,
- {userId: '1', scheduledMessageId: '2'},
- expect.objectContaining({errorMessage: RETIRED_REASON, lane: 'lifecycle', originalSeq: 7}),
- );
- expect(ledgerStub.markDeadletter).toHaveBeenCalledWith(BigInt(LEDGER_JOB_ID), RETIRED_REASON);
- expect(msg.term).toHaveBeenCalledWith(RETIRED_REASON);
- expect(msg.nak).not.toHaveBeenCalled();
- expect(msg.ack).not.toHaveBeenCalled();
- });
-
- it('dead-letters a legacy job that has no ledger id', async () => {
- const runner = createRunner();
- const msg = createJobMessage(RETIRED_TASK_TYPE, {userId: '1', scheduledMessageId: '2'});
-
- await expect(runner.runJob(RETIRED_TASK_TYPE, msg as unknown as JsMsg)).resolves.toBe(false);
-
- expect(queueStub.publishToDlq).toHaveBeenCalledTimes(1);
- expect(ledgerStub.markDeadletter).not.toHaveBeenCalled();
- expect(msg.term).toHaveBeenCalledWith(RETIRED_REASON);
- expect(msg.nak).not.toHaveBeenCalled();
- });
-
- it('redelivers a retired job when the dead-letter publish fails', async () => {
- const runner = createRunner();
- queueStub.publishToDlq.mockRejectedValueOnce(new Error('no responders'));
- const msg = createJobMessage(RETIRED_TASK_TYPE, {__jobId: LEDGER_JOB_ID});
-
- await expect(runner.runJob(RETIRED_TASK_TYPE, msg as unknown as JsMsg)).resolves.toBe(false);
-
- expect(ledgerStub.markDeadletter).not.toHaveBeenCalled();
- expect(msg.term).not.toHaveBeenCalled();
- expect(msg.nak).toHaveBeenCalledTimes(1);
- });
-
- it('still terminates a task type that was never registered or retired', async () => {
- const runner = createRunner();
- const msg = createJobMessage('neverShippedTask', {});
-
- await expect(runner.runJob('neverShippedTask', msg as unknown as JsMsg)).resolves.toBe(false);
-
- expect(queueStub.publishToDlq).not.toHaveBeenCalled();
- expect(msg.term).toHaveBeenCalledWith(expect.stringMatching(/unknown task type/));
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.ts b/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.ts
deleted file mode 100644
index 8acd6dd9c..000000000
--- a/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {WorkerRunner} from '@app/api/worker/WorkerRunner';
-import type {ConsumerMessages, JsMsg} from '@nats-io/jetstream';
-import {afterEach, beforeAll, describe, expect, it, vi} from 'vitest';
-
-const TASK_TYPE = 'processInactivityDeletions';
-const RESUBSCRIBE_WINDOW_MS = 30000;
-
-class FakeConsumerMessages {
- private readonly pending: Array<JsMsg> = [];
- private notify: (() => void) | null = null;
- private closed = false;
- private failure: Error | null = null;
-
- push(msg: JsMsg): void {
- this.pending.push(msg);
- this.wake();
- }
-
- abort(error: Error): void {
- this.failure = error;
- this.wake();
- }
-
- end(): void {
- this.closed = true;
- this.wake();
- }
-
- async close(): Promise<void> {
- this.end();
- }
-
- stop(error?: Error): void {
- if (error) {
- this.failure = error;
- }
- this.end();
- }
-
- async *[Symbol.asyncIterator](): AsyncGenerator<JsMsg> {
- while (true) {
- while (this.pending.length > 0) {
- yield this.pending.shift()!;
- }
- if (this.failure !== null) {
- throw this.failure;
- }
- if (this.closed) {
- return;
- }
- await new Promise<void>((resolve) => {
- this.notify = resolve;
- });
- }
- }
-
- private wake(): void {
- const notify = this.notify;
- this.notify = null;
- notify?.();
- }
-}
-
-function createRunner(streams: Array<FakeConsumerMessages>): {runner: WorkerRunner; consumeCount: () => number} {
- let consumed = 0;
- const queue = {
- getConnectionManager: () => ({
- getJetStreamClient: () => ({
- consumers: {
- get: async () => ({
- fetch: async () => {
- const stream = streams[consumed];
- consumed += 1;
- if (!stream) {
- throw new Error('no more streams');
- }
- return stream as unknown as ConsumerMessages;
- },
- }),
- },
- }),
- }),
- getStreamName: () => 'JOBS',
- publishToDlq: vi.fn(),
- };
- const runner = new WorkerRunner({
- tasks: {[TASK_TYPE]: async () => {}},
- queue,
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger: {} as JobLedgerRepository,
- concurrency: 12,
- maxDeliver: 25,
- ackWaitMs: 120000,
- });
- return {runner, consumeCount: () => consumed};
-}
-
-function createJobMessage() {
- const envelope = {
- payload: {},
- max_attempts: 5,
- priority: 0,
- created_at: new Date().toISOString(),
- };
- return {
- seq: 1,
- subject: `jobs.${TASK_TYPE}`,
- redelivered: false,
- data: new TextEncoder().encode(JSON.stringify(envelope)),
- info: {deliveryCount: 1},
- ack: vi.fn(),
- nak: vi.fn(),
- term: vi.fn(),
- working: vi.fn(),
- };
-}
-
-describe('Worker runner resubscribe', () => {
- beforeAll(() => {
- setInjectedWorkerService(new NoopWorkerService());
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('resubscribes after the message stream fails', async () => {
- vi.useFakeTimers();
- const streams = [new FakeConsumerMessages(), new FakeConsumerMessages()];
- const {runner, consumeCount} = createRunner(streams);
-
- await runner.start();
- expect(consumeCount()).toBe(1);
-
- streams[0]!.abort(new Error('consumer deleted'));
- await vi.advanceTimersByTimeAsync(RESUBSCRIBE_WINDOW_MS);
- expect(consumeCount()).toBe(2);
-
- const msg = createJobMessage();
- streams[1]!.push(msg as unknown as JsMsg);
- await vi.advanceTimersByTimeAsync(0);
- expect(msg.ack).toHaveBeenCalledTimes(1);
-
- await runner.stop();
- });
-
- it('resubscribes after the message stream ends without a stop', async () => {
- vi.useFakeTimers();
- const streams = [new FakeConsumerMessages(), new FakeConsumerMessages()];
- const {runner, consumeCount} = createRunner(streams);
-
- await runner.start();
- streams[0]!.end();
- await vi.advanceTimersByTimeAsync(RESUBSCRIBE_WINDOW_MS);
- expect(consumeCount()).toBe(2);
-
- const msg = createJobMessage();
- streams[1]!.push(msg as unknown as JsMsg);
- await vi.advanceTimersByTimeAsync(0);
- expect(msg.ack).toHaveBeenCalledTimes(1);
-
- await runner.stop();
- });
-
- it('does not resubscribe after the runner is stopped', async () => {
- vi.useFakeTimers();
- const streams = [new FakeConsumerMessages(), new FakeConsumerMessages()];
- const {runner, consumeCount} = createRunner(streams);
-
- await runner.start();
- await runner.stop();
- await vi.advanceTimersByTimeAsync(RESUBSCRIBE_WINDOW_MS);
-
- expect(consumeCount()).toBe(1);
- });
-});
diff --git a/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.ts b/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.ts
deleted file mode 100644
index da3af954d..000000000
--- a/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import type {JobLedgerRepository} from '@app/api/jobs/JobLedgerRepository';
-import {setInjectedWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {NoopWorkerService} from '@app/api/test/NoopWorkerService';
-import {WorkerRunner} from '@app/api/worker/WorkerRunner';
-import type {ConsumerMessages, JsMsg} from '@nats-io/jetstream';
-import {beforeAll, describe, expect, it, vi} from 'vitest';
-
-const TASK_TYPE = 'processInactivityDeletions';
-
-class FakeConsumerMessages {
- private readonly pending: Array<JsMsg> = [];
- private notify: (() => void) | null = null;
- private closed = false;
- private failure: Error | null = null;
-
- push(msg: JsMsg): void {
- this.pending.push(msg);
- this.wake();
- }
-
- async close(): Promise<void> {
- this.stop();
- }
-
- stop(error?: Error): void {
- if (error) {
- this.failure = error;
- }
- this.closed = true;
- this.wake();
- }
-
- async *[Symbol.asyncIterator](): AsyncGenerator<JsMsg> {
- while (true) {
- while (this.pending.length > 0) {
- yield this.pending.shift()!;
- }
- if (this.failure !== null) {
- throw this.failure;
- }
- if (this.closed) {
- return;
- }
- await new Promise<void>((resolve) => {
- this.notify = resolve;
- });
- }
- }
-
- private wake(): void {
- const notify = this.notify;
- this.notify = null;
- notify?.();
- }
-}
-
-function createQueueStub(messages: FakeConsumerMessages) {
- return {
- getConnectionManager: () => ({
- getJetStreamClient: () => ({
- consumers: {
- get: async () => ({
- fetch: async () => messages as unknown as ConsumerMessages,
- }),
- },
- }),
- }),
- getStreamName: () => 'JOBS',
- publishToDlq: vi.fn(),
- };
-}
-
-function createRunner(task: () => Promise<void>, messages: FakeConsumerMessages): WorkerRunner {
- return new WorkerRunner({
- tasks: {[TASK_TYPE]: task},
- queue: createQueueStub(messages),
- consumerName: 'workers_batch',
- laneName: 'batch',
- ledger: {} as JobLedgerRepository,
- concurrency: 12,
- maxDeliver: 25,
- ackWaitMs: 120000,
- });
-}
-
-function createJobMessage() {
- const envelope = {
- payload: {},
- max_attempts: 5,
- priority: 0,
- created_at: new Date().toISOString(),
- };
- return {
- seq: 1,
- subject: `jobs.${TASK_TYPE}`,
- redelivered: false,
- data: new TextEncoder().encode(JSON.stringify(envelope)),
- info: {deliveryCount: 1},
- ack: vi.fn(),
- nak: vi.fn(),
- term: vi.fn(),
- working: vi.fn(),
- };
-}
-
-describe('Worker runner shutdown', () => {
- beforeAll(() => {
- setInjectedWorkerService(new NoopWorkerService());
- });
-
- it('drains in-flight jobs before stop resolves', async () => {
- let started = false;
- let finished = false;
- let release: () => void = () => {};
- const pending = new Promise<void>((resolve) => {
- release = resolve;
- });
- const messages = new FakeConsumerMessages();
- const runner = createRunner(async () => {
- started = true;
- await pending;
- finished = true;
- }, messages);
- const msg = createJobMessage();
-
- await runner.start();
- messages.push(msg as unknown as JsMsg);
- await vi.waitFor(() => expect(started).toBe(true));
-
- setTimeout(release, 0);
- await runner.stop();
-
- expect(finished).toBe(true);
- expect(msg.ack).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/fluxer_api/vitest.config.ts b/fluxer_api/vitest.config.ts
index fe4c2dceb..d4f51efb0 100644
--- a/fluxer_api/vitest.config.ts
+++ b/fluxer_api/vitest.config.ts
@@ -26,6 +26,7 @@ const MODULE_REGISTRY_TEST_FILES = ['src/api/voice/tests/VoiceAvailabilityServic
const INSTANCE_POLICY_TEST_FILES = ['src/api/admin/tests/InstanceConfigPendingRegistrationApproval.test.ts'];
+const NATIVE_TIMEZONE_TEST_FILES = ['src/api/utils/AgeUtils.test.ts'];
const sharedExclude = [...configDefaults.exclude, 'pkgs/**', '../fluxer_desktop/**', '**/target/**'];
diff --git a/packages/errors/src/__tests__/RateLimitError.test.ts b/packages/errors/src/__tests__/RateLimitError.test.ts
index 33290feda..a98489be9 100644
--- a/packages/errors/src/__tests__/RateLimitError.test.ts
+++ b/packages/errors/src/__tests__/RateLimitError.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';
-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
interface RateLimitResponseBody {
code: string;
@@ -10,19 +10,13 @@ interface RateLimitResponseBody {
}
describe('RateLimitError', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date('2026-01-27T12:00:00.000Z'));
- });
- afterEach(() => {
- vi.useRealTimers();
- });
it('returns bucket headers for route limits', async () => {
+ const resetTime = new Date(Math.ceil(Date.now() / 1000) * 1000 + 60_000);
const error = new RateLimitError({
retryAfter: 5,
retryAfterDecimal: 4.5,
limit: 10,
- resetTime: new Date('2026-01-27T12:00:05.000Z'),
+ resetTime,
resetAfterDecimal: 4.5,
bucketHash: 'bucket-hash',
scope: 'user',
@@ -38,9 +32,7 @@ describe('RateLimitError', () => {
expect(response.headers.get('Retry-After')).toBe('5');
expect(response.headers.get('X-RateLimit-Limit')).toBe('10');
expect(response.headers.get('X-RateLimit-Remaining')).toBe('0');
- expect(response.headers.get('X-RateLimit-Reset')).toBe(
- Math.floor(new Date('2026-01-27T12:00:05.000Z').getTime() / 1000).toString(),
- );
+ expect(response.headers.get('X-RateLimit-Reset')).toBe(String(resetTime.getTime() / 1000));
expect(response.headers.get('X-RateLimit-Reset-After')).toBe('4.5');
expect(response.headers.get('X-RateLimit-Bucket')).toBe('bucket-hash');
expect(response.headers.get('X-RateLimit-Scope')).toBe('user');
diff --git a/packages/errors/src/i18n/ErrorI18n.test.ts b/packages/errors/src/i18n/ErrorI18n.test.ts
index 4d1fb316e..0ac04cbe1 100644
--- a/packages/errors/src/i18n/ErrorI18n.test.ts
+++ b/packages/errors/src/i18n/ErrorI18n.test.ts
@@ -4,7 +4,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {SsoRequiredReasons} from '@fluxer/errors/src/domains/auth/SsoRequiredError';
import {getErrorMessageUnsafe} from '@fluxer/errors/src/i18n/ErrorI18n';
import {ERROR_I18N_LOCALE_MESSAGES} from '@fluxer/errors/src/i18n/ErrorI18nLocales';
-import {describe, expect, it, vi} from 'vitest';
+import {describe, expect, it} from 'vitest';
describe('ErrorI18n global IP block messages', () => {
const HOSTED = {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d772d92eb..36733c86b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -677,9 +677,6 @@ importers:
mime:
specifier: 'catalog:'
version: 4.1.0
- nodemailer:
- specifier: 'catalog:'
- version: 10.1.4
pdf-lib:
specifier: 'catalog:'
version: 1.17.1