Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/desktop/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"mediasoup-client": "^3.26.0",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-i18next": "^16.6.6",
"react-i18next": "^18.0.3",
"react-markdown": "^10.1.0",
"react-router-dom": "^7.18.7",
"react-virtuoso": "^4.18.24",
Expand Down
112 changes: 112 additions & 0 deletions apps/desktop/src/__tests__/i18n/transValues.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { describe, it, expect, afterEach } from 'vitest';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { Trans } from 'react-i18next';
import i18n, { SUPPORTED_LANGUAGES } from '../../i18n';

// Three sentences place a name a person chose (a role's, a space's, an e-mail
// address) inside a translation through <Trans values>. This renders them with
// the real react-i18next and the app's real i18n instance, in every language,
// and reads the DOM: the name is shown as it was written, inside the one
// emphasised element, whatever it contains. A name is text, never markup,
// never a placeholder and never an entity.

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

/** The three call sites: key, the variable its translation names, and the
* children the component gives (index 1 is the emphasised element). */
const SENTENCES = [
{ key: 'roles.deleteRoleQuestion', variable: 'name' },
{ key: 'serverSettings.general.typeToConfirm', variable: 'name' },
{ key: 'auth.emailPending.description', variable: 'email' },
] as const;

const NAMES = [
'Moderators',
'Tom & Jerry',
'<1>inside</1>',
'<b>bold</b> <img src=x onerror=alert(1)>',
'{{name}} {{email}} {{other}}',
'$t(roles.deleteRole)',
'a &lt; b &amp; c &#169; &nbsp;',
'user+tag@example.test',
'17/12/2025 "quoted" \'single\'',
];

let root: Root | null = null;
let host: HTMLDivElement | null = null;

function render(key: string, variable: string, value: string): HTMLDivElement {
host = document.createElement('div');
document.body.appendChild(host);
root = createRoot(host);
act(() => {
root!.render(
<p>
<Trans i18nKey={key} values={{ [variable]: value }}>
before <span data-testid="name">{`{{${variable}}}`}</span> after
</Trans>
</p>,
);
});
return host;
}

/** The sentence a reader should see: the stored translation with its one
* numbered element opened up and the value put in the variable's place. */
function expectedText(language: string, key: string, variable: string, value: string): string {
const stored = i18n.getResource(language, 'translation', key) as unknown;
if (typeof stored !== 'string') throw new Error(`${language}: ${key} is not a string`);
return stored.replace('<1>', '').replace('</1>', '').replace(`{{${variable}}}`, () => value);
}

afterEach(async () => {
act(() => { root?.unmount(); });
host?.remove();
root = null;
host = null;
await act(async () => { await i18n.changeLanguage('en'); });
});

describe('a name placed in a translation by <Trans values>', () => {
it('every language holds the three sentences with one numbered element around the variable, and no entity', () => {
for (const { code } of SUPPORTED_LANGUAGES) {
for (const { key, variable } of SENTENCES) {
const stored = i18n.getResource(code, 'translation', key) as unknown;
expect(typeof stored, `${code} ${key}`).toBe('string');
expect(stored as string, `${code} ${key}`).toContain(`<1>{{${variable}}}</1>`);
// <Trans> decodes an entity it finds in a translation: none is written there
expect(stored as string, `${code} ${key}`).not.toMatch(/&(#\d+|#x[0-9a-f]+|[a-z]+);/i);
}
}
});

for (const { key, variable } of SENTENCES) {
for (const value of NAMES) {
it(`${key}: shows ${JSON.stringify(value)} as written, in every language`, async () => {
for (const { code } of SUPPORTED_LANGUAGES) {
await act(async () => { await i18n.changeLanguage(code); });
const container = render(key, variable, value);
const names = container.querySelectorAll('[data-testid="name"]');
expect(names.length, code).toBe(1);
expect(names[0].textContent, code).toBe(value);
// The emphasised element holds text only: nothing of the value became an element
expect(names[0].children.length, code).toBe(0);
expect(container.querySelectorAll('p > *').length, code).toBe(1);
expect(container.textContent, code).toBe(expectedText(code, key, variable, value));
act(() => { root?.unmount(); });
container.remove();
root = null;
host = null;
}
});
}
}

it('a sentence on screen follows a change of language by itself', async () => {
const container = render('roles.deleteRoleQuestion', 'name', 'Moderators');
expect(container.textContent).toBe(expectedText('en', 'roles.deleteRoleQuestion', 'name', 'Moderators'));
await act(async () => { await i18n.changeLanguage('fr'); });
expect(container.textContent).toBe(expectedText('fr', 'roles.deleteRoleQuestion', 'name', 'Moderators'));
});
});
2 changes: 1 addition & 1 deletion apps/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"prisma": "^7.10.1",
"qrcode": "^1.5.4",
"rate-limiter-flexible": "^10.0.1",
"redis": "^5.11.0",
"redis": "^6.4.0",
"socket.io": "^4.8.4"
},
"devDependencies": {
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/__tests__/utils/redis.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,11 @@ describe('utils/redis — lazy initialization', () => {
socket: {
reconnectStrategy: expect.any(Function),
keepAlive: true,
keepAliveInitialDelay: 5000,
connectTimeout: 10000,
},
commandOptions: { timeout: undefined },
maintNotifications: 'disabled',
});
delete process.env.REDIS_URL;
});
Expand Down
64 changes: 64 additions & 0 deletions apps/server/src/__tests__/utils/redisClientOptions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { describe, it, expect } from 'vitest';
import { createClient } from 'redis';
import { redisClientOptions } from '../../utils/redis';

// The REAL client, never connected: what it resolves from the server's
// options, beside what it resolves from none for the command timeout and the
// maintenance notifications. The second half is the reason for the first. The
// day one of those defaults moves again, or the place the client keeps the
// resolved value does, a test here fails and the options in utils/redis.ts
// are read against the client's notes before anything else.

interface Resolved {
options?: {
maintNotifications?: string;
socket?: { keepAlive?: boolean; keepAliveInitialDelay?: number };
};
/** The command options the client applies to every command (its own field). */
_commandOptions?: { timeout?: number };
}
const resolved = (client: unknown) => client as Resolved;

// Nothing listens on port 1, and no client here connects
const ADDRESS = 'redis://127.0.0.1:1';

describe('the Redis client options, as the real client resolves them', () => {
it('a command waiting to be sent has no timeout', () => {
const client = resolved(createClient(redisClientOptions(ADDRESS)));
expect(client._commandOptions).toBeDefined();
expect(client._commandOptions?.timeout).toBeUndefined();
});

it('the hand-shake asks for no maintenance notifications', () => {
const client = resolved(createClient(redisClientOptions(ADDRESS)));
expect(client.options?.maintNotifications).toBe('disabled');
});

it('the first keep-alive probe of an idle connection goes out after 5 s', () => {
const client = resolved(createClient(redisClientOptions(ADDRESS)));
expect(client.options?.socket?.keepAlive).toBe(true);
expect(client.options?.socket?.keepAliveInitialDelay).toBe(5000);
});

it('a duplicate, as the pub/sub clients are made, resolves the same', () => {
const duplicate = resolved(createClient(redisClientOptions(ADDRESS)).duplicate());
expect(duplicate._commandOptions).toBeDefined();
expect(duplicate._commandOptions?.timeout).toBeUndefined();
expect(duplicate.options?.maintNotifications).toBe('disabled');
expect(duplicate.options?.socket?.keepAliveInitialDelay).toBe(5000);
});

it('the options carry the address they were asked for', () => {
expect(redisClientOptions('redis://example.test:6380').url).toBe('redis://example.test:6380');
});
});

describe('what the client does when it is given no such option (why they are stated)', () => {
it('rejects a command still waiting to be sent after 5 s', () => {
expect(resolved(createClient({ url: ADDRESS }))._commandOptions?.timeout).toBe(5000);
});

it('asks for maintenance notifications when the server offers them', () => {
expect(resolved(createClient({ url: ADDRESS })).options?.maintNotifications).toBe('auto');
});
});
30 changes: 29 additions & 1 deletion apps/server/src/utils/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,41 @@ let redisConfigSub: RedisClientType;
const REDIS_SOCKET_OPTIONS: NonNullable<RedisClientOptions<RedisModules, RedisFunctions, RedisScripts>['socket']> = {
reconnectStrategy: (retries: number) => Math.min(retries * 50, 2000),
keepAlive: true,
keepAliveInitialDelay: 5000,
connectTimeout: 10000,
};

/**
* The options every Redis client of the server is made with (the pub/sub
* duplicates inherit them). Three of them state what major 5 of the client
* did by default and major 6 changed, so what the server does while Redis is
* away is the same under both:
* - `commandOptions.timeout` undefined: a command issued while the
* connection is down waits for the reconnect. By default major 6 rejects
* it after 5 s, unsent. The few calls that must not wait bound themselves
* (the statistics cache, the visibility resync's publish); the rest wait,
* as they did.
* - `maintNotifications` 'disabled': a connection's hand-shake sends no
* maintenance-notification command. By default major 6 sends one, and
* resolves the host's address for it; the server uses neither.
* - `socket.keepAliveInitialDelay` 5000: the first keep-alive probe of an
* idle connection (a subscriber's above all) goes out after 5 s. Major 6
* waits 30 s by default.
* The wire protocol is the client's own default (RESP3 since major 6).
*/
export function redisClientOptions(url: string): RedisClientOptions<RedisModules, RedisFunctions, RedisScripts> {
return {
url,
socket: REDIS_SOCKET_OPTIONS,
commandOptions: { timeout: undefined },
maintNotifications: 'disabled',
};
}

export async function initRedis(): Promise<RedisClientType> {
const url = process.env.REDIS_URL || 'redis://localhost:6379';

redisClient = createClient({ url, socket: REDIS_SOCKET_OPTIONS });
redisClient = createClient(redisClientOptions(url));
redisClient.on('error', (err) => console.error('[Redis] Error:', err));
await redisClient.connect();

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"eslint": "^10.15.0",
"mediasoup-client": "^3.26.0",
"otpauth": "^9.6.0",
"redis": "^5.11.0",
"redis": "^6.4.0",
"typescript-eslint": "^8.74.0"
},
"license": "SEE LICENSE IN LICENSE.md"
Expand Down
Loading
Loading