fix(db): move persistMessage lookups and prepares inside the writer lock - #7551
Conversation
Walkthrough
ChangesMedia persistence transaction
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
app/lib/methods/handleMediaDownload.ts (1)
225-225: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDeclare the exported result type.
Declare
Promise<void>onpersistMessage. This keeps the exported API contract explicit.Proposed change
-export const persistMessage = async (messageId: string, uri: string, encryption: boolean, downloadUrl: string) => { +export const persistMessage = async ( + messageId: string, + uri: string, + encryption: boolean, + downloadUrl: string +): Promise<void> => {As per coding guidelines, add explicit type annotations to function parameters and return types.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/lib/methods/handleMediaDownload.ts` at line 225, Update the exported persistMessage function signature to explicitly declare a Promise<void> return type, while preserving its existing parameter annotations and implementation behavior.Source: Coding guidelines
app/lib/methods/handleMediaDownload.test.ts (1)
7-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winType the test doubles.
mockDbBatchandmakeRecorduseany.makeRecordanddeferredalso infer their return types. Define minimalPreparedRecordandDeferredinterfaces, then annotate these helper contracts.This keeps the concurrency test checked when the mocked WatermelonDB record shape changes.
As per coding guidelines, use TypeScript for type safety, add explicit type annotations to function parameters and return types, and prefer interfaces for object shapes.
Also applies to: 158-180
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@app/lib/methods/handleMediaDownload.test.ts` around lines 7 - 29, Replace the any-based test doubles with minimal PreparedRecord and Deferred interfaces, then update mockDbBatch, makeRecord, and deferred with explicit parameter and return-type annotations. Ensure the mocked database batch and record helpers use these interfaces so changes to the WatermelonDB record shape remain type-checked.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@app/lib/methods/handleMediaDownload.ts`:
- Around line 226-230: Update persistMessage and the getMessageById,
getThreadById, and getThreadMessageById lookup flow to use the captured db
instance inside db.write instead of database.active. Add a regression test that
switches the active database while the writer is queued and verifies records are
read from the captured database.
---
Nitpick comments:
In `@app/lib/methods/handleMediaDownload.test.ts`:
- Around line 7-29: Replace the any-based test doubles with minimal
PreparedRecord and Deferred interfaces, then update mockDbBatch, makeRecord, and
deferred with explicit parameter and return-type annotations. Ensure the mocked
database batch and record helpers use these interfaces so changes to the
WatermelonDB record shape remain type-checked.
In `@app/lib/methods/handleMediaDownload.ts`:
- Line 225: Update the exported persistMessage function signature to explicitly
declare a Promise<void> return type, while preserving its existing parameter
annotations and implementation behavior.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 87c843dc-98c1-40b6-a6be-ad443cf47a2d
📒 Files selected for processing (2)
app/lib/methods/handleMediaDownload.test.tsapp/lib/methods/handleMediaDownload.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
- GitHub Check: ESLint and Test / run-eslint-and-test
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions
Files:
app/lib/methods/handleMediaDownload.tsapp/lib/methods/handleMediaDownload.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers
Files:
app/lib/methods/handleMediaDownload.tsapp/lib/methods/handleMediaDownload.test.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{js,jsx,ts,tsx}: Format JavaScript and TypeScript code with Oxfmt using the repository configuration: tabs, single quotes, 130-character width, no trailing commas, omitted arrow-function parentheses where possible, and same-line brackets.
Follow Oxlint rules configured in.oxlintrc.json, including the import, React, Jest, TypeScript, and React Native plugins.
Files:
app/lib/methods/handleMediaDownload.tsapp/lib/methods/handleMediaDownload.test.ts
🧠 Learnings (2)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.
Applied to files:
app/lib/methods/handleMediaDownload.tsapp/lib/methods/handleMediaDownload.test.ts
📚 Learning: 2026-06-25T18:37:25.526Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.test.tsx:16-22
Timestamp: 2026-06-25T18:37:25.526Z
Learning: In Rocket.Chat ReactNative tests that mock selectors for `useAppSelector`, don’t require the mocked selector input to be typed as `IApplicationState` when the fixture only includes a partial Redux state slice (e.g., only `server` and `settings`). Requiring the full `IApplicationState` type in that scenario forces unsafe `as IApplicationState` casts and undermines type-safety. For these narrowly scoped selector-mock fixtures, use a less strict type (e.g., `any`) to keep the mock focused on the slice under test.
Applied to files:
app/lib/methods/handleMediaDownload.test.ts
Proposed changes
persistMessagelooked up the message, thread and thread message and calledprepareUpdateon each outsidedb.write, committing the batch in a separate write later. A concurrent writer touching any of those cached records during that window — an incoming message update in a busy room, for instance — left the prepared records stale, so the commit threwCannot update a record with pending changes(reaching Bugsnag) and the finished download never attached to its message: the attachment stayed in a to-download state until the next sync, and the user had to tap it again.The three lookups, the three
prepareUpdatecalls and thedb.batchnow all run inside a singledb.writecallback. The file and download work indownloadMediaFilestays outside the lock.Because the lookups now happen under the lock, the
if (batch.length)guard moved inside it and only wrapsdb.batch. A download for a message that no longer exists locally acquires the writer lock and does nothing, rather than skipping it — one no-op acquisition per completed download. There's a test pinning that no empty batch is committed.persistMessageis now exported so the regression test can drive it directly; it was only reachable throughdownloadMediaFile's real file-download path. Its signature and its single caller are unchanged.Adds one regression test: a concurrent writer races the record being updated and the batch must commit without a "pending changes" throw. It fails on the current code and passes with the fix.
Issue(s)
https://rocketchat.atlassian.net/browse/NATIVE-1466
How to test or reproduce
TZ=UTC pnpm test app/lib/methods/handleMediaDownload.test.ts— all pass; reverthandleMediaDownload.tsand the new test fails withCannot update a record with pending changestitle_linkwas saved, not just held in memoryTypes of changes
Checklist
Further comments
Summary by CodeRabbit