fix(crypto): retry outgoing requests and serialize key claims and room encryption

This commit is contained in:
Erwan Leboucher committed 2026-08-30 19:48:18 +02:00
1 parent 4fb7eeb0e6
commit a9eaf55840
4 files changed
+158 -18

No files matched your search

+37 -11
View File
@@ -331,6 +331,10 @@ export class EngineCrypto
readonly #roomsWithTrackedMembers = new Set<string>();
#claimChain: Promise<unknown> = Promise.resolve();
readonly #encryptionChains = new Map<string, Promise<unknown>>();
readonly #backupUpload = createCoalescedRunner(
() =>
this.#uploadRoomKeysToBackup().catch((error: unknown) => {
@@ -851,6 +855,8 @@ export class EngineCrypto
this.#backupUpload.cancel();
this.#eventsPendingKey.clear();
this.#roomsWithTrackedMembers.clear();
this.#encryptionChains.clear();
this.#claimChain = Promise.resolve();
}
#trustRequirement(): number {
@@ -893,7 +899,30 @@ export class EngineCrypto
return settings;
}
#serializeForRoom<T>(roomId: string, run: () => Promise<T>): Promise<T> {
const next = (this.#encryptionChains.get(roomId) ?? Promise.resolve())
.catch(() => undefined)
.then(run);
this.#encryptionChains.set(roomId, next);
return next;
}
async #ensureSessionsForUsers(users: string[]): Promise<void> {
const next = this.#claimChain
.catch(() => undefined)
.then(async () => {
const claim = (await this.#call('getMissingSessions', { users })) as OutgoingRequest | null;
await this.#sendTracked(claim);
});
this.#claimChain = next;
await next;
}
async encryptEvent(event: MatrixEvent, room: Room): Promise<void> {
return this.#serializeForRoom(room.roomId, () => this.#encryptEventInner(event, room));
}
async #encryptEventInner(event: MatrixEvent, room: Room): Promise<void> {
// The megolm session has to reach every device in the room before the event does.
const members = await room.getEncryptionTargetMembers();
const users = members.map((member) => member.userId);
@@ -906,8 +935,7 @@ export class EngineCrypto
this.#roomsWithTrackedMembers.add(room.roomId);
}
const claim = (await this.#call('getMissingSessions', { users })) as OutgoingRequest | null;
await this.#sendTracked(claim);
await this.#ensureSessionsForUsers(users);
const shared = ((await this.#call('shareRoomKey', {
roomId: room.roomId,
@@ -1295,15 +1323,13 @@ export class EngineCrypto
}
prepareToEncrypt(room: Room): void {
void room
.getEncryptionTargetMembers()
.then(async (members) => {
const users = members.map((member) => member.userId);
await this.#trackUsers(users);
await this.#sendTracked(await this.#call('getMissingSessions', { users }));
await this.#flushOutgoingRequests();
})
.catch((error: unknown) => engineCryptoLog.warn('general', 'prepareToEncrypt failed', error));
void this.#serializeForRoom(room.roomId, async () => {
const members = await room.getEncryptionTargetMembers();
const users = members.map((member) => member.userId);
await this.#trackUsers(users);
await this.#ensureSessionsForUsers(users);
await this.#flushOutgoingRequests();
}).catch((error: unknown) => engineCryptoLog.warn('general', 'prepareToEncrypt failed', error));
}
async forceDiscardSession(roomId: string): Promise<void> {
@@ -0,0 +1,57 @@
import { describe, expect, it, vi } from 'vitest';
import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
import { engineInvoke } from '../olmMachine/engineInvoke';
import { EngineCrypto } from './EngineCrypto';
vi.mock('../olmMachine/engineInvoke', () => ({ engineInvoke: vi.fn() }));
const mockInvoke = vi.mocked(engineInvoke);
const room = (roomId: string) =>
({
roomId,
getEncryptionTargetMembers: async () => [{ userId: '@me:e.org' }],
getHistoryVisibility: () => 'shared',
getBlacklistUnverifiedDevices: () => false,
currentState: { getStateEvents: () => null },
}) as unknown as Room;
const event = () =>
({
getType: () => 'm.room.message',
getContent: () => ({}),
makeEncrypted: vi.fn(),
getTxnId: () => 't',
}) as unknown as MatrixEvent;
describe('encryptEvent ordering', () => {
it('never runs two encryptions for a room at the same time', async () => {
const marks: string[] = [];
let inFlight = 0;
mockInvoke.mockImplementation(async (_identity, method) => {
if (method === 'encryptRoomEvent') {
inFlight += 1;
marks.push(`enter${inFlight}`);
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
inFlight -= 1;
marks.push('exit');
return '{}';
}
if (method === 'identityKeys') return { ed25519: 'e', curve25519: 'c' };
return null;
});
const mx = { http: { authedRequest: vi.fn() } } as unknown as MatrixClient;
const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' });
await Promise.all([
crypto.encryptEvent(event(), room('!r:e.org')),
crypto.encryptEvent(event(), room('!r:e.org')),
]);
expect(marks).toEqual(['enter1', 'exit', 'enter1', 'exit']);
});
});
+21 -7
View File
@@ -1,4 +1,6 @@
import { Method } from 'matrix-js-sdk/lib/http-api';
import { calculateRetryBackoff } from 'matrix-js-sdk/lib/http-api/utils';
import { sleep } from 'matrix-js-sdk/lib/utils';
import type { MatrixClient } from '$types/matrix-sdk';
/** Numeric codes the engine tags outgoing requests with; see wasm_enums.rs. */
@@ -41,13 +43,25 @@ export const sendOutgoingRequest = async (
mx: MatrixClient,
request: OutgoingRequest
): Promise<string> => {
const send = (method: Method, url: string, params: Record<string, string> = {}) =>
mx.http.authedRequest<string>(method, url, params, request.body, {
prefix: '',
json: false,
localTimeoutMs: OUTGOING_REQUEST_TIMEOUT_MS,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
});
const send = async (method: Method, url: string, params: Record<string, string> = {}) => {
for (let attempts = 0; ;) {
try {
// eslint-disable-next-line no-await-in-loop
return await mx.http.authedRequest<string>(method, url, params, request.body, {
prefix: '',
json: false,
localTimeoutMs: OUTGOING_REQUEST_TIMEOUT_MS,
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
});
} catch (error) {
attempts += 1;
const backoff = calculateRetryBackoff(error, attempts, true);
if (backoff < 0) throw error;
// eslint-disable-next-line no-await-in-loop
await sleep(backoff);
}
}
};
switch (request.type) {
case RequestType.KeysUpload:
@@ -0,0 +1,43 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Method } from 'matrix-js-sdk/lib/http-api';
import type { MatrixClient } from '$types/matrix-sdk';
import { RequestType, sendOutgoingRequest } from './outgoing';
vi.mock('matrix-js-sdk/lib/utils', async (importOriginal) => ({
...(await importOriginal<typeof import('matrix-js-sdk/lib/utils')>()),
sleep: vi.fn(async () => undefined),
}));
const rateLimited = () =>
Object.assign(new Error('rate limited'), {
httpStatus: 429,
data: { errcode: 'M_LIMIT_EXCEEDED', retry_after_ms: 10 },
});
const request = { id: 'r1', type: RequestType.KeysClaim, body: '{}' };
describe('sendOutgoingRequest', () => {
beforeEach(() => vi.clearAllMocks());
it('retries a rate-limited request instead of failing the caller', async () => {
const authedRequest = vi
.fn<(...args: never[]) => Promise<string>>()
.mockRejectedValueOnce(rateLimited())
.mockResolvedValueOnce('{}');
const mx = { http: { authedRequest } } as unknown as MatrixClient;
await expect(sendOutgoingRequest(mx, request)).resolves.toBe('{}');
expect(authedRequest).toHaveBeenCalledTimes(2);
expect(authedRequest.mock.calls[0]?.[0]).toBe(Method.Post);
});
it('rethrows an error that is not worth retrying', async () => {
const authedRequest = vi
.fn<(...args: never[]) => Promise<string>>()
.mockRejectedValue(Object.assign(new Error('nope'), { httpStatus: 400, data: {} }));
const mx = { http: { authedRequest } } as unknown as MatrixClient;
await expect(sendOutgoingRequest(mx, request)).rejects.toThrow('nope');
expect(authedRequest).toHaveBeenCalledTimes(1);
});
});