Skip to content

Conversation

@adityachoudhari26
Copy link
Contributor

@adityachoudhari26 adityachoudhari26 commented Apr 2, 2025

Summary by CodeRabbit

  • New Features
    • Integrated advanced telemetry capabilities to enhance system monitoring and logging.
    • Introduced an automated setup process ensuring observability is fully operational before background services start.
    • Enabled adaptive instrumentation based on the runtime environment to optimize performance and resource usage.
    • Added multiple new dependencies to support OpenTelemetry functionalities for improved observability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes integrate OpenTelemetry into the event worker service and the web service. Multiple new dependencies are added to the package.json files of both services to enhance observability. A new asynchronous registration function is introduced in the event worker, which is awaited in the entry file before initializing worker instances. Additionally, a new file is added to set up the OpenTelemetry NodeSDK for tracing and logging, with conditional dynamic loading based on the runtime environment.

Changes

File(s) Change Summary
apps/event-worker/package.json Added dependencies: @opentelemetry/auto-instrumentations-node (^0.52.1), @opentelemetry/exporter-logs-otlp-http (^0.54.2), @opentelemetry/exporter-trace-otlp-http (^0.54.2), @opentelemetry/resources (^1.27.0), @opentelemetry/sdk-logs (^0.54.2), @opentelemetry/sdk-node (^0.54.2), @opentelemetry/sdk-trace-base (^1.27.0), @opentelemetry/semantic-conventions (^1.27.0)
apps/event-worker/src/index.ts Imported register from ./instrumentation.js and added await register(); before initializing worker instances
apps/event-worker/src/instrumentation.ts Introduced a new async register function that conditionally imports the instrumentation module based on the environment variable NEXT_RUNTIME
apps/event-worker/src/instrumentation-node.ts Added a new file that sets up the OpenTelemetry NodeSDK for tracing and logging, initializing with a service name and configuring various instrumentations
apps/webservice/package.json Added dependencies: @opentelemetry/exporter-logs-otlp-http (^0.54.2), @opentelemetry/exporter-trace-otlp-http (^0.54.2), @opentelemetry/resources (^1.27.0), @opentelemetry/sdk-logs (^0.54.2), @opentelemetry/sdk-trace-base (^1.27.0), @opentelemetry/semantic-conventions (^1.27.0)

Sequence Diagram(s)

sequenceDiagram
    participant App as "Event Worker App"
    participant Index as "index.ts"
    participant Instr as "instrumentation.ts"
    participant InstrNode as "instrumentation-node.ts"

    App->>Index: Start application
    Index->>Instr: Call await register()
    Instr->>InstrNode: If NEXT_RUNTIME=="nodejs", dynamically import
    InstrNode-->>Instr: Complete SDK initialization
    Instr-->>Index: Return registration complete
    Index->>App: Initialize worker instances
Loading

Suggested reviewers

  • jsbroks

Poem

I'm just a bunny on a code spree,
Hopping through changes, wild and free.
OpenTelemetry lights my way,
Instruments on guard by night and day.
Code carrots crunch with glee,
A joyful hop in our PR spree!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 2

🧹 Nitpick comments (5)
apps/event-worker/src/instrumentation.ts (2)

1-4: Consider adding braces for better code maintainability

The conditional block without braces is valid, but adding them would improve code clarity and prevent future bugs if additional statements are added later.

export async function register() {
-  if (process.env.NEXT_RUNTIME === "nodejs")
-    await import("./instrumentation-node.js");
+  if (process.env.NEXT_RUNTIME === "nodejs") {
+    await import("./instrumentation-node.js");
+  }
}

1-4: Add error handling for dynamic import

The dynamic import could fail if the module doesn't exist or has errors. Consider adding error handling to gracefully handle such failures.

export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs")
-    await import("./instrumentation-node.js");
+    try {
+      await import("./instrumentation-node.js");
+    } catch (error) {
+      console.error("Failed to load OpenTelemetry instrumentation:", error);
+      // Optionally: throw error if you want to prevent app from starting with failed instrumentation
+    }
}
apps/event-worker/src/index.ts (1)

10-11: Consider adding error handling for the register call

If the OpenTelemetry registration fails, it could potentially prevent the application from starting. Consider adding error handling to ensure the application can still function without telemetry.

-await register();
+try {
+  await register();
+} catch (error) {
+  logger.error("Failed to register OpenTelemetry:", error);
+  // Application can continue without telemetry
+}
apps/event-worker/src/instrumentation-node.ts (2)

43-45: Ensure consistency in service name references

The service name "ctrlplane/event-worker" appears in two places. Consider extracting it to a constant to ensure consistency and ease of maintenance.

+const SERVICE_NAME = "ctrlplane/event-worker";

const sdk = new NodeSDK({
  resource: new Resource({
-    [ATTR_SERVICE_NAME]: "ctrlplane/event-worker",
+    [ATTR_SERVICE_NAME]: SERVICE_NAME,
  }),
  // ...
  instrumentations: [
    getNodeAutoInstrumentations({
      // ...
      "@opentelemetry/instrumentation-winston": {
        enabled: true,
        logHook: (span, record) => {
-          record["resource.service.name"] = "ctrlplane/event-worker";
+          record["resource.service.name"] = SERVICE_NAME;
        },
      },
      // ...

52-57: Use logger instead of console.log

Since the application uses a logger (visible in index.ts), consider using it here instead of console.log/console.error for consistency.

+import { logger } from "@ctrlplane/logger";

try {
  sdk.start();
-  console.log("Tracing initialized");
+  logger.info("OpenTelemetry tracing initialized");
} catch (error) {
-  console.error("Error initializing tracing", error);
+  logger.error("Error initializing OpenTelemetry tracing", error);
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cb3828a and a3b8c7e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • apps/event-worker/package.json (1 hunks)
  • apps/event-worker/src/index.ts (1 hunks)
  • apps/event-worker/src/instrumentation-node.ts (1 hunks)
  • apps/event-worker/src/instrumentation.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • apps/event-worker/src/instrumentation.ts
  • apps/event-worker/src/index.ts
  • apps/event-worker/src/instrumentation-node.ts
🧬 Code Definitions (1)
apps/event-worker/src/index.ts (1)
apps/event-worker/src/instrumentation.ts (1)
  • register (1-4)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build (linux/amd64)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
🔇 Additional comments (2)
apps/event-worker/src/index.ts (1)

3-3: LGTM: Good import of the register function

The import statement correctly references the instrumentation.js file.

apps/event-worker/src/instrumentation-node.ts (1)

13-50: Service configuration looks good with appropriately selected instrumentations

The OpenTelemetry SDK is properly configured with the correct service name and appropriate instrumentations enabled/disabled based on the event worker's requirements.

Comment on lines 31 to 32
"@opentelemetry/auto-instrumentations-node": "^0.52.1",
"@opentelemetry/sdk-node": "^0.54.2",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Consider aligning package versions

The two OpenTelemetry packages have different version ranges (0.52.1 vs 0.54.2). Consider aligning them if possible to ensure compatibility and make maintenance easier.


🌐 Web query:

Are @opentelemetry/auto-instrumentations-node@0.52.1 and @opentelemetry/sdk-node@0.54.2 compatible versions?

💡 Result:

The compatibility between @opentelemetry/auto-instrumentations-node@0.52.1 and @opentelemetry/sdk-node@0.54.2 is not guaranteed due to potential breaking changes in the experimental 0.x release phase, where minor version increments often introduce compatibility risks. Here's a structured analysis:


Key Considerations

  1. Experimental Phase Versioning:
    Pre-1.0 versions like 0.52.x and 0.54.x follow OpenTelemetry's versioning rules where minor versions (e.g., 0.52 → 0.54) may include breaking changes[9][10].

  2. Breaking Changes in 0.52.0:
    The 0.52.0 release introduced significant breaking changes, such as:

    • Simplified registerInstrumentations() API requiring instrumentations to be passed as an array[2].
    • Removal of convert() from exporters and changes to metric configuration[2].

    While 0.52.1 fixes bugs, it inherits these breaking changes from 0.52.0[2].

  3. SDK 0.54.x Context:
    SDK 0.54.2 is two minor versions ahead of 0.52.1. Given the experimental nature of the releases, subsequent versions like 0.54.x may further modify APIs or dependencies (e.g., environment variable handling or instrumentation registration), potentially creating incompatibilities with older auto-instrumentations packages[2][9].


Recommendation

  • Use Aligned Minor Versions: Pair @opentelemetry/sdk-node@0.54.x with auto-instrumentations from the same minor version range (e.g., 0.54.x).
  • Check Release Notes: Review the changelogs for SDK 0.54.00.54.2 to identify specific breaking changes that might affect 0.52.1[3][2].
  • Update Auto-Instrumentations: If upgrading the SDK, consider updating auto-instrumentations to a version tested with 0.54.x (e.g., 0.54.x or later)[4][7].

In summary, direct compatibility is unlikely without explicit confirmation from release notes. Aligning minor versions minimizes risks during the experimental pre-1.0 phase.

Citations:


Attention: Align OpenTelemetry Package Versions for Compatibility

The current configuration in apps/event-worker/package.json uses:

  • "@opentelemetry/auto-instrumentations-node": "^0.52.1"
  • "@opentelemetry/sdk-node": "^0.54.2"

Due to the experimental nature of pre-1.0 releases, minor version differences (e.g., 0.52.x vs. 0.54.x) can introduce breaking changes. This compatibility gap may lead to issues in instrumentation registration and API usage. To minimize risks, please consider updating the auto-instrumentations package to the 0.54.x series (or otherwise align both packages' minor versions) and review the release notes for any pertinent breaking changes.

Comment on lines +52 to +57
try {
sdk.start();
console.log("Tracing initialized");
} catch (error) {
console.error("Error initializing tracing", error);
}
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

Consider graceful shutdown of the OpenTelemetry SDK

The SDK is started correctly, but there's no mechanism to shut it down gracefully when the application terminates. Consider adding a shutdown function that can be called during the application's shutdown process.

try {
  sdk.start();
  console.log("Tracing initialized");
+  
+  // Register shutdown handler
+  process.on('beforeExit', async () => {
+    await sdk.shutdown();
+    console.log("Tracing terminated");
+  });
} catch (error) {
  console.error("Error initializing tracing", error);
}

Alternatively, you could export a shutdown function that can be called from the main shutdown handler in index.ts:

try {
  sdk.start();
  console.log("Tracing initialized");
} catch (error) {
  console.error("Error initializing tracing", error);
}

+export async function shutdownTracing() {
+  return sdk.shutdown();
+}
📝 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
try {
sdk.start();
console.log("Tracing initialized");
} catch (error) {
console.error("Error initializing tracing", error);
}
try {
sdk.start();
console.log("Tracing initialized");
// Register shutdown handler
process.on('beforeExit', async () => {
await sdk.shutdown();
console.log("Tracing terminated");
});
} catch (error) {
console.error("Error initializing tracing", error);
}
Suggested change
try {
sdk.start();
console.log("Tracing initialized");
} catch (error) {
console.error("Error initializing tracing", error);
}
try {
sdk.start();
console.log("Tracing initialized");
} catch (error) {
console.error("Error initializing tracing", error);
}
export async function shutdownTracing() {
return sdk.shutdown();
}

adityachoudhari26 and others added 3 commits April 2, 2025 11:11
Signed-off-by: Aditya Choudhari <48932219+adityachoudhari26@users.noreply.github.com>
@adityachoudhari26 adityachoudhari26 merged commit 2fc0c94 into main Apr 2, 2025
7 of 9 checks passed
@adityachoudhari26 adityachoudhari26 deleted the add-instrumentation-event-worker branch April 2, 2025 18:44
This was referenced Oct 15, 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.

2 participants