Skip to content

Commit 92c50f8

Browse files
authored
feat: bind exposition writers to negotiated escaping (#2642)
I added an immutable `ExpositionFormatWriterWithEscaping` wrapper and a factory that binds the selected format to the escaping scheme negotiated from the `Accept` header. The scrape handler now uses the negotiated writer, while the existing writer API and standard content types remain unchanged. Fixes #1577. I added the generated API diff report and normalized its generator to omit trailing blank lines rejected by lint. Lint and unit tests pass. The local `mise run build` reached integration tests but Docker/Testcontainers failures prevented the full build; the install build with integration tests skipped passed. I also documented manual negotiated responses in the Formats guide. --------- Signed-off-by: Gregor Zeitlinger <gregor.zeitlinger@grafana.com>
1 parent 6551bab commit 92c50f8

6 files changed

Lines changed: 314 additions & 57 deletions

File tree

‎docs/apidiffs/current_vs_latest/prometheus-metrics-exposition-textformats.txt‎

Lines changed: 11 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎docs/content/exporters/formats.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,31 @@ Prometheus server will scrape OpenMetrics text format with gzip encoding. If the
2323
is started with `--enable-feature=native-histograms`, it will scrape Prometheus protobuf format
2424
instead.
2525

26+
## Writing a negotiated response
27+
28+
Applications that write exposition responses themselves can use `findWriterWithEscaping` to select
29+
the format and escaping scheme together from one `Accept` header. Create and reuse an
30+
`ExpositionFormats` instance instead of initializing it for each response:
31+
32+
```java
33+
import io.prometheus.metrics.expositionformats.ExpositionFormatWriterWithEscaping;
34+
import io.prometheus.metrics.expositionformats.ExpositionFormats;
35+
36+
ExpositionFormats formats = ExpositionFormats.init(); // Create once and reuse.
37+
38+
// In response-writing code, acceptHeader, registry, and outputStream are supplied by the app.
39+
ExpositionFormatWriterWithEscaping writer = formats.findWriterWithEscaping(acceptHeader);
40+
String contentType = writer.getContentType(); // Set the response header before writing the body.
41+
writer.write(outputStream, registry.scrape());
42+
```
43+
44+
The returned writer binds the negotiated format and escaping scheme, so there is no need to parse
45+
the `Accept` header again when writing. `getContentType()` returns the selected format's standard
46+
content type; it does not append an escaping parameter. The existing `findWriter` and writer methods
47+
remain available when you need to choose the escaping scheme explicitly. For details, see the
48+
[Unicode escaping documentation]({{< relref "./unicode.md" >}}) and
49+
[OpenMetrics 2.0 preview]({{< relref "./openmetrics2.md" >}}).
50+
2651
## Viewing with a Web Browser
2752

2853
If you view the `/metrics` endpoint with your Web browser you will see Prometheus text format. For

‎prometheus-metrics-exporter-common/src/main/java/io/prometheus/metrics/exporter/common/PrometheusScrapeHandler.java‎

Lines changed: 5 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@
44
import io.prometheus.metrics.config.EscapingScheme;
55
import io.prometheus.metrics.config.ExporterFilterProperties;
66
import io.prometheus.metrics.config.PrometheusProperties;
7-
import io.prometheus.metrics.expositionformats.ExpositionFormatWriter;
7+
import io.prometheus.metrics.expositionformats.ExpositionFormatWriterWithEscaping;
88
import io.prometheus.metrics.expositionformats.ExpositionFormats;
9-
import io.prometheus.metrics.expositionformats.OpenMetrics2TextFormatWriter;
109
import io.prometheus.metrics.model.registry.MetricNameFilter;
1110
import io.prometheus.metrics.model.registry.PrometheusRegistry;
1211
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
@@ -76,23 +75,21 @@ public void handleRequest(PrometheusHttpExchange exchange) throws IOException {
7675
snapshots, EscapingScheme.fromAcceptHeader(acceptHeader), debugParam, exchange)) {
7776
return;
7877
}
79-
ExpositionFormatWriter writer = expositionFormats.findWriter(acceptHeader);
80-
EscapingScheme escapingScheme =
81-
EscapingScheme.fromAcceptHeader(
82-
acceptHeader, defaultEscapingScheme(writer, acceptHeader));
78+
ExpositionFormatWriterWithEscaping writer =
79+
expositionFormats.findWriterWithEscaping(acceptHeader);
8380
PrometheusHttpResponse response = exchange.getResponse();
8481
response.setHeader("Content-Type", writer.getContentType());
8582

8683
if (shouldUseCompression(request)) {
8784
response.setHeader("Content-Encoding", "gzip");
8885
try (GZIPOutputStream gzipOutputStream =
8986
new GZIPOutputStream(response.sendHeadersAndGetBody(200, 0))) {
90-
writer.write(gzipOutputStream, snapshots, escapingScheme);
87+
writer.write(gzipOutputStream, snapshots);
9188
}
9289
} else {
9390
ByteArrayOutputStream responseBuffer =
9491
new ByteArrayOutputStream(lastResponseSize.get() + 1024);
95-
writer.write(responseBuffer, snapshots, escapingScheme);
92+
writer.write(responseBuffer, snapshots);
9693
lastResponseSize.set(responseBuffer.size());
9794
int contentLength = responseBuffer.size();
9895
if (contentLength > 0) {
@@ -118,39 +115,6 @@ public void handleRequest(PrometheusHttpExchange exchange) throws IOException {
118115
}
119116
}
120117

121-
/**
122-
* OpenMetrics 2.0 supports UTF-8 names and has no escaping parameter, so names are not escaped
123-
* unless the scraper asks for it. With contentNegotiation=false the OM2 writer also serves OM 1.0
124-
* and unversioned requests, so 2.0.0 must have been requested explicitly.
125-
*/
126-
private EscapingScheme defaultEscapingScheme(
127-
ExpositionFormatWriter writer, @Nullable String acceptHeader) {
128-
if (writer instanceof OpenMetrics2TextFormatWriter
129-
&& "2.0.0".equals(parseOpenMetricsVersion(acceptHeader))) {
130-
return EscapingScheme.ALLOW_UTF8;
131-
}
132-
return EscapingScheme.DEFAULT;
133-
}
134-
135-
@Nullable
136-
private static String parseOpenMetricsVersion(@Nullable String acceptHeader) {
137-
if (acceptHeader == null) {
138-
return null;
139-
}
140-
for (String mediaType : acceptHeader.split(",")) {
141-
if (mediaType.contains("application/openmetrics-text")) {
142-
for (String param : mediaType.split(";")) {
143-
String[] tokens = param.split("=");
144-
if (tokens.length == 2 && tokens[0].trim().equals("version")) {
145-
return tokens[1].trim();
146-
}
147-
}
148-
return null;
149-
}
150-
}
151-
return null;
152-
}
153-
154118
@Nullable
155119
private Predicate<String> makeNameFilter(ExporterFilterProperties props) {
156120
if (props.getAllowedMetricNames() == null
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package io.prometheus.metrics.expositionformats;
2+
3+
import io.prometheus.metrics.annotations.StableApi;
4+
import io.prometheus.metrics.config.EscapingScheme;
5+
import io.prometheus.metrics.model.snapshots.MetricSnapshots;
6+
import java.io.IOException;
7+
import java.io.OutputStream;
8+
9+
/**
10+
* An exposition format writer paired with the escaping scheme selected from an Accept header.
11+
*
12+
* <p>Instances are immutable and delegate to the underlying format writer. The content type is the
13+
* format's standard content type and does not include an escaping parameter.
14+
*/
15+
@StableApi
16+
public final class ExpositionFormatWriterWithEscaping {
17+
18+
private final ExpositionFormatWriter writer;
19+
private final EscapingScheme escapingScheme;
20+
21+
ExpositionFormatWriterWithEscaping(ExpositionFormatWriter writer, EscapingScheme escapingScheme) {
22+
this.writer = writer;
23+
this.escapingScheme = escapingScheme;
24+
}
25+
26+
/** Writes the given metric snapshots using the negotiated escaping scheme. */
27+
public void write(OutputStream out, MetricSnapshots metricSnapshots) throws IOException {
28+
writer.write(out, metricSnapshots, escapingScheme);
29+
}
30+
31+
/** Converts the metric snapshots to a debug string using the negotiated escaping scheme. */
32+
public String toDebugString(MetricSnapshots metricSnapshots) {
33+
return writer.toDebugString(metricSnapshots, escapingScheme);
34+
}
35+
36+
/** Returns the standard content type for the selected exposition format. */
37+
public String getContentType() {
38+
return writer.getContentType();
39+
}
40+
41+
/** Returns the escaping scheme selected from the Accept header. */
42+
public EscapingScheme getEscapingScheme() {
43+
return escapingScheme;
44+
}
45+
}

‎prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats/ExpositionFormats.java‎

Lines changed: 73 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package io.prometheus.metrics.expositionformats;
22

33
import io.prometheus.metrics.annotations.StableApi;
4+
import io.prometheus.metrics.config.EscapingScheme;
45
import io.prometheus.metrics.config.ExporterProperties;
56
import io.prometheus.metrics.config.OpenMetrics2Properties;
67
import io.prometheus.metrics.config.PrometheusProperties;
@@ -60,14 +61,19 @@ public static ExpositionFormats init(ExporterProperties properties) {
6061
return init(PrometheusProperties.builder().exporterProperties(properties).build());
6162
}
6263

64+
/**
65+
* Finds the exposition format writer for the given Accept header.
66+
*
67+
* @see #findWriterWithEscaping(String) to select a format and bind its escaping scheme together
68+
*/
6369
public ExpositionFormatWriter findWriter(@Nullable String acceptHeader) {
6470
if (prometheusProtobufWriter.accepts(acceptHeader)) {
6571
return prometheusProtobufWriter;
6672
}
6773

6874
if (isOpenMetrics2Enabled() && openMetrics2TextFormatWriter.accepts(acceptHeader)) {
6975
if (openMetrics2TextFormatWriter.getOpenMetrics2Properties().getContentNegotiation()) {
70-
String version = parseOpenMetricsVersion(acceptHeader);
76+
String version = parseOpenMetricsVersion(findOpenMetricsMediaType(acceptHeader));
7177
if ("2.0.0".equals(version)) {
7278
return openMetrics2TextFormatWriter;
7379
}
@@ -85,6 +91,63 @@ public ExpositionFormatWriter findWriter(@Nullable String acceptHeader) {
8591
return prometheusTextFormatWriter;
8692
}
8793

94+
/**
95+
* Finds the exposition format writer and escaping scheme negotiated by the given Accept header.
96+
*
97+
* <p>Use this method when writing a scrape response to select the format and its escaping scheme
98+
* from the same {@code Accept} header. Only parameters on the media range accepted by the
99+
* selected format affect the escaping scheme. The returned writer's content type is the format's
100+
* standard content type; as with {@link #findWriter(String)}, it does not include an escaping
101+
* parameter.
102+
*
103+
* <pre>{@code
104+
* ExpositionFormats.init().findWriterWithEscaping(acceptHeader).write(out, registry.scrape());
105+
* }</pre>
106+
*
107+
* @see #findWriter(String) to select only the format writer
108+
*/
109+
public ExpositionFormatWriterWithEscaping findWriterWithEscaping(@Nullable String acceptHeader) {
110+
ExpositionFormatWriter writer = findWriter(acceptHeader);
111+
String mediaType = findMatchingMediaType(writer, acceptHeader);
112+
EscapingScheme fallback = EscapingScheme.DEFAULT;
113+
// OpenMetrics 2.0 has no escaping parameter and permits UTF-8 names. Only an explicit request
114+
// for version 2.0.0 selects unescaped names; the OM2 writer may also serve OM1/unversioned
115+
// requests when content negotiation is disabled.
116+
if (writer instanceof OpenMetrics2TextFormatWriter
117+
&& "2.0.0".equals(parseOpenMetricsVersion(mediaType))) {
118+
fallback = EscapingScheme.ALLOW_UTF8;
119+
}
120+
return new ExpositionFormatWriterWithEscaping(
121+
writer, EscapingScheme.fromAcceptHeader(mediaType, fallback));
122+
}
123+
124+
@Nullable
125+
private static String findMatchingMediaType(
126+
ExpositionFormatWriter writer, @Nullable String acceptHeader) {
127+
if (acceptHeader == null) {
128+
return null;
129+
}
130+
for (String mediaType : acceptHeader.split(",")) {
131+
if (writer.accepts(mediaType)) {
132+
return mediaType;
133+
}
134+
}
135+
return null;
136+
}
137+
138+
@Nullable
139+
private static String findOpenMetricsMediaType(@Nullable String acceptHeader) {
140+
if (acceptHeader == null) {
141+
return null;
142+
}
143+
for (String mediaType : acceptHeader.split(",")) {
144+
if (mediaType.contains("application/openmetrics-text")) {
145+
return mediaType;
146+
}
147+
}
148+
return null;
149+
}
150+
88151
private boolean isOpenMetrics2Enabled() {
89152
return openMetrics2TextFormatWriter.getOpenMetrics2Properties().getEnabled();
90153
}
@@ -106,23 +169,18 @@ public OpenMetrics2TextFormatWriter getOpenMetrics2TextFormatWriter() {
106169
}
107170

108171
@Nullable
109-
private static String parseOpenMetricsVersion(@Nullable String acceptHeader) {
110-
if (acceptHeader == null) {
172+
private static String parseOpenMetricsVersion(@Nullable String mediaType) {
173+
if (mediaType == null) {
111174
return null;
112175
}
113-
for (String mediaType : acceptHeader.split(",")) {
114-
if (mediaType.contains("application/openmetrics-text")) {
115-
for (String param : mediaType.split(";")) {
116-
String[] tokens = param.split("=");
117-
if (tokens.length == 2) {
118-
String key = tokens[0].trim();
119-
String value = tokens[1].trim();
120-
if (key.equals("version")) {
121-
return value;
122-
}
123-
}
176+
for (String param : mediaType.split(";")) {
177+
String[] tokens = param.split("=");
178+
if (tokens.length == 2) {
179+
String key = tokens[0].trim();
180+
String value = tokens[1].trim();
181+
if (key.equals("version")) {
182+
return value;
124183
}
125-
return null;
126184
}
127185
}
128186
return null;

0 commit comments

Comments
 (0)