From c08f235ea8f09c008d1625fb19f57f04aebea7e8 Mon Sep 17 00:00:00 2001 From: hayyaksi <193020925+hayaksi1@users.noreply.github.com> Date: Wed, 12 Aug 2026 14:04:07 +0300 Subject: [PATCH] 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 --- apps/web/src/i18n/strings/en_EN.json | 1 + apps/web/src/utils/MultiInviter.test.ts | 79 ++++++++++++++++++++++++- apps/web/src/utils/MultiInviter.ts | 33 ++++++++++- 3 files changed, 109 insertions(+), 4 deletions(-) diff --git a/apps/web/src/i18n/strings/en_EN.json b/apps/web/src/i18n/strings/en_EN.json index 6e4b92d002..999cc1f9b2 100644 --- a/apps/web/src/i18n/strings/en_EN.json +++ b/apps/web/src/i18n/strings/en_EN.json @@ -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.", diff --git a/apps/web/src/utils/MultiInviter.test.ts b/apps/web/src/utils/MultiInviter.test.ts index f23434c0a8..e29677f7ba 100644 --- a/apps/web/src/utils/MultiInviter.test.ts +++ b/apps/web/src/utils/MultiInviter.test.ts @@ -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)); diff --git a/apps/web/src/utils/MultiInviter.ts b/apps/web/src/utils/MultiInviter.ts index 09ae6adb9c..d01f68d5a8 100644 --- a/apps/web/src/utils/MultiInviter.ts +++ b/apps/web/src/utils/MultiInviter.ts @@ -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 = {}; // { address: {errorText, errcode} } + private rateLimitRetries: Record = {}; // { 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");