Skip to content

Conversation

@rodrigok
Copy link
Member

@rodrigok rodrigok commented Sep 24, 2025

Related to RocketChat/homeserver#212

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability when accepting room invitations, reducing intermittent join failures and duplicate notifications.
    • Ensures correct sequencing of the join process for a smoother, more consistent experience.
    • Any added delay is minimal and should be unnoticeable to users.

@rodrigok rodrigok added this to the 7.11.0 milestone Sep 24, 2025
@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Sep 24, 2025

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Sep 24, 2025

⚠️ No Changeset found

Latest commit: a7b858f

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 24, 2025

Walkthrough

A 200 ms asynchronous delay was introduced before invoking startJoiningRoom in ee/packages/federation-matrix/src/api/_matrix/invite.ts, replacing the previous immediate call. No exported or public API signatures were changed.

Changes

Cohort / File(s) Summary
Matrix federation invite handling
ee/packages/federation-matrix/src/api/_matrix/invite.ts
Replaced direct call to startJoiningRoom({ inviteEvent, user: ourUser, room, state }) with setTimeout(() => { void startJoiningRoom({...}); }, 200), altering control flow to delayed async execution without modifying inputs/outputs or exports.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant IH as InviteHandler
  participant T as Timer (200ms)
  participant JR as startJoiningRoom

  C->>IH: Receive invite event
  note right of IH: Previous flow: IH -> JR immediately
  IH->>T: setTimeout(200ms, callback)
  T-->>IH: timeout fires (200ms later)
  IH->>JR: startJoiningRoom({inviteEvent, user, room, state})
  JR-->>IH: Join process continues
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • fix: dm check on invite #37012 — Also modifies invite/join handling in invite.ts (DM detection logic), related to the timing change of invoking startJoiningRoom.

Suggested reviewers

  • ggazzo

Poem

A hop, a pause—two hundred ticks,
I twitch my ears at async tricks.
The room will open, soon enough,
After a breath, a gentle buff.
With timed delight I join the chat—
A rabbit waits, then taps: “Hello!” 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title precisely names the bug fix for federation direct messages by referencing the first message issue and matches the code changes that delay room joining to address that problem while using clear conventional commit syntax.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/federation-dm-first-message

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Sep 24, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.77%. Comparing base (9ee2c14) to head (a7b858f).
⚠️ Report is 1 commits behind head on chore/federation-backup.

Additional details and impacted files

Impacted file tree graph

@@                     Coverage Diff                     @@
##           chore/federation-backup   #37048      +/-   ##
===========================================================
+ Coverage                    69.75%   69.77%   +0.02%     
===========================================================
  Files                         3035     3035              
  Lines                       103431   103431              
  Branches                     18383    18385       +2     
===========================================================
+ Hits                         72146    72171      +25     
+ Misses                       29405    29380      -25     
  Partials                      1880     1880              
Flag Coverage Δ
unit 71.29% <ø> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@rodrigok rodrigok force-pushed the fix/federation-dm-first-message branch from e2e8a0c to 81c1c24 Compare September 24, 2025 14:55
@rodrigok rodrigok force-pushed the fix/federation-dm-first-message branch from 81c1c24 to a7b858f Compare September 24, 2025 16:34
@rodrigok rodrigok changed the base branch from use-published-package to chore/federation-backup September 24, 2025 16:35
@rodrigok rodrigok marked this pull request as ready for review September 24, 2025 16:35
@rodrigok rodrigok merged commit 01efd39 into chore/federation-backup Sep 24, 2025
20 of 22 checks passed
@rodrigok rodrigok deleted the fix/federation-dm-first-message branch September 24, 2025 16:39
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
ee/packages/federation-matrix/src/api/_matrix/invite.ts (1)

134-144: Fix the backoff timing (ms vs sec) — current logic retries almost immediately, then explodes to multi‑day delays

The units are mixed up. You log ms but calculate seconds, call setTimeout with seconds (treated as ms), and pass ms back as seconds for the next iteration. This causes a 25 ms retry instead of 25 s, then jumps to days on subsequent attempts. Patch below keeps seconds for the state, ms for timers, and caps at 625 s as per the comment.

 async function runWithBackoff(fn: () => Promise<void>, delaySec = 5) {
 	try {
 		await fn();
 	} catch (e) {
-		const delay = delaySec === 625 ? 625 : delaySec ** 2;
-		console.log(`error occurred, retrying in ${delay}ms`, e);
-		setTimeout(() => {
-			runWithBackoff(fn, delay * 1000);
-		}, delay);
+		const nextDelaySec = delaySec >= 625 ? 625 : delaySec ** 2;
+		const delayMs = delaySec * 1000;
+		console.log(`error occurred, retrying in ${delayMs}ms`, e);
+		setTimeout(() => {
+			void runWithBackoff(fn, nextDelaySec);
+		}, delayMs);
 	}
 }
🧹 Nitpick comments (2)
ee/packages/federation-matrix/src/api/_matrix/invite.ts (2)

325-333: Avoid hardcoded 200 ms “magic sleep”; make it configurable (or justify necessity)

If the intent is to decouple from the request or wait for persistence, a fixed 200 ms is brittle. Either rely on runWithBackoff (no delay) or make the initial delay a named, configurable constant.

-			setTimeout(() => {
+			setTimeout(() => {
 				void startJoiningRoom({
 					inviteEvent,
 					user: ourUser,
 					room,
 					state,
 				});
-			}, 200);
+			}, INVITE_INITIAL_JOIN_DELAY_MS);

Add near the top of the file (or a config module):

// Initial defer before attempting the first join; allows eventual consistency after invite processing.
const INVITE_INITIAL_JOIN_DELAY_MS = Number(process.env.FEDERATION_INVITE_INITIAL_JOIN_DELAY_MS ?? 200);

Please confirm the root cause that necessitated the delay; if it’s eventual consistency, consider replacing this with a readiness check and relying solely on the (fixed) backoff.


285-287: Remove unnecessary async from startJoiningRoom

The function doesn’t await anything and always returns immediately; dropping async avoids returning an unused Promise.

-async function startJoiningRoom(...opts: Parameters<typeof joinRoom>) {
+function startJoiningRoom(...opts: Parameters<typeof joinRoom>) {
 	void runWithBackoff(() => joinRoom(...opts));
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ee2c14 and a7b858f.

📒 Files selected for processing (1)
  • ee/packages/federation-matrix/src/api/_matrix/invite.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: 🔨 Test Unit / Unit Tests
  • GitHub Check: 🔎 Code Check / TypeScript
  • GitHub Check: 🔎 Code Check / Code Lint
  • GitHub Check: 📦 Meteor Build - coverage
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants