Respect retry_after_ms and stop retrying rate limited invites forever (#34480)

A rate limited invite was retried on a hard coded five second delay with no
bound, so the client kept hammering a server which had already refused, and
ignored the retry_after_ms it asked us to wait.

The delay now comes from the server, capped so a very long backoff cannot leave
the invite dialog hanging, and each address gives up after a few attempts with
an error rather than looping.

Cancelling an in-flight invite is a separate concern and is not addressed here.

Fixes https://github.com/element-hq/element-web/issues/30427

Co-authored-by: David Baker <dbkr@users.noreply.github.com>
This commit is contained in:
hayyaksi
2026-08-12 14:04:07 +03:00
committed by GitHub
parent 5349566611
commit c08f235ea8
3 changed files with 109 additions and 4 deletions
+1
View File
@@ -1360,6 +1360,7 @@
"error_permissions_room": "You do not have permission to invite people to this room.",
"error_permissions_space": "You do not have permission to invite people to this space.",
"error_profile_undisclosed": "User may or may not exist",
"error_rate_limited": "Too many invites were sent. Please try again later.",
"error_transfer_multiple_target": "A call can only be transferred to a single user.",
"error_unfederated_room": "This room is unfederated. You cannot invite people from external servers.",
"error_unfederated_space": "This space is unfederated. You cannot invite people from external servers.",
+78 -1
View File
@@ -8,7 +8,7 @@ Please see LICENSE files in the repository root for full details.
// @vitest-environment happy-dom
import { vi, describe, it, expect, beforeEach, type Mocked } from "vitest";
import { vi, describe, it, expect, beforeEach, afterEach, type Mocked } from "vitest";
import { EventType, type MatrixClient, MatrixError, MatrixEvent, Room, RoomMember } from "matrix-js-sdk/src/matrix";
import { KnownMembership } from "matrix-js-sdk/src/types";
import * as TestUtilsMatrix from "test-utils";
@@ -121,6 +121,83 @@ describe("MultiInviter", () => {
expect(mockModalHandle.close).toHaveBeenCalled();
});
describe("when the server rate limits us", () => {
const rateLimited = (retryAfterMs?: number) =>
new MatrixError({
errcode: "M_LIMIT_EXCEEDED",
error: "Too Many Requests",
retry_after_ms: retryAfterMs,
});
beforeEach(() => {
mockPromptBeforeInviteUnknownUsers(false);
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("should wait as long as the server asks before retrying", async () => {
client.invite.mockRejectedValueOnce(rateLimited(2000)).mockResolvedValue({});
const resultPromise = inviter.invite([MXID1]);
await vi.advanceTimersByTimeAsync(1999);
expect(client.invite).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
await resultPromise;
expect(client.invite).toHaveBeenCalledTimes(2);
expect(inviter.getCompletionState(MXID1)).toBe("invited");
});
it("should give up instead of retrying forever", async () => {
client.invite.mockRejectedValue(rateLimited(1000));
const resultPromise = inviter.invite([MXID1]);
await vi.advanceTimersByTimeAsync(10 * 60 * 1000);
await resultPromise;
// the initial attempt plus a bounded number of retries, not an unbounded loop
expect(client.invite).toHaveBeenCalledTimes(4);
expect(inviter.getCompletionState(MXID1)).toBe("error");
expect(inviter.getErrorText(MXID1)).toMatchInlineSnapshot(
`"Too many invites were sent. Please try again later."`,
);
});
it("should fall back to a fixed delay when the server does not say how long to wait", async () => {
client.invite.mockRejectedValueOnce(rateLimited()).mockResolvedValue({});
const resultPromise = inviter.invite([MXID1]);
await vi.advanceTimersByTimeAsync(4999);
expect(client.invite).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
await resultPromise;
expect(client.invite).toHaveBeenCalledTimes(2);
});
it("should not wait longer than the maximum delay however long the server asks for", async () => {
// The report which prompted this had the server asking for over four minutes.
client.invite.mockRejectedValueOnce(rateLimited(255839)).mockResolvedValue({});
const resultPromise = inviter.invite([MXID1]);
await vi.advanceTimersByTimeAsync(29999);
expect(client.invite).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(1);
await resultPromise;
expect(client.invite).toHaveBeenCalledTimes(2);
});
});
describe("with promptBeforeInviteUnknownUsers = false", () => {
beforeEach(() => mockPromptBeforeInviteUnknownUsers(false));
+30 -3
View File
@@ -41,6 +41,13 @@ const USER_ALREADY_JOINED = "IO.ELEMENT.ALREADY_JOINED";
const USER_ALREADY_INVITED = "IO.ELEMENT.ALREADY_INVITED";
const USER_BANNED = "IO.ELEMENT.BANNED";
/** How long to wait before retrying a rate limited invite, when the server does not tell us. */
const RATE_LIMIT_DEFAULT_DELAY_MS = 5000;
/** The longest we will wait between retries, however long the server asks us to wait. */
const RATE_LIMIT_MAX_DELAY_MS = 30000;
/** How many times a single address is retried before we give up and report an error. */
const RATE_LIMIT_MAX_RETRIES = 3;
/** Options interface for {@link MultiInviter} */
export interface MultiInviterOptions {
/** Optional callback, fired after each invite */
@@ -61,6 +68,7 @@ export default class MultiInviter {
private _fatal = false;
private completionStates: CompletionStates = {}; // State of each address (invited or error)
private errors: Record<string, IError> = {}; // { address: {errorText, errcode} }
private rateLimitRetries: Record<string, number> = {}; // { address: number of retries so far }
private reason: string | undefined;
/**
@@ -253,6 +261,7 @@ export default class MultiInviter {
.then(() => {
this.completionStates[address] = InviteState.Invited;
delete this.errors[address];
delete this.rateLimitRetries[address];
resolve();
this.options.progressCallback?.();
@@ -297,12 +306,30 @@ export default class MultiInviter {
errorText = _t("invite|error_already_joined_room");
}
break;
case "M_LIMIT_EXCEEDED":
// we're being throttled so wait a bit & try again
case "M_LIMIT_EXCEEDED": {
const retries = this.rateLimitRetries[address] ?? 0;
if (retries >= RATE_LIMIT_MAX_RETRIES) {
// We have given the server several chances; stop hammering it.
errorText = _t("invite|error_rate_limited");
break;
}
this.rateLimitRetries[address] = retries + 1;
// we're being throttled so wait as long as the server asks & try again.
// The delay is capped so that a very long backoff does not leave the
// invite dialog hanging with no way out.
const retryAfterMs = Number(err.data?.retry_after_ms);
const delayMs = Math.min(
Number.isFinite(retryAfterMs) && retryAfterMs >= 0
? retryAfterMs
: RATE_LIMIT_DEFAULT_DELAY_MS,
RATE_LIMIT_MAX_DELAY_MS,
);
window.setTimeout(() => {
this.doInvite(address, ignoreProfile).then(resolve, reject);
}, 5000);
}, delayMs);
return;
}
case "M_NOT_FOUND":
case "M_USER_NOT_FOUND":
errorText = _t("invite|error_user_not_found");