Skip to content

Conversation

@sampaiodiego
Copy link
Member

@sampaiodiego sampaiodiego commented Sep 24, 2025

Summary by CodeRabbit

  • Refactor

    • Standardized structured logging across federation services for clearer, more consistent logs.
    • Unified logger source to a central utility; removed redundant local logger usage.
  • Chores

    • Cleaned up dependencies by removing unused runtime packages and consolidating logger-related dependencies.
    • Reordered dependencies for consistency without changing functionality.
  • Note

    • No user-facing behavior changes; control flow and public APIs remain the same.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 24, 2025

Walkthrough

Dependencies and logging were reorganized: root removed pino deps; core added pino and dev pino-pretty; SDK reordered dependencies. SDK and core files switched to structured logging and, in SDK, adopted the core logger, removing the local logger module. No control flow or public API changes, except SDK logger module removal.

Changes

Cohort / File(s) Summary of changes
Dependency adjustments
package.json, packages/core/package.json, packages/federation-sdk/package.json
Root: removed pino, pino-pretty. Core: added pino runtime, pino-pretty dev. SDK: reordered emitter dependency (no net set change).
Structured logging refactor (SDK services)
packages/federation-sdk/src/services/event-authorization.service.ts, .../event-emitter.service.ts, .../event.service.ts, .../federation.service.ts, .../invite.service.ts, .../state.service.ts, packages/federation-sdk/src/queues/base.queue.ts
Replaced string/positional logger calls with structured objects (e.g., { msg, err, ... }). Unified logger source to @rocket.chat/federation-core where applicable. No control-flow changes.
Logger module removal (SDK)
packages/federation-sdk/src/utils/logger.ts
Removed local pino-based logger and createLogger export. Call sites switched to core logger. Public exports from this module eliminated.
Core logging tweaks
packages/core/src/utils/checkSignAndHashes.ts, packages/core/src/utils/makeRequest.ts
Switched an error log to structured object; removed an unused logger import. No behavioral changes.

Sequence Diagram(s)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • rodrigok
  • ggazzo

Poem

A bunny taps logs with delicate paws,
Turns strings to shapes—structured clauses and cause.
The local burrow’s torch now shared from the core,
Dependencies trimmed, the garden’s not sore.
Hippity-hop, the console sings pretty—
JSON carrots in a neat little city. 🥕🐇

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 pull request title succinctly captures the core changes of updating logger usage patterns and adjusting project dependencies, which are the main modifications across package configuration and code. It clearly signals a non-functional chore update and references both logging and dependency fixes. The phrasing is concise and specific enough for team members to understand the change 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 fix-logger

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 20.00000% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.94%. Comparing base (ee01e15) to head (13b282c).

Files with missing lines Patch % Lines
...ages/federation-sdk/src/services/config.service.ts 0.00% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #215      +/-   ##
==========================================
- Coverage   80.99%   80.94%   -0.06%     
==========================================
  Files          63       63              
  Lines        4693     4696       +3     
==========================================
  Hits         3801     3801              
- Misses        892      895       +3     

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

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

Caution

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

⚠️ Outside diff range comments (2)
packages/federation-sdk/src/services/config.service.ts (1)

50-51: Schema/interface mismatch and unused config: make signingKeyPath optional.

Interface marks it optional, schema requires it, and loadSigningKey ignores it. Make optional and actually use it (see below).

-	signingKeyPath: z.string(),
+	signingKeyPath: z.string().optional(),
packages/federation-sdk/src/services/invite.service.ts (1)

94-94: Avoid unhandled promise rejections when fire-and-forgetting.
Detached promises should log failures to prevent silent drops.

-			void federationService.sendEventToAllServersInRoom(inviteEvent);
+			void federationService
+				.sendEventToAllServersInRoom(inviteEvent)
+				.catch((err) => this.logger.error({ err, eventId: inviteEvent.eventId, roomId }, 'Failed to broadcast invite event'));
-		void federationService.sendEventToAllServersInRoom(inviteEvent);
+		void federationService
+			.sendEventToAllServersInRoom(inviteEvent)
+			.catch((err) => this.logger.error({ err, eventId: inviteEvent.eventId, roomId }, 'Failed to broadcast invite event'));

Also applies to: 120-120

🧹 Nitpick comments (19)
packages/federation-sdk/package.json (1)

18-28: Consider alphabetizing dependencies to reduce diff churn

Optional: keeping the dependencies list alphabetized makes future diffs smaller and easier to review.

packages/federation-sdk/src/services/config.service.ts (5)

85-88: Log error with proper structure (avoid 'msg' field and include the Error object).

Preserve stack/causes and keep the message in the logger’s message slot. Example pino-style:

-				this.logger.error({
-					msg: 'Configuration validation failed:',
-					details: error.errors,
-				});
+				this.logger.error(
+					{ err: error, details: error.errors },
+					'Configuration validation failed',
+				);

142-147: Honor signingKeyPath and use structured info logs.

Currently ignores signingKeyPath and interpolates strings. Use provided path when present and structured logging.

-			const signingKeyPath = `${CONFIG_FOLDER}/${this.config.serverName}.signing.key`;
-			this.logger.info(`Loading signing key from ${signingKeyPath}`);
+			const signingKeyPath =
+				this.config.signingKeyPath ?? `${CONFIG_FOLDER}/${this.config.serverName}.signing.key`;
+			this.logger.info({ signingKeyPath }, 'Loading signing key');
 			const keys = await getKeyPair({ signingKeyPath });
-			this.logger.info(
-				`Successfully loaded signing key for server ${this.config.serverName}`,
-			);
+			this.logger.info({ serverName: this.config.serverName }, 'Successfully loaded signing key');

150-153: Preserve error stack in logs.

Avoid stringifying errors; log the Error instance to keep stack and cause.

-			const errorMessage =
-				error instanceof Error ? error.message : 'Unknown error';
-			this.logger.error(`Failed to load signing key: ${errorMessage}`);
+			const err = error instanceof Error ? error : new Error(String(error));
+			this.logger.error({ err }, 'Failed to load signing key');

129-133: Unreachable fallback and missing guard for empty keys.

Template string is always truthy; default never used. Also guard empty array.

-		const signingKeys = await this.getSigningKey();
-		const signingKey = signingKeys[0];
-		return `${signingKey.algorithm}:${signingKey.version}` || 'ed25519:1';
+		const signingKeys = await this.getSigningKey();
+		const signingKey = signingKeys?.[0];
+		if (!signingKey?.algorithm || !signingKey?.version) {
+			return 'ed25519:1';
+		}
+		return `${signingKey.algorithm}:${signingKey.version}`;

135-138: Guard against missing privateKey to avoid runtime crash.

-		const signingKeys = await this.getSigningKey();
-		return toUnpaddedBase64(signingKeys[0].privateKey);
+		const signingKeys = await this.getSigningKey();
+		const signingKey = signingKeys?.[0];
+		if (!signingKey?.privateKey) {
+			throw new Error('No signing key available');
+		}
+		return toUnpaddedBase64(signingKey.privateKey);
packages/federation-sdk/src/services/event-emitter.service.ts (1)

6-6: Use a scoped logger via createLogger for consistency and context

Other services use createLogger(''). Standardize here and include the service name in logs.

Apply:

-import { logger } from '@rocket.chat/federation-core';
+import { createLogger } from '@rocket.chat/federation-core';
-		logger.debug({ msg: `Event emitted: ${event}`, event, data });
+		this.logger.debug({ event, data }, `Event emitted: ${String(event)}`);

Add the scoped logger on the class (outside these ranges):

private readonly logger = createLogger('EventEmitterService');

Also applies to: 33-33

packages/federation-sdk/src/services/federation.service.ts (1)

278-281: Good move to structured errors; align remaining catch blocks to the same shape

These use { msg, err }, which is consistent with pino conventions. Please update earlier catches (e.g., makeJoin, sendJoin, sendTransaction, sendEvent, getEvent, getState, getStateIds, getVersion) that still log strings and stacks to use the same structured shape for uniformity and better parsing.

Also applies to: 315-318

packages/federation-sdk/src/services/event-authorization.service.ts (1)

362-363: Prefer err key for Error objects to match the rest of the codebase

Other sites use err; standardize the field name for tooling/serialization consistency.

-			this.logger.warn({ msg: `Invalid ACL pattern: ${pattern}`, error });
+			this.logger.warn({ msg: `Invalid ACL pattern: ${pattern}`, err: error });
packages/federation-sdk/src/services/event.service.ts (2)

179-183: Use err instead of error and minimize heavy payloads in error logs

  • Rename error to err for consistency with other logs/tools.
  • Optional: logging the entire event can be noisy; consider logging identifiers (eventId/type) unless you need full payloads for triage.
-						this.logger.error({
-							msg: 'Event validation failed',
-							event,
-							error: err,
-						});
+						this.logger.error({
+							msg: 'Event validation failed',
+							event, // consider reducing to { id: generateId(event), type: event.type }
+							err: err,
+						});

721-725: LGTM: consistent structured logging across state/auth paths

These follow the { msg, err } convention and keep messages uniform. Consider rolling this style out to remaining non-structured logs in this file (e.g., EDU processing) for full consistency.

Also applies to: 733-737, 783-787, 799-803, 811-815

packages/federation-sdk/src/queues/base.queue.ts (1)

35-38: Use Pino’s structured parameters for logging errors

Replace the object-with-msg usage with a separate message and context object:

- logger.error({
-   msg: `${this.constructor.name}: Error processing item`,
-   err,
- });
+ logger.error(
+   { err, queue: this.constructor.name },
+   'Error processing item',
+ );
packages/federation-sdk/src/services/invite.service.ts (5)

41-41: Prefer structured logging over string interpolation.
Easier to query logs and avoids coupling message formatting to code.

-		this.logger.debug(`Inviting ${userId} to room ${roomId}`);
+		this.logger.debug({ userId, roomId, sender, isDirectMessage }, 'Inviting user to room');

181-181: Replace console.error with the centralized logger.
Aligns with the PR goal and preserves structured logging.

-			console.error(e);
+			this.logger.warn({ err: e, roomId, eventId }, 'Invite persistence skipped; local room state not present yet');

148-149: Improve error detail for easier debugging.
Include both expected and received IDs.

-			throw new Error(`Invalid eventId ${eventId}`);
+			throw new Error(`Invalid eventId: expected ${inviteEvent.eventId}, got ${eventId}`);

102-102: Typo in comment: “room” → “server”.
Minor doc polish.

-		// invited user from another room
+		// invited user from another server

77-81: Make server extraction robust to additional colons.
Use first-colon index instead of last-segment .pop().

-		const invitedServer = inviteEvent.stateKey?.split(':').pop();
+		const sk = inviteEvent.stateKey;
+		const invitedServer = sk && sk.includes(':') ? sk.slice(sk.indexOf(':') + 1) : undefined;
-		const residentServer = roomId.split(':').pop();
+		const residentServer = roomId.includes(':') ? roomId.slice(roomId.indexOf(':') + 1) : undefined;

Also applies to: 136-139

packages/core/src/utils/checkSignAndHashes.ts (1)

43-45: Use Pino’s standard signature and add minimal context; avoid logging full hashes

Prefer passing the message as the second argument and include origin; trim hashes to keep logs small.

-		logger.error({ msg: 'Invalid hash', hash, expectedHash });
+		logger.error(
+			{ origin, hash: hash?.slice(0, 12), expectedHash: expectedHash?.slice(0, 12) },
+			'Invalid hash',
+		);
packages/core/package.json (1)

21-22: pino version consistency is confirmed; add Node.js engine constraint

  • Only packages/core/package.json includes pino@^9.11.0 — no duplicates.
  • Add an engines.node field (e.g. ">=18") in package.json (root or relevant packages) to enforce Node.js compatibility with pino v9.
📜 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 ee01e15 and 13b282c.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • package.json (0 hunks)
  • packages/core/package.json (1 hunks)
  • packages/core/src/utils/checkSignAndHashes.ts (1 hunks)
  • packages/core/src/utils/makeRequest.ts (0 hunks)
  • packages/federation-sdk/package.json (1 hunks)
  • packages/federation-sdk/src/queues/base.queue.ts (1 hunks)
  • packages/federation-sdk/src/services/config.service.ts (1 hunks)
  • packages/federation-sdk/src/services/event-authorization.service.ts (2 hunks)
  • packages/federation-sdk/src/services/event-emitter.service.ts (2 hunks)
  • packages/federation-sdk/src/services/event.service.ts (5 hunks)
  • packages/federation-sdk/src/services/federation.service.ts (2 hunks)
  • packages/federation-sdk/src/services/invite.service.ts (1 hunks)
  • packages/federation-sdk/src/services/state.service.ts (3 hunks)
  • packages/federation-sdk/src/utils/logger.ts (0 hunks)
💤 Files with no reviewable changes (3)
  • packages/core/src/utils/makeRequest.ts
  • packages/federation-sdk/src/utils/logger.ts
  • package.json
🔇 Additional comments (8)
packages/federation-sdk/package.json (1)

19-19: Move-only dependency change looks good

Reordering @rocket.chat/emitter within dependencies has no functional impact. Safe change.

packages/federation-sdk/src/services/config.service.ts (1)

76-83: Approve structured logging and key-loading flow createLogger returns a pino child logger supporting object+message calls, and getKeyPair resolves to a SigningKey array.

packages/federation-sdk/src/services/event-authorization.service.ts (1)

238-239: LGTM: structured error with context

Consistent with the new logging pattern.

packages/federation-sdk/src/services/event.service.ts (1)

233-236: LGTM: structured validation error logs

Good shape and field names; easy to parse and correlate.

Also applies to: 244-246

packages/federation-sdk/src/services/state.service.ts (3)

1-1: LGTM: centralized logger and signEvent import

Aligns with the repo-wide logger consolidation.


156-156: LGTM: structured error with context

Clear message and machine-parsable fields.


641-643: LGTM: structured debug with explicit msg

Good contextualization while keeping fields queryable.

packages/core/package.json (1)

26-26: pino-pretty only in dev is correct

Keeping pino-pretty as a devDependency avoids bundling it in production. LGTM.

If other packages still have pino-pretty, consider consolidating it here or at the root, depending on where it’s used. The script above will list all occurrences.

HttpException,
HttpStatus,
} from '@rocket.chat/federation-core';
import { EventBase, createLogger } from '@rocket.chat/federation-core';
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

🧩 Analysis chain

Centralizing logger import: looks good. Please verify no leftover local logger/console usage.
Great switch to the core logger.

Run to confirm the SDK no longer imports a local logger or uses console/pino directly:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Searching for legacy local logger imports…"
rg -nP -C2 "(from|require\()\\s*['\"][^'\\\"]*utils/logger['\\\"]" --type=ts --type=tsx || true

echo
echo "Searching for direct pino usage…"
rg -nP -C2 "\\bpino\\b" -g "!**/node_modules/**" --type=ts --type=tsx || true

echo
echo "Searching for console.* calls (exclude tests)…"
rg -nP -C1 "\\bconsole\\.(log|info|warn|error|debug)\\s*\\(" --type=ts --type=tsx -g "!**/test/**" || true

Length of output: 208


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Searching for legacy local logger imports…"
rg -nP -C2 "(?:from|require\()\\s*['\"][^'\"]*utils/logger['\"]" -g "*.{ts,tsx}" -g "!node_modules/**" || true

echo
echo "Searching for direct pino usage…"
rg -nP -C2 "\\bpino\\b" -g "*.{ts,tsx}" -g "!node_modules/**" || true

echo
echo "Searching for console.* calls (exclude tests)…"
rg -nP -C1 "\\bconsole\\.(?:log|info|warn|error|debug)\\s*\\(" -g "*.{ts,tsx}" -g "!**/test/**" || true

Length of output: 3839


Eliminate direct pino imports and console calls across the SDK

  • packages/federation-sdk/src/server-discovery/discovery.ts:2 – remove import type { Logger } from 'pino'; use the core-exported logger API.
  • packages/federation-sdk/src/services/invite.service.ts:181 – replace console.error(e) with logger.error(e).
  • packages/federation-sdk/src/services/room.service.ts:911–912 – replace console.log(…) with the appropriate logger.debug(…).
🤖 Prompt for AI Agents
In packages/federation-sdk/src/services/invite.service.ts around line 181, there
is a direct console.error(e) call; replace it with the SDK logger: ensure an
instance is created from the core createLogger (or reuse the file's existing
logger) and call logger.error(e) instead of console.error(e); if no logger
instance exists in this module/class, create one via
createLogger('federation:invite-service') at the top and use that instance for
the error call.

@sampaiodiego sampaiodiego merged commit 3b47d37 into main Sep 24, 2025
3 checks passed
@sampaiodiego sampaiodiego deleted the fix-logger branch September 24, 2025 17:19
@coderabbitai coderabbitai bot mentioned this pull request Oct 6, 2025
@coderabbitai coderabbitai bot mentioned this pull request Oct 16, 2025
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