Skip to content

Conversation

@rodrigok
Copy link
Member

@rodrigok rodrigok commented Sep 25, 2025

Linked to RocketChat/homeserver#225

Proposed changes (including videos or screenshots)

Issue(s)

Steps to test or reproduce

Further comments

Summary by CodeRabbit

  • Bug Fixes
    • Ensures media files shared via Matrix federation are correctly linked to the specific room, preventing cross-room mix-ups.
    • Improves reliability of uploading and downloading attachments (including previews/thumbnails) in federated Matrix conversations.
    • Enhances consistency of media metadata, reducing errors when sending or receiving files across federated rooms.

@rodrigok rodrigok requested a review from a team as a code owner September 25, 2025 18:04
@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Sep 25, 2025

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

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

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 25, 2025

⚠️ No Changeset found

Latest commit: a98d239

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 25, 2025

Walkthrough

Adds matrixRoomId propagation through media handling: updates event handler to pass data.room_id into media processing, extends MatrixMediaService methods to accept matrixRoomId and store it as federation.mrid, updates FederationMatrix to pass matrixRoomId for local files, and extends IUpload.federation with a new mrid field.

Changes

Cohort / File(s) Summary of changes
Event flow: media message handling
ee/packages/federation-matrix/src/events/message.ts
Added matrixRoomId param to handleMediaMessage; message() now passes data.room_id; downstream call to MatrixMediaService.downloadAndStoreRemoteFile updated to include matrixRoomId.
Service layer: media preparation and download
ee/packages/federation-matrix/src/services/MatrixMediaService.ts
Updated method signatures to include matrixRoomId for prepareLocalFileForMatrix and downloadAndStoreRemoteFile; persisted federation.mrid alongside existing federation fields in both local and remote file paths.
Outbound file handling
ee/packages/federation-matrix/src/FederationMatrix.ts
handleFileMessage now passes matrixRoomId to MatrixMediaService.prepareLocalFileForMatrix.
Type definitions
packages/core-typings/src/IUpload.ts
Added federation.mrid: string to IUpload interface.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Matrix as Matrix Event
  participant Msg as message() handler
  participant MediaH as handleMediaMessage()
  participant Svc as MatrixMediaService
  participant Store as Upload Storage

  Note over Matrix,Msg: Incoming Matrix message

  Matrix->>Msg: event (data.room_id, content)
  alt Remote media (mxc://)
    Msg->>MediaH: handleMediaMessage(..., matrixRoomId=data.room_id)
    MediaH->>Svc: downloadAndStoreRemoteFile(mxcUri, matrixRoomId, metadata)
    Svc->>Store: save file (+federation.mrid)
    Store-->>Svc: fileId
    Svc-->>MediaH: fileId
  else Local file to send
    Msg->>Svc: prepareLocalFileForMatrix(fileId, serverName, matrixRoomId)
    Svc->>Store: update upload (+federation.mrid)
    Store-->>Svc: ok
    Svc-->>Msg: prepared media info
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • ricardogarim

Poem

A hop, a skip, a room ID in tow,
I stash my MRID where the media will go.
From burrow to Matrix, I carefully thread—
Files with context, neatly spread.
Thump-thump! says the queue as I commit with glee,
Carrots for tests, and a bug-free spree. 🥕🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly indicates that this change addresses a bug in the federation upload functionality by fixing uploads that were failing, which matches the modifications to the federation‐matrix service and interface. It is concise, contextually relevant, and follows a standard "fix(scope): description" format without extraneous details. The phrasing is specific enough for a reviewer to understand the purpose of the PR at a glance.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/federation-backup-fix-upload

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.

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 (2)
ee/packages/federation-matrix/src/services/MatrixMediaService.ts (2)

49-56: Backfill mrid when MXC already exists

If a file already has mxcUri but no mrid (existing data before this change), we return early and never set mrid, leaving federation metadata incomplete. Update it before returning.

Apply:

-      if (file.federation?.mxcUri) {
-        return file.federation.mxcUri;
-      }
+      if (file.federation?.mxcUri) {
+        if (!file.federation.mrid || file.federation.mrid !== matrixRoomId) {
+          await Uploads.setFederationInfo(fileId, {
+            mxcUri: file.federation.mxcUri,
+            mrid: matrixRoomId,
+            serverName: file.federation.serverName ?? serverName,
+            mediaId: file.federation.mediaId ?? fileId,
+          });
+        }
+        return file.federation.mxcUri;
+      }

107-111: Backfill mrid for existing remote uploads

Early return skips setting mrid for files that already exist, causing missing room context on older records.

Apply:

-      if (uploadAlreadyExists) {
-        return uploadAlreadyExists._id;
-      }
+      if (uploadAlreadyExists) {
+        if (!uploadAlreadyExists.federation?.mrid || uploadAlreadyExists.federation.mrid !== matrixRoomId) {
+          await Uploads.setFederationInfo(uploadAlreadyExists._id, {
+            mxcUri,
+            mrid: matrixRoomId,
+            serverName: parts.serverName,
+            mediaId: parts.mediaId,
+          });
+        }
+        return uploadAlreadyExists._id;
+      }
🧹 Nitpick comments (1)
ee/packages/federation-matrix/src/events/message.ts (1)

230-240: Use of data.room_id – optional consistency tweak

You could pass room.federation.mrid here (already validated above) to keep a single source of truth, but current usage is fine.

📜 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 37c5bf7 and a98d239.

📒 Files selected for processing (4)
  • ee/packages/federation-matrix/src/FederationMatrix.ts (1 hunks)
  • ee/packages/federation-matrix/src/events/message.ts (3 hunks)
  • ee/packages/federation-matrix/src/services/MatrixMediaService.ts (4 hunks)
  • packages/core-typings/src/IUpload.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-09-19T15:15:04.642Z
Learnt from: rodrigok
PR: RocketChat/Rocket.Chat#36991
File: apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts:219-221
Timestamp: 2025-09-19T15:15:04.642Z
Learning: The Federation_Matrix_homeserver_domain setting in apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Settings.ts is part of the old federation system and is being deprecated/removed, so configuration issues with this setting should not be flagged for improvement.

Applied to files:

  • ee/packages/federation-matrix/src/services/MatrixMediaService.ts
🧬 Code graph analysis (2)
ee/packages/federation-matrix/src/events/message.ts (1)
ee/packages/federation-matrix/src/services/MatrixMediaService.ts (1)
  • MatrixMediaService (18-151)
ee/packages/federation-matrix/src/FederationMatrix.ts (1)
ee/packages/federation-matrix/src/services/MatrixMediaService.ts (1)
  • MatrixMediaService (18-151)
⏰ 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). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: Builds matrix rust bindings against alpine
  • GitHub Check: CodeQL-Build
🔇 Additional comments (4)
ee/packages/federation-matrix/src/events/message.ts (2)

25-35: handleMediaMessage signature extended – OK

Adding matrixRoomId keeps room context through media ingestion.


46-52: Pass matrixRoomId to downloadAndStoreRemoteFile – OK

Correctly propagates room context into stored federation info.

ee/packages/federation-matrix/src/FederationMatrix.ts (1)

431-431: All MatrixMediaService calls updated to new signature
No remaining old-arity calls to prepareLocalFileForMatrix or downloadAndStoreRemoteFile.

packages/core-typings/src/IUpload.ts (1)

62-67: All setFederationInfo callers supply mrid – no breaking changes
Detected invocations in MatrixMediaService (both branches) and model methods all include the new mrid field, and Required<IUpload>['federation'] enforces it at compile time.

@codecov
Copy link

codecov bot commented Sep 25, 2025

Codecov Report

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

Additional details and impacted files

Impacted file tree graph

@@                     Coverage Diff                     @@
##           chore/federation-backup   #37064      +/-   ##
===========================================================
+ Coverage                    69.76%   69.79%   +0.02%     
===========================================================
  Files                         3022     3022              
  Lines                       103465   103465              
  Branches                     18400    18398       -2     
===========================================================
+ Hits                         72186    72209      +23     
+ Misses                       29401    29378      -23     
  Partials                      1878     1878              
Flag Coverage Δ
e2e 57.28% <ø> (+0.01%) ⬆️
unit 71.15% <ø> (+0.02%) ⬆️

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 merged commit 1a32eb4 into chore/federation-backup Sep 25, 2025
51 checks passed
@rodrigok rodrigok deleted the chore/federation-backup-fix-upload branch September 25, 2025 20:56
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.

3 participants