Skip to content

chore: add indexes to events collection#336

Open
sampaiodiego wants to merge 1 commit intomainfrom
add-indexes-events-col
Open

chore: add indexes to events collection#336
sampaiodiego wants to merge 1 commit intomainfrom
add-indexes-events-col

Conversation

@sampaiodiego
Copy link
Member

@sampaiodiego sampaiodiego commented Feb 25, 2026

FGA-6

Summary by CodeRabbit

  • Chores
    • Optimized event data retrieval performance through database query improvements.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 25, 2026

Walkthrough

Two MongoDB composite indexes are created on the EventRepository collection during constructor initialization: one on room_id, nextEventId, depth, and createdAt; another on room_id and event type.

Changes

Cohort / File(s) Summary
MongoDB Index Creation
packages/federation-sdk/src/repositories/event.repository.ts
Added two composite indexes to the event collection: (1) on room_id, nextEventId, depth, and createdAt; (2) on room_id and event type, to optimize query performance during repository initialization.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested labels

type: chore

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and directly summarizes the primary change: adding indexes to the events collection in MongoDB.
Linked Issues check ✅ Passed The PR adds database indexes to optimize query performance for the events collection, which directly supports the scale load testing objectives by reducing query latency and improving database performance under stress.
Out of Scope Changes check ✅ Passed All changes are focused on adding indexes to the events collection as stated in the title; no unrelated modifications are present outside the stated objective.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


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-commenter
Copy link

Codecov Report

❌ Patch coverage is 91.66667% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 50.82%. Comparing base (7bb5a49) to head (3b8aca3).

Files with missing lines Patch % Lines
...ederation-sdk/src/repositories/event.repository.ts 91.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #336      +/-   ##
==========================================
+ Coverage   50.78%   50.82%   +0.04%     
==========================================
  Files          97       97              
  Lines       10949    10960      +11     
==========================================
+ Hits         5560     5570      +10     
- Misses       5389     5390       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 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.

@sampaiodiego sampaiodiego marked this pull request as ready for review March 2, 2026 12:53
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/federation-sdk/src/repositories/event.repository.ts`:
- Around line 12-23: The createIndex() calls in the constructor are
fire-and-forget which causes unhandled promise rejections and no startup
guarantee; remove the direct createIndex() calls from the constructor and add an
async initialization method (e.g., ensureIndexes() or init()) on the
EventRepository class that awaits each this.collection.createIndex(...) call (or
wraps them in Promise.all), surrounds them with try/catch to log or rethrow
errors, and then call await eventRepository.ensureIndexes() from app bootstrap
so indexes are created before queries run; alternatively, if you prefer minimal
change, at least append .catch(...) to each this.collection.createIndex(...) in
the class to handle errors and avoid unhandled rejections.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7bb5a49 and 3b8aca3.

📒 Files selected for processing (1)
  • packages/federation-sdk/src/repositories/event.repository.ts
📜 Review details
⏰ 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). (1)
  • GitHub Check: cubic · AI code reviewer

Comment on lines +12 to +23
) {
this.collection.createIndex({
'event.room_id': 1,
'nextEventId': 1,
'event.depth': 1,
'createdAt': 1,
});
this.collection.createIndex({
'event.room_id': 1,
'event.type': 1,
});
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Unhandled promises from createIndex() calls.

createIndex() returns a Promise<string> that is neither awaited nor has error handling attached. This means:

  1. Index creation errors will be silently swallowed as unhandled rejections.
  2. There's no guarantee indexes are ready before the first query executes.

Since this is a @singleton() managed by tsyringe, consider adding an explicit async init() method that the application can await during startup, or at minimum handle the promise rejection:

Option 1: Add error handling (minimal change)
 	constructor(
 		`@inject`('EventCollection')
 		private readonly collection: Collection<EventStore>,
 	) {
-		this.collection.createIndex({
+		this.collection.createIndex({
 			'event.room_id': 1,
 			'nextEventId': 1,
 			'event.depth': 1,
 			'createdAt': 1,
-		});
-		this.collection.createIndex({
+		}).catch((err) => console.error('Failed to create event index (room_id, nextEventId, depth, createdAt):', err));
+		this.collection.createIndex({
 			'event.room_id': 1,
 			'event.type': 1,
-		});
+		}).catch((err) => console.error('Failed to create event index (room_id, type):', err));
 	}
Option 2: Separate initialization method (recommended for startup guarantees)
 	constructor(
 		`@inject`('EventCollection')
 		private readonly collection: Collection<EventStore>,
-	) {
-		this.collection.createIndex({
-			'event.room_id': 1,
-			'nextEventId': 1,
-			'event.depth': 1,
-			'createdAt': 1,
-		});
-		this.collection.createIndex({
-			'event.room_id': 1,
-			'event.type': 1,
-		});
-	}
+	) {}
+
+	async ensureIndexes(): Promise<void> {
+		await Promise.all([
+			this.collection.createIndex({
+				'event.room_id': 1,
+				'nextEventId': 1,
+				'event.depth': 1,
+				'createdAt': 1,
+			}),
+			this.collection.createIndex({
+				'event.room_id': 1,
+				'event.type': 1,
+			}),
+		]);
+	}

Then call await eventRepository.ensureIndexes() during application bootstrap.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
) {
this.collection.createIndex({
'event.room_id': 1,
'nextEventId': 1,
'event.depth': 1,
'createdAt': 1,
});
this.collection.createIndex({
'event.room_id': 1,
'event.type': 1,
});
}
constructor(
`@inject`('EventCollection')
private readonly collection: Collection<EventStore>,
) {
this.collection.createIndex({
'event.room_id': 1,
'nextEventId': 1,
'event.depth': 1,
'createdAt': 1,
}).catch((err) => console.error('Failed to create event index (room_id, nextEventId, depth, createdAt):', err));
this.collection.createIndex({
'event.room_id': 1,
'event.type': 1,
}).catch((err) => console.error('Failed to create event index (room_id, type):', err));
}
Suggested change
) {
this.collection.createIndex({
'event.room_id': 1,
'nextEventId': 1,
'event.depth': 1,
'createdAt': 1,
});
this.collection.createIndex({
'event.room_id': 1,
'event.type': 1,
});
}
constructor(
`@inject`('EventCollection')
private readonly collection: Collection<EventStore>,
) {}
async ensureIndexes(): Promise<void> {
await Promise.all([
this.collection.createIndex({
'event.room_id': 1,
'nextEventId': 1,
'event.depth': 1,
'createdAt': 1,
}),
this.collection.createIndex({
'event.room_id': 1,
'event.type': 1,
}),
]);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/federation-sdk/src/repositories/event.repository.ts` around lines 12
- 23, The createIndex() calls in the constructor are fire-and-forget which
causes unhandled promise rejections and no startup guarantee; remove the direct
createIndex() calls from the constructor and add an async initialization method
(e.g., ensureIndexes() or init()) on the EventRepository class that awaits each
this.collection.createIndex(...) call (or wraps them in Promise.all), surrounds
them with try/catch to log or rethrow errors, and then call await
eventRepository.ensureIndexes() from app bootstrap so indexes are created before
queries run; alternatively, if you prefer minimal change, at least append
.catch(...) to each this.collection.createIndex(...) in the class to handle
errors and avoid unhandled rejections.

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 1 file

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants