Skip to content

feat: report a per call http metric#310

Open
SoulPancake wants to merge 3 commits intomainfrom
feat/add-per-call-http-metric
Open

feat: report a per call http metric#310
SoulPancake wants to merge 3 commits intomainfrom
feat/add-per-call-http-metric

Conversation

@SoulPancake
Copy link
Copy Markdown
Member

@SoulPancake SoulPancake commented Mar 26, 2026

Description

Adds #118

What problem is being solved?

How is it being solved?

What changes are made to solve it?

References

Review Checklist

  • I have clicked on "allow edits by maintainers".
  • I have added documentation for new/changed functionality in this PR or in a PR to openfga.dev [Provide a link to any relevant PRs in the references section above]
  • The correct base branch is being used, if not main
  • I have added tests to validate that the change in functionality is working as expected

Summary by CodeRabbit

New Features

  • Added a new HTTP request count telemetry metric to track the total number of requests made to the FGA server. This metric enhances observability for monitoring API usage and request patterns. It is disabled by default and must be explicitly enabled through telemetry configuration.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 26, 2026

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f509430e-7b95-4752-ac0a-4fe0605cfc3b

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

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

This PR introduces a new fga-client.request.count counter metric to track HTTP requests made by the SDK. The metric is disabled by default and must be explicitly enabled through TelemetryConfiguration. It is emitted once per HTTP response in HttpRequestAttempt.

Changes

Cohort / File(s) Summary
Telemetry Metric Definition
src/main/java/dev/openfga/sdk/telemetry/Counters.java, src/main/java/dev/openfga/sdk/telemetry/Metrics.java
Added new REQUEST_COUNT constant to Counters and corresponding requestCount() method to Metrics class, following existing counter-lookup patterns.
Request Count Emission
src/main/java/dev/openfga/sdk/api/client/HttpRequestAttempt.java
Added telemetry metric emission call to record HTTP request count after response processing, using configured telemetry attributes.
Telemetry Configuration Tests
src/test/java/dev/openfga/sdk/api/configuration/TelemetryConfigurationTest.java, src/test/java/dev/openfga/sdk/telemetry/MetricsTest.java
Added tests verifying REQUEST_COUNT is disabled by default and can be explicitly enabled via TelemetryConfiguration.
Counter Metrics Tests
src/test/java/dev/openfga/sdk/telemetry/CountersTest.java
Added test verifying REQUEST_COUNT constant has correct name and description.
Documentation
CHANGELOG.md
Documented new fga-client.request.count counter metric in the unreleased section.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: report a per call http metric' accurately summarizes the main change—adding a per-call HTTP request count metric to the SDK's telemetry.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/add-per-call-http-metric

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.

@SoulPancake SoulPancake linked an issue Mar 26, 2026 that may be closed by this pull request
@codecov-commenter
Copy link
Copy Markdown

codecov-commenter commented Mar 26, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 38.05%. Comparing base (9d2fde1) to head (c615e98).

❌ Your project status has failed because the head coverage (38.05%) is below the target coverage (80.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##               main     #310      +/-   ##
============================================
+ Coverage     38.02%   38.05%   +0.03%     
- Complexity     1257     1259       +2     
============================================
  Files           198      198              
  Lines          7643     7646       +3     
  Branches        885      885              
============================================
+ Hits           2906     2910       +4     
  Misses         4598     4598              
+ Partials        139      138       -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.

@SoulPancake SoulPancake marked this pull request as ready for review March 27, 2026 05:58
@SoulPancake SoulPancake requested a review from a team as a code owner March 27, 2026 05:58
Copilot AI review requested due to automatic review settings March 27, 2026 05:58
@dosubot
Copy link
Copy Markdown

dosubot bot commented Mar 27, 2026

Related Documentation

1 document(s) may need updating based on files changed in this PR:

OpenFGA's Space

OpenTelemetry Metrics Integration
View Suggested Changes
@@ -4,13 +4,13 @@
 ---
 
 ### Supported Metrics
-The JavaScript and Java SDKs emit the following OpenTelemetry metrics by default. The Go SDK requires explicit configuration to enable `fga-client.http_request.duration`.
+The JavaScript SDK emits the following OpenTelemetry metrics by default. The Java SDK requires explicit configuration to enable `fga-client.request.count`. The Go SDK requires explicit configuration to enable `fga-client.http_request.duration`.
 
 | Metric Name                          | Type      | Enabled by Default | Description                                                                                  |
 |--------------------------------------|-----------|--------------------|----------------------------------------------------------------------------------------------|
 | `fga-client.request.duration`        | Histogram | Yes                | Total request time for FGA requests (milliseconds)                                           |
 | `fga-client.query.duration`          | Histogram | Yes                | Time taken by the FGA server to process and evaluate the request (milliseconds)              |
-| `fga-client.request.count`           | Counter   | Yes                | Total number of HTTP requests made by the SDK                                                |
+| `fga-client.request.count`           | Counter   | Yes (JS/Go), No (Java) | Total number of HTTP requests made to the FGA server                                         |
 | `fga-client.credentials.request`     | Counter   | Yes                | Total number of new token requests initiated using the Client Credentials flow               |
 | `fga-client.http_request.duration`   | Histogram | Yes (JS/Java), No (Go) | Time taken for a single HTTP request to complete, including retries (milliseconds)           |
 
@@ -116,6 +116,8 @@
 #### Java SDK
 Configure telemetry by supplying a custom `TelemetryConfiguration` when constructing the client. Map metrics to attributes to control which telemetry data is emitted.
 
+The `fga-client.request.count` metric is disabled by default in the Java SDK and must be explicitly enabled. To enable it, include `Counters.REQUEST_COUNT` in your telemetry configuration:
+
 ```java
 import dev.openfga.sdk.api.configuration.TelemetryConfiguration;
 import dev.openfga.sdk.telemetry.Attribute;
@@ -145,6 +147,7 @@
 
     Map<Metric, Map<Attribute, Optional<Object>>> metrics = new HashMap<>();
     metrics.put(Counters.CREDENTIALS_REQUEST, attributes);
+    metrics.put(Counters.REQUEST_COUNT, attributes);  // Explicitly enable request count metric
     metrics.put(Histograms.QUERY_DURATION, attributes);
     metrics.put(Histograms.REQUEST_DURATION, attributes);
 
@@ -272,6 +275,7 @@
 - The Java SDK supports both manual configuration and Java Agent (automatic instrumentation with zero code changes).
 - High-cardinality attributes (like `fga-client.user`) are disabled by default to avoid excessive costs with some metric collectors. Enable only if necessary.
 - In the Go SDK, `fga-client.http_request.duration` is disabled by default. Enable it through telemetry configuration if per-HTTP request monitoring is required.
+- In the Java SDK, `fga-client.request.count` is disabled by default and must be explicitly enabled via `TelemetryConfiguration`.
 
 ---
 

[Accept] [Decline]

Note: You must be authenticated to accept/decline updates.

How did I do? Any feedback?  Join Discord

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds a new OpenTelemetry counter intended to track HTTP request volume at the SDK’s HTTP layer, with supporting configuration/tests and changelog entry.

Changes:

  • Introduces Counters.REQUEST_COUNT (fga-client.request.count) and a Metrics.requestCount(...) helper.
  • Emits the new metric from HttpRequestAttempt alongside existing request-duration telemetry.
  • Adds tests asserting the metric is disabled by default and can be enabled explicitly; updates CHANGELOG.md.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/main/java/dev/openfga/sdk/telemetry/Counters.java Adds the new REQUEST_COUNT counter definition.
src/main/java/dev/openfga/sdk/telemetry/Metrics.java Adds requestCount(...) API to record the counter.
src/main/java/dev/openfga/sdk/api/client/HttpRequestAttempt.java Records the new counter during HTTP response processing.
src/test/java/dev/openfga/sdk/telemetry/CountersTest.java Verifies counter name/description.
src/test/java/dev/openfga/sdk/telemetry/MetricsTest.java Verifies requestCount is null unless explicitly configured.
src/test/java/dev/openfga/sdk/api/configuration/TelemetryConfigurationTest.java Verifies default config does not enable REQUEST_COUNT and that it can be enabled.
CHANGELOG.md Documents the newly added counter metric and that it’s disabled by default.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link
Copy Markdown
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.

Caution

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

⚠️ Outside diff range comments (1)
src/main/java/dev/openfga/sdk/api/client/HttpRequestAttempt.java (1)

172-223: ⚠️ Potential issue | 🟠 Major

requestCount is undercounted for HTTP error responses.

Line 222 emits the metric only in the success path, but Line 192 returns early for error responses, so failed HTTP responses are never counted. For a “total requests made” counter, this should increment once per response regardless of status.

💡 Proposed fix
 private CompletableFuture<ApiResponse<T>> processHttpResponse(
         HttpResponse<String> response, int retryNumber, Throwable previousError) {
+    addTelemetryAttributes(Attributes.fromHttpResponse(response, this.configuration.getCredentials()));
+
+    if (retryNumber > 0) {
+        addTelemetryAttribute(Attributes.HTTP_REQUEST_RESEND_COUNT, String.valueOf(retryNumber));
+    }
+
+    telemetry.metrics().requestCount(1L, this.getTelemetryAttributes());
+
     Optional<FgaError> fgaError = FgaError.getError(name, request, configuration, response, previousError);

     if (fgaError.isPresent()) {
         FgaError error = fgaError.get();
         int statusCode = error.getStatusCode();
@@
-    addTelemetryAttributes(Attributes.fromHttpResponse(response, this.configuration.getCredentials()));
-
-    if (retryNumber > 0) {
-        addTelemetryAttribute(Attributes.HTTP_REQUEST_RESEND_COUNT, String.valueOf(retryNumber));
-    }
-
     if (response.headers()
             .firstValue(FgaConstants.QUERY_DURATION_HEADER_NAME)
             .isPresent()) {
@@
     Double requestDuration = (double) (System.currentTimeMillis() - requestStarted);

     telemetry.metrics().requestDuration(requestDuration, this.getTelemetryAttributes());
-    telemetry.metrics().requestCount(1L, this.getTelemetryAttributes());

     return deserializeResponse(response)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/dev/openfga/sdk/api/client/HttpRequestAttempt.java` around
lines 172 - 223, processHttpResponse currently returns early on error (when
FgaError.isPresent()) so telemetry.metrics().requestCount(...) is only executed
on the success path; increment the request counter for every response by calling
telemetry.metrics().requestCount(1L, this.getTelemetryAttributes()) before the
FgaError check (or ensure it's invoked in the error branch prior to
returning/CompletableFuture.failedFuture), and likewise ensure request duration
(requestStarted -> now) is recorded for error responses if you want consistent
timing metrics; update references in processHttpResponse and
handleHttpErrorRetry as needed so every HTTP response triggers
telemetry.metrics().requestCount.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/main/java/dev/openfga/sdk/api/client/HttpRequestAttempt.java`:
- Around line 172-223: processHttpResponse currently returns early on error
(when FgaError.isPresent()) so telemetry.metrics().requestCount(...) is only
executed on the success path; increment the request counter for every response
by calling telemetry.metrics().requestCount(1L, this.getTelemetryAttributes())
before the FgaError check (or ensure it's invoked in the error branch prior to
returning/CompletableFuture.failedFuture), and likewise ensure request duration
(requestStarted -> now) is recorded for error responses if you want consistent
timing metrics; update references in processHttpResponse and
handleHttpErrorRetry as needed so every HTTP response triggers
telemetry.metrics().requestCount.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 532d1466-1bf5-43fd-87cf-863f2f20379d

📥 Commits

Reviewing files that changed from the base of the PR and between 9d2fde1 and 3ce00d5.

📒 Files selected for processing (7)
  • CHANGELOG.md
  • src/main/java/dev/openfga/sdk/api/client/HttpRequestAttempt.java
  • src/main/java/dev/openfga/sdk/telemetry/Counters.java
  • src/main/java/dev/openfga/sdk/telemetry/Metrics.java
  • src/test/java/dev/openfga/sdk/api/configuration/TelemetryConfigurationTest.java
  • src/test/java/dev/openfga/sdk/telemetry/CountersTest.java
  • src/test/java/dev/openfga/sdk/telemetry/MetricsTest.java

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.

Report a per-http call metric

4 participants