Skip to content

Enable prisma metrics and add them to the /metrics endpoint #2111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2025

Conversation

ericallam
Copy link
Member

No description provided.

Copy link
Contributor

coderabbitai bot commented May 27, 2025

Walkthrough

The changes enhance the metrics route loader to include optional authentication based on an environment variable. If the TRIGGER_METRICS_AUTH_PASSWORD is set, the loader verifies the Authorization header and returns a 401 Unauthorized response if authentication fails. Upon successful authentication, it asynchronously fetches Prometheus-formatted metrics from the Prisma client and concatenates them with existing core metrics before returning the combined result. Additionally, the Prisma schema generator configuration is updated to add the "metrics" preview feature alongside "tracing". No changes were made to function signatures or schema models.

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c571c5e and d4813a2.

📒 Files selected for processing (2)
  • apps/webapp/app/routes/metrics.ts (1 hunks)
  • internal-packages/database/prisma/schema.prisma (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/webapp/app/routes/metrics.ts (2)
apps/webapp/app/db.server.ts (1)
  • prisma (100-100)
apps/webapp/app/metrics.server.ts (1)
  • metricsRegister (5-5)
⏰ Context from checks skipped due to timeout of 90000ms (25)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (10, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (9, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 10)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/webapp/app/routes/metrics.ts (1)

2-2: LGTM!

The import is correctly added to access the Prisma client for metrics collection.

@@ -7,7 +7,7 @@ datasource db {
generator client {
provider = "prisma-client-js"
binaryTargets = ["native", "debian-openssl-1.1.x"]
previewFeatures = ["tracing"]
previewFeatures = ["tracing", "metrics"]
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

Verify the stability of the Prisma metrics preview feature.

Adding the "metrics" preview feature enables Prisma client metrics collection. Since preview features can have breaking changes and may not be production-ready, ensure this feature is stable enough for your use case.


🌐 Web query:

What is the current status and stability of Prisma's "metrics" preview feature? Is it production-ready?

💡 Result:

As of May 2025, Prisma has announced plans to discontinue the "metrics" preview feature between June and August 2025 due to low usage and compatibility issues with the Query Compiler. (github.com) Consequently, the "metrics" feature is not considered production-ready.

For monitoring and observability, Prisma recommends using the "tracing" feature, which provides detailed insights into database interactions and is fully supported. (prismagraphql.com)

Citations:


Remove the “metrics” preview feature – it’s unstable and slated for removal

Prisma has announced that the “metrics” preview feature will be discontinued between June and August 2025 and is not production-ready. To avoid future breakages, remove it from your schema and rely on the fully supported “tracing” feature for observability.

Please update:

  • internal-packages/database/prisma/schema.prisma (line 10)
- previewFeatures = ["tracing", "metrics"]
+ previewFeatures = ["tracing"]
📝 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
previewFeatures = ["tracing", "metrics"]
previewFeatures = ["tracing"]
🤖 Prompt for AI Agents
In internal-packages/database/prisma/schema.prisma at line 10, remove the
"metrics" entry from the previewFeatures array because it is an unstable Prisma
preview feature slated for removal. Keep only the "tracing" feature to ensure
stability and avoid future breakages related to the deprecated "metrics"
feature.

import { metricsRegister } from "~/metrics.server";

export async function loader({ request }: LoaderFunctionArgs) {
return new Response(await metricsRegister.metrics(), {
const prismaMetrics = await prisma.$metrics.prometheus();
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

Add error handling for the Prisma metrics call.

The call to prisma.$metrics.prometheus() could potentially fail, which would cause the entire metrics endpoint to fail. Consider adding error handling to gracefully degrade when Prisma metrics are unavailable.

-  const prismaMetrics = await prisma.$metrics.prometheus();
+  let prismaMetrics = "";
+  try {
+    prismaMetrics = await prisma.$metrics.prometheus();
+  } catch (error) {
+    console.error("Failed to fetch Prisma metrics:", error);
+    // Continue with empty prisma metrics to avoid breaking the endpoint
+  }
🤖 Prompt for AI Agents
In apps/webapp/app/routes/metrics.ts at line 6, the call to
prisma.$metrics.prometheus() lacks error handling, which can cause the metrics
endpoint to fail if the call throws an error. Wrap this call in a try-catch
block to catch any exceptions, and in the catch block, handle the error
gracefully by either returning a fallback response or logging the error and
returning an empty or default metrics response to ensure the endpoint remains
functional.

Comment on lines +7 to +9
const coreMetrics = await metricsRegister.metrics();

return new Response(coreMetrics + prismaMetrics, {
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

Verify the metrics concatenation approach.

Simple string concatenation of Prometheus metrics may not be the correct approach. Prometheus metrics typically require proper formatting, and there could be conflicts between metric names or improper line endings.

Consider using a proper Prometheus metrics library for combining metrics:

-  return new Response(coreMetrics + prismaMetrics, {
+  // Ensure proper line separation between metric sets
+  const combinedMetrics = [coreMetrics.trim(), prismaMetrics.trim()]
+    .filter(Boolean)
+    .join('\n');
+  
+  return new Response(combinedMetrics, {

🏁 Script executed:

#!/bin/bash
# Description: Search for existing Prometheus metrics handling patterns in the codebase
# Expected: Find examples of how metrics are properly combined or formatted

# Search for other prometheus metrics usage
rg -A 5 -B 5 "prometheus|metrics" --type typescript --type javascript

# Look for existing metrics formatting or combination logic
ast-grep --pattern 'metricsRegister.$_($$$)'

Length of output: 244


🏁 Script executed:

#!/bin/bash
# Locate prismaMetrics usage and display the metrics route implementation
grep -n "prismaMetrics" apps/webapp/app/routes/metrics.ts || true
sed -n '1,200p' apps/webapp/app/routes/metrics.ts

Length of output: 693


Ensure proper Prometheus metrics formatting when combining outputs

Directly concatenating two metrics strings can lead to missing newline separators or duplicated HELP/TYPE directives, which breaks the Prometheus exposition format. It’s safer to trim each output and join them with a newline.

• File: apps/webapp/app/routes/metrics.ts
Update the loader’s return to combine and format both metric strings.

Suggested diff:

   const prismaMetrics = await prisma.$metrics.prometheus();
   const coreMetrics = await metricsRegister.metrics();
-
-  return new Response(coreMetrics + prismaMetrics, {
+  // Combine metrics outputs with proper newline separation
+  const combinedMetrics = [coreMetrics.trim(), prismaMetrics.trim()]
+    .filter(Boolean)
+    .join('\n');
+
+  return new Response(combinedMetrics, {
     headers: {
       "Content-Type": metricsRegister.contentType,
     },
   });
📝 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
const coreMetrics = await metricsRegister.metrics();
return new Response(coreMetrics + prismaMetrics, {
const prismaMetrics = await prisma.$metrics.prometheus();
const coreMetrics = await metricsRegister.metrics();
// Combine metrics outputs with proper newline separation
const combinedMetrics = [coreMetrics.trim(), prismaMetrics.trim()]
.filter(Boolean)
.join('\n');
return new Response(combinedMetrics, {
headers: {
"Content-Type": metricsRegister.contentType,
},
});
🤖 Prompt for AI Agents
In apps/webapp/app/routes/metrics.ts around lines 7 to 9, the code concatenates
Prometheus metrics strings directly, which can cause formatting issues such as
missing newlines or duplicated HELP/TYPE directives. To fix this, trim both
metrics strings individually and join them with a single newline character
before returning the combined response, ensuring proper Prometheus exposition
format.

Copy link

changeset-bot bot commented May 27, 2025

⚠️ No Changeset found

Latest commit: 6726bf8

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.

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

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

♻️ Duplicate comments (2)
apps/webapp/app/routes/metrics.ts (2)

16-16: Add error handling for the Prisma metrics call.

This is the same issue raised in the previous review - the Prisma metrics call still lacks proper error handling.


19-19: Ensure proper Prometheus metrics formatting when combining outputs.

This is the same metrics concatenation issue raised in the previous review - the formatting concerns remain unaddressed.

🧹 Nitpick comments (2)
apps/webapp/app/routes/metrics.ts (2)

6-14: Consider using constant-time comparison for password verification.

The authentication logic is functional, but using direct string comparison for password verification can be vulnerable to timing attacks.

Consider using a constant-time comparison:

- if (auth !== `Bearer ${authPassword}`) {
+ const crypto = require('crypto');
+ const expectedAuth = `Bearer ${authPassword}`;
+ if (auth?.length !== expectedAuth.length || 
+     !crypto.timingSafeEqual(Buffer.from(auth), Buffer.from(expectedAuth))) {
   return new Response("Unauthorized", { status: 401 });
 }

16-17: Optimize metrics fetching with parallel execution.

The metrics are fetched sequentially, but they could run in parallel since they're independent operations.

- const prismaMetrics = await prisma.$metrics.prometheus();
- const coreMetrics = await metricsRegister.metrics();
+ const [prismaMetrics, coreMetrics] = await Promise.all([
+   prisma.$metrics.prometheus(),
+   metricsRegister.metrics()
+ ]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4813a2 and 6726bf8.

📒 Files selected for processing (1)
  • apps/webapp/app/routes/metrics.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/webapp/app/routes/metrics.ts (2)
apps/webapp/app/db.server.ts (1)
  • prisma (100-100)
apps/webapp/app/metrics.server.ts (1)
  • metricsRegister (5-5)
⏰ Context from checks skipped due to timeout of 90000ms (25)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (10, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (9, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/webapp/app/routes/metrics.ts (1)

2-2: LGTM - Correct import for Prisma metrics.

The import is properly aligned with the singleton pattern used in the codebase.

@ericallam ericallam merged commit 0410316 into main May 27, 2025
33 checks passed
@ericallam ericallam deleted the ea-branch-73 branch May 27, 2025 12:28
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