-
Notifications
You must be signed in to change notification settings - Fork 480
feat(request-cost): publish aggregate token telemetry to external endpoint #35749
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
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
bd61563
feat(request-cost): publish aggregate token telemetry to external end…
wezell dfafca1
fix(request-cost): address Claude AI review feedback on PR #35749
wezell 81aff38
fix(request-cost): second round of review fixes — continuous telemetr…
wezell b2c6fcf
fix(request-cost): close whitespace-token auth-strip gap + clearer fa…
wezell 0a45855
docs(request-cost): note intentional non-atomic counter read in logRe…
wezell 8c8c4af
fix(request-cost): warn-once on plain-http URL + split fail-log dedup…
wezell 0f2f5bf
refactor(request-cost): rename snapshot field environmentId -> serverId
wezell 66efc57
fix(request-cost): clamp denominator, drop redundant Content-Type, re…
wezell 017e76e
fix(request-cost): tighten Jackson visibility, coalesce null cluster/…
wezell aed6477
chore(ai-workflows): add wezell to backend reviewer pilot allowlist
wezell 885ed15
Revert "chore(ai-workflows): add wezell to backend reviewer pilot all…
wezell bcf5e09
Merge branch 'main' into feat/request-cost-publisher
wezell d6b02a6
Potential fix for pull request finding
wezell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
172 changes: 172 additions & 0 deletions
172
dotCMS/src/main/java/com/dotcms/cost/RequestCostPublisher.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| package com.dotcms.cost; | ||
|
|
||
| import com.dotcms.concurrent.DotConcurrentFactory; | ||
| import com.dotcms.http.CircuitBreakerUrl; | ||
| import com.dotmarketing.util.Config; | ||
| import com.dotmarketing.util.Logger; | ||
| import com.dotmarketing.util.UtilMethods; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import java.net.URI; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.concurrent.atomic.AtomicBoolean; | ||
| import javax.enterprise.context.ApplicationScoped; | ||
|
|
||
| /** | ||
| * Ships {@link RequestCostSnapshot} payloads to an external REST endpoint on each tick of | ||
| * {@link RequestCostApiImpl#logRequestCost()}. | ||
| * | ||
| * <p>Activates implicitly when both {@code REQUEST_COST_PUSH_URL} and | ||
| * {@code REQUEST_COST_PUSH_TOKEN} are set. Failures are rate-limited warnings and the snapshot | ||
| * is dropped — this is observational telemetry, not durable accounting.</p> | ||
| * | ||
| * <p>Config keys: | ||
| * <ul> | ||
| * <li>{@code REQUEST_COST_PUSH_URL} (presence with token activates the publisher)</li> | ||
| * <li>{@code REQUEST_COST_PUSH_TOKEN} (bearer token; presence with url activates the publisher)</li> | ||
| * <li>{@code REQUEST_COST_PUSH_TIMEOUT_MS} (default 5000)</li> | ||
| * </ul> | ||
| * </p> | ||
| */ | ||
| @ApplicationScoped | ||
| public class RequestCostPublisher { | ||
|
|
||
| private static final ObjectMapper MAPPER = new ObjectMapper(); | ||
| private static final int FAIL_LOG_INTERVAL_MS = 10 * 60 * 1000; | ||
| private final AtomicBoolean httpSchemeWarned = new AtomicBoolean(false); | ||
|
|
||
| public boolean isEnabled() { | ||
| // Use the sanitized token in the gate so a whitespace-or-CRLF-only token | ||
| // doesn't activate the publisher and cause an unauthenticated POST. | ||
| return UtilMethods.isSet(getUrl()) && UtilMethods.isSet(sanitizeHeaderValue(getToken())); | ||
| } | ||
|
|
||
| private String getUrl() { | ||
| return Config.getStringProperty("REQUEST_COST_PUSH_URL", null); | ||
| } | ||
|
|
||
| private String getToken() { | ||
| return Config.getStringProperty("REQUEST_COST_PUSH_TOKEN", null); | ||
| } | ||
|
|
||
| private long getTimeoutMs() { | ||
| return Config.getLongProperty("REQUEST_COST_PUSH_TIMEOUT_MS", 5_000L); | ||
| } | ||
|
|
||
| /** | ||
| * Submits the snapshot to {@link DotConcurrentFactory}'s default submitter so the HTTP POST | ||
| * never blocks the request-cost monitor scheduler. Returns immediately. Transport errors are | ||
| * logged at most once every 10 minutes and the snapshot is dropped. | ||
| */ | ||
| public void publish(final RequestCostSnapshot snapshot) { | ||
| if (!isEnabled()) { | ||
| return; | ||
| } | ||
| DotConcurrentFactory.getInstance().getSubmitter().submit(() -> post(snapshot)); | ||
| } | ||
|
|
||
| private void post(final RequestCostSnapshot snapshot) { | ||
| final String url = getUrl(); | ||
| final String token = sanitizeHeaderValue(getToken()); | ||
| // Re-check both pieces — config may have been cleared between submit and execute, and | ||
| // posting without an Authorization header is a worse failure mode than not posting at all. | ||
| if (!UtilMethods.isSet(url) || !UtilMethods.isSet(token)) { | ||
| return; | ||
| } | ||
| warnOncePlainHttp(url); | ||
| try { | ||
| // CircuitBreakerUrl sniffs the rawData and applies Content-Type automatically when | ||
| // the payload starts with '{', so we don't set it explicitly (would risk a duplicate | ||
| // header on some Apache HttpClient versions). | ||
| final Map<String, String> headers = new HashMap<>(); | ||
| headers.put("Authorization", "Bearer " + token); | ||
|
wezell marked this conversation as resolved.
|
||
|
|
||
| final CircuitBreakerUrl call = CircuitBreakerUrl.builder() | ||
| .setMethod(CircuitBreakerUrl.Method.POST) | ||
| .setUrl(url) | ||
| .setHeaders(headers) | ||
| .setRawData(MAPPER.writeValueAsString(snapshot)) | ||
| .setTimeout(getTimeoutMs()) | ||
| .setThrowWhenError(false) | ||
| .build(); | ||
|
|
||
| call.doString(); | ||
| if (!call.isProcessed()) { | ||
| Logger.warnEvery(this.getClass(), | ||
| "REQUEST_COST_PUSH_FAIL_TRANSPORT", | ||
| "Request cost push to " + sanitizeUrlForLog(url) + " did not complete (circuit open or transport error)", | ||
| FAIL_LOG_INTERVAL_MS); | ||
| return; | ||
| } | ||
| final int response = call.response(); | ||
| if (!CircuitBreakerUrl.isSuccessResponse(response)) { | ||
| Logger.warnEvery(this.getClass(), | ||
| "REQUEST_COST_PUSH_FAIL_HTTP", | ||
| "Request cost push to " + sanitizeUrlForLog(url) + " returned HTTP " + response, | ||
| FAIL_LOG_INTERVAL_MS); | ||
| } | ||
|
wezell marked this conversation as resolved.
|
||
| } catch (final Exception e) { | ||
| Logger.warnEvery(this.getClass(), | ||
| "REQUEST_COST_PUSH_ERR_EXCEPTION", | ||
| "Request cost push to " + sanitizeUrlForLog(url) + " failed: " + e.getMessage(), | ||
| FAIL_LOG_INTERVAL_MS); | ||
|
wezell marked this conversation as resolved.
|
||
| Logger.debug(this.getClass(), | ||
| "Request cost push to " + sanitizeUrlForLog(url) + " failed with exception", | ||
| e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Warns once (per process lifetime) if the configured URL uses the plain {@code http://} | ||
| * scheme — the bearer token would otherwise traverse the wire in cleartext. Stays a warning | ||
| * rather than a refusal so a misconfiguration doesn't silently drop telemetry. | ||
| */ | ||
| private void warnOncePlainHttp(final String url) { | ||
| if (httpSchemeWarned.get()) { | ||
| return; | ||
| } | ||
| try { | ||
| final String scheme = URI.create(url).getScheme(); | ||
| if (scheme != null && scheme.equalsIgnoreCase("http") | ||
|
wezell marked this conversation as resolved.
|
||
| && httpSchemeWarned.compareAndSet(false, true)) { | ||
| Logger.warn(this.getClass(), | ||
| "REQUEST_COST_PUSH_URL uses plain http:// — bearer token will be sent " | ||
| + "in cleartext. Use https:// for any non-loopback destination."); | ||
| } | ||
| } catch (final Exception ignored) { | ||
| // sanitizer is best-effort | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Strips CR/LF and surrounding whitespace from a header value. A misconfigured | ||
| * {@code REQUEST_COST_PUSH_TOKEN} containing CRLF would otherwise enable HTTP header | ||
| * injection — low-risk since only operators set this, but cheap to harden. | ||
| */ | ||
| static String sanitizeHeaderValue(final String value) { | ||
| return value == null ? null : value.replace("\r", "").replace("\n", "").trim(); | ||
| } | ||
|
|
||
| /** | ||
| * Strips RFC-3986 userinfo (the {@code user:pass@} segment) from a URL before logging so a | ||
| * misconfigured {@code REQUEST_COST_PUSH_URL=https://user:secret@host/...} doesn't leak the | ||
| * credential into every failure log line. | ||
| */ | ||
| static String sanitizeUrlForLog(final String url) { | ||
| if (!UtilMethods.isSet(url)) { | ||
| return url; | ||
| } | ||
| try { | ||
| final URI uri = URI.create(url); | ||
| if (uri.getUserInfo() == null) { | ||
| return url; | ||
| } | ||
| final URI safe = new URI( | ||
| uri.getScheme(), null, uri.getHost(), uri.getPort(), | ||
| uri.getPath(), uri.getQuery(), uri.getFragment()); | ||
| return safe.toString(); | ||
| } catch (final Exception ignored) { | ||
| return "<unparseable-url>"; | ||
| } | ||
| } | ||
| } | ||
49 changes: 49 additions & 0 deletions
49
dotCMS/src/main/java/com/dotcms/cost/RequestCostSnapshot.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package com.dotcms.cost; | ||
|
|
||
| import com.fasterxml.jackson.annotation.JsonAutoDetect; | ||
| import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; | ||
|
|
||
| /** | ||
| * Immutable payload shipped to the external request-cost (a.k.a. request token) collection | ||
| * endpoint on each scheduled tick. One snapshot = one point in the time series. | ||
| */ | ||
| @JsonAutoDetect( | ||
| fieldVisibility = Visibility.PUBLIC_ONLY, | ||
| getterVisibility = Visibility.NONE, | ||
| isGetterVisibility = Visibility.NONE) | ||
| public final class RequestCostSnapshot { | ||
|
|
||
|
wezell marked this conversation as resolved.
|
||
| public final String clusterId; | ||
| public final String serverId; | ||
| public final String timestamp; | ||
| public final int windowSeconds; | ||
| public final long windowRequests; | ||
| public final double windowTokens; | ||
| public final double windowAvgTokensPerRequest; | ||
| public final long lifetimeRequests; | ||
| public final double lifetimeTokens; | ||
| public final double lifetimeAvgTokensPerRequest; | ||
|
|
||
| public RequestCostSnapshot( | ||
| final String clusterId, | ||
| final String serverId, | ||
| final String timestamp, | ||
| final int windowSeconds, | ||
| final long windowRequests, | ||
| final double windowTokens, | ||
| final double windowAvgTokensPerRequest, | ||
| final long lifetimeRequests, | ||
| final double lifetimeTokens, | ||
| final double lifetimeAvgTokensPerRequest) { | ||
| this.clusterId = clusterId; | ||
| this.serverId = serverId; | ||
| this.timestamp = timestamp; | ||
| this.windowSeconds = windowSeconds; | ||
| this.windowRequests = windowRequests; | ||
| this.windowTokens = windowTokens; | ||
| this.windowAvgTokensPerRequest = windowAvgTokensPerRequest; | ||
| this.lifetimeRequests = lifetimeRequests; | ||
| this.lifetimeTokens = lifetimeTokens; | ||
| this.lifetimeAvgTokensPerRequest = lifetimeAvgTokensPerRequest; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.