diff --git a/dogstatsd-http-core/src/main/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilder.java b/dogstatsd-http-core/src/main/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilder.java index 60c9ae8f..a21983f7 100644 --- a/dogstatsd-http-core/src/main/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilder.java +++ b/dogstatsd-http-core/src/main/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilder.java @@ -12,7 +12,14 @@ import java.util.Collections; import java.util.List; -/** Build metrics payloads in a format accepted by the agent or the intake. */ +/** + * Build metrics payloads in a format accepted by the agent or the intake. + * + *

If any {@link Metric} method throws, the in-progress metric is no longer valid; the caller + * must call {@link #resetMetric()} to discard the partial state before encoding any further + * metrics. Metrics that are ended without any successfully-added points are silently dropped from + * the payload. + */ public class PayloadBuilder { private static final int DEFAULT_MAX_PAYLOAD_SIZE = 256 * 1024; private static final int METRIC_DATA_FIELD_ID = 3; @@ -205,6 +212,10 @@ void endMetric() { } try { + if (timestamps.length() == 0) { + return; + } + m.encodeIndependentFields(); m.encodeDependentFields(); @@ -221,14 +232,24 @@ void endMetric() { } payload.put(record); } finally { - record.clear(); - timestamps.clear(); - values.clear(); - counts.clear(); - metricInProgress = null; + resetMetric(); } } + /** + * Discard the in-progress metric without adding it to the payload. + * + *

Must be called after any {@link Metric} method throws — the metric is no longer valid and + * its partial state must be discarded before encoding any further metrics. + */ + public void resetMetric() { + record.clear(); + timestamps.clear(); + values.clear(); + counts.clear(); + metricInProgress = null; + } + ColumnarBuffer currentRecord() { return record; } diff --git a/dogstatsd-http-core/src/test/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilderTest.java b/dogstatsd-http-core/src/test/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilderTest.java index 6fa11660..a36295c1 100644 --- a/dogstatsd-http-core/src/test/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilderTest.java +++ b/dogstatsd-http-core/src/test/java/com/datadoghq/dogstatsd/http/serializer/PayloadBuilderTest.java @@ -43,6 +43,8 @@ public void handle(byte[] p) { b.gauge("defgh").addPoint(100, 0).close(); + b.gauge("noop").setTags(Arrays.asList(new String[] {"foo", "bar"})).setInterval(10).close(); + Sketch sketch1 = new Sketch(); sketch1.build(new long[] {1, 2, 2}, 1.0); Sketch sketch2 = new Sketch();