diff --git a/Cargo.lock b/Cargo.lock index 8a46138d2..b329f9568 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2778,7 +2778,9 @@ version = "0.1.0" dependencies = [ "flate2", "opentelemetry-proto", + "prometheus_remote_write", "prost", + "serde_json", "thiserror 1.0.69", ] diff --git a/README.md b/README.md index 64e15e533..e7179afc1 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ default 1 GiB) and queued requests. **Measurements.** `GET /metrics` exports, in the Prometheus text format, the thread CPU and wall time of each phase (`asap_phase_cpu_seconds_total{phase=...}`: `remote_write_decode`, -`append`, `precompute` per refresh group, `query` per query text), query +`otlp_decode`, `append`, `precompute` per refresh group, `query` per query text), query latency, sample and window counters, the backlogs, the watermark lag, the bytes held by raw panes and views, RSS, and each thread's CPU time by name; the view tier and push precompute add `asap_view_cache_*`, @@ -207,9 +207,22 @@ Remote Write (the same protobuf, zstd-compressed) on `/api/v1/import` and OTLP/HTTP metrics (protobuf, optionally gzip) on `/v1/metrics`, the routes ASAPQuery serves them on. An OTLP data point becomes a sample of the series named by its metric (`_sum` and `_count` for histograms and -summaries) and labeled by its scope's, resource's and own attributes. Both -routes answer as Remote Write does (400, 503, 500), and are not served in -forward mode, which delivers only Remote Write bodies to the raw store. +summaries), labeled as Prometheus' OTLP receiver labels it by default: the +point's attributes, their names escaped (`http.method` is `http_method`), +plus `job` from the resource's `service.namespace`/`service.name` and +`instance` from its `service.instance.id`. Other resource attributes are +labels only when named by `--otlp-promote-resource-attributes a,b` (as +Prometheus' `promote_resource_attributes`); scope attributes are not labels. +Sums with DELTA temporality are rejected, counted on `/metrics` +(`asap_otlp_rejected_points_total`); a point flagged "no recorded value" +gives Prometheus' stale marker, as Prometheus writes it and as Remote Write +stale markers are kept. The `otlp` crate's docs list the rules and where +they differ from Prometheus. `/api/v1/import` answers as +Remote Write does (400, 503, 500); `/v1/metrics` answers as OTLP/HTTP asks: +200 with a protobuf `ExportMetricsServiceResponse` (its `partial_success` +counting rejected points), or a `google.rpc.Status` body with 400, 415 +(OTLP/JSON, not decoded), 503 or 500. Neither route is served in forward +mode, which delivers only Remote Write bodies to the raw store. `--deployment-capabilities caps.json` replaces the default `DeploymentCapabilities`: every summary the Planner's executor builds, raw @@ -260,9 +273,9 @@ not stored) with a Prometheus `execution` error (422, | `crates/query/` | package `query`: planned queries on the query workers, and the result cache | | `crates/storage/` | package `storage`: raw samples and views in memory, the view cache, segments, persistence and the persist threads | | `crates/internal-metrics/` | package `internal_metrics`: the backend's measurements of itself, exported on `/metrics` | -| `crates/adapters/ingest/prometheus-remote-write/` | package `prometheus_remote_write`: Remote Write v1 decoding and validation | +| `crates/adapters/ingest/prometheus-remote-write/` | package `prometheus_remote_write`: Remote Write v1 decoding and validation; its protobuf reader and series cache also serve `otlp` | | `crates/adapters/ingest/victoriametrics-remote-write/` | package `victoriametrics_remote_write`: VictoriaMetrics Remote Write (the Remote Write protobuf, zstd-compressed), `POST /api/v1/import` | -| `crates/adapters/ingest/otlp/` | package `otlp`: OTLP/HTTP metrics decoding into samples, `POST /v1/metrics` | +| `crates/adapters/ingest/otlp/` | package `otlp`: OTLP/HTTP metrics decoding into samples, and the OTLP/HTTP replies, `POST /v1/metrics` | | `crates/adapters/query/clickhouse-http/` | package `clickhouse_http`: the `query` parameter, TabSeparated bodies and the fallback client of a ClickHouse server, `/clickhouse/query` | | `crates/adapters/query/elastic-http/` | package `elastic_http`: `_sql` and `_search` bodies and the fallback client of an Elasticsearch server, `POST /_sql`, `POST /_search` | | `crates/adapters/query/prometheus-http/` | package `prometheus_http`: query parameters, response bodies and the fallback client of a Prometheus-compatible server | diff --git a/benchmarks/micro/decode_bench.rs b/benchmarks/micro/decode_bench.rs index dab9813d2..5f616e825 100644 --- a/benchmarks/micro/decode_bench.rs +++ b/benchmarks/micro/decode_bench.rs @@ -1,8 +1,12 @@ -//! Remote Write decode cost, in process: decodes the same request -//! repeatedly into interned samples, as the write handler does, and prints -//! microseconds per sample for two request shapes: one series per sample -//! (10,000 series with one sample each, as a paced feeder sends) and -//! Prometheus' shape (100 series with 100 samples each). +//! Ingest decode cost, in process: decodes the same request repeatedly +//! into interned samples, as the write handlers do, and prints +//! microseconds per sample for Remote Write and OTLP, each in two request +//! shapes: one series per sample (10,000 series with one sample each, as +//! a paced feeder sends) and Prometheus' shape (100 series with 100 +//! samples each). The OTLP request holds the same series and samples as +//! the Remote Write one: one gauge, each label but `__name__` a point +//! attribute (uncompressed protobuf, as an OpenTelemetry SDK sends it by +//! default). //! //! `cargo run --release -p data_plane --example decode_bench` @@ -12,25 +16,34 @@ static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; use std::time::Instant; -use data_plane::remote_write::decode_samples; +use data_plane::remote_write::{decode_otlp_samples, decode_samples}; +use otlp::proto::collector::metrics::v1::ExportMetricsServiceRequest; +use otlp::proto::common::v1::{any_value, AnyValue, KeyValue}; +use otlp::proto::metrics::v1::{ + metric::Data, number_data_point, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, +}; use prometheus_remote_write::{encode, Label, Limits, Sample, TimeSeries, WriteRequest}; -fn request(series: usize, samples_per_series: usize) -> Vec { +fn labels(i: usize) -> [(&'static str, String); 5] { + [ + ("__name__", "data".to_string()), + ("instance", format!("i{i}")), + ("job", format!("job{}", i % 16)), + ("region", format!("r{}", i % 4)), + ("service", format!("s{}", i % 8)), + ] +} + +fn remote_write_request(series: usize, samples_per_series: usize) -> Vec { let timeseries = (0..series) .map(|i| TimeSeries { - labels: [ - ("__name__", "data".to_string()), - ("instance", format!("i{i}")), - ("job", format!("job{}", i % 16)), - ("region", format!("r{}", i % 4)), - ("service", format!("s{}", i % 8)), - ] - .into_iter() - .map(|(name, value)| Label { - name: name.into(), - value, - }) - .collect(), + labels: labels(i) + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value, + }) + .collect(), samples: (0..samples_per_series) .map(|t| Sample { timestamp: 1_000 * t as i64, @@ -42,24 +55,73 @@ fn request(series: usize, samples_per_series: usize) -> Vec { encode(&WriteRequest { timeseries }) } +fn otlp_request(series: usize, samples_per_series: usize) -> Vec { + let data_points = (0..series) + .flat_map(|i| { + let attributes: Vec = labels(i)[1..] + .iter() + .map(|(name, value)| KeyValue { + key: name.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.clone())), + }), + }) + .collect(); + (0..samples_per_series).map(move |t| NumberDataPoint { + attributes: attributes.clone(), + time_unix_nano: 1_000_000_000 * t as u64, + value: Some(number_data_point::Value::AsDouble(t as f64)), + ..Default::default() + }) + }) + .collect(); + let request = ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + scope_metrics: vec![ScopeMetrics { + metrics: vec![Metric { + name: "data".into(), + data: Some(Data::Gauge(Gauge { data_points })), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }], + }; + prost::Message::encode_to_vec(&request) +} + +/// Microseconds per sample of `decode` over `body`, after one decode that +/// interns the series, as a steady stream would. +fn per_sample(body: &[u8], samples: usize, decode: impl Fn(&[u8]) -> Vec) -> f64 { + assert_eq!(decode(body).len(), samples); + let rounds = 200; + let started = Instant::now(); + for _ in 0..rounds { + std::hint::black_box(decode(body)); + } + started.elapsed().as_secs_f64() * 1e6 / (rounds * samples) as f64 +} + fn main() { let limits = Limits::default(); + let options = otlp::LabelOptions::default(); for (name, series, per_series) in [ ("one series per sample", 10_000, 1), ("100 samples per series", 100, 100), ] { - let body = request(series, per_series); - // Interns the series once, as a steady stream would. - decode_samples(&body, &limits).unwrap(); - let rounds = 200; - let started = Instant::now(); - for _ in 0..rounds { - std::hint::black_box(decode_samples(&body, &limits).unwrap()); - } - let samples = (rounds * series * per_series) as f64; + let samples = series * per_series; + let remote_write = per_sample(&remote_write_request(series, per_series), samples, |b| { + decode_samples(b, &limits).unwrap() + }); + let otlp = per_sample(&otlp_request(series, per_series), samples, |b| { + decode_otlp_samples(b, None, &options, &limits) + .unwrap() + .samples + }); println!( - "{name}: {:.3} µs/sample", - started.elapsed().as_secs_f64() * 1e6 / samples + "{name}: Remote Write {remote_write:.3} µs/sample, OTLP {otlp:.3} µs/sample ({:.2}x)", + otlp / remote_write ); } } diff --git a/crates/adapters/ingest/otlp/Cargo.toml b/crates/adapters/ingest/otlp/Cargo.toml index 8590127cd..d4de7928f 100644 --- a/crates/adapters/ingest/otlp/Cargo.toml +++ b/crates/adapters/ingest/otlp/Cargo.toml @@ -3,13 +3,18 @@ name = "otlp" version.workspace = true edition.workspace = true -# OTLP (OpenTelemetry) metrics over HTTP: request decoding into data -# points. An adapter: no workspace dependency, so it never sees an engine -# or a store. +# OTLP (OpenTelemetry) metrics over HTTP: request decoding into the +# caller's samples, and the replies. An adapter: it never sees an engine or +# a store. It depends on `prometheus-remote-write` alone, for the caller's +# sample types (`SampleBuilder`), the in-place protobuf reader and the +# series cache its decoder shares. [dependencies] -# The OTLP protobuf messages (no gRPC server; the crate still builds -# tonic's codegen types and the OpenTelemetry SDK it depends on). +prometheus_remote_write.workspace = true +# The OTLP protobuf messages, for senders, tests and the replies (no gRPC +# server; the crate still builds tonic's codegen types and the +# OpenTelemetry SDK it depends on). opentelemetry-proto = { version = "0.28", default-features = false, features = ["gen-tonic-messages", "metrics"] } prost = "0.13" flate2 = "1.0" +serde_json.workspace = true thiserror.workspace = true diff --git a/crates/adapters/ingest/otlp/src/lib.rs b/crates/adapters/ingest/otlp/src/lib.rs index 08d8917ef..dcac639e8 100644 --- a/crates/adapters/ingest/otlp/src/lib.rs +++ b/crates/adapters/ingest/otlp/src/lib.rs @@ -1,24 +1,84 @@ -//! OTLP (OpenTelemetry protocol) metrics decoding: an +//! OTLP (OpenTelemetry protocol) metrics over HTTP: an //! `ExportMetricsServiceRequest` body, as `POST /v1/metrics` receives it, -//! into one [`Point`] per sample, the way ASAPQuery's OTLP receiver reads it. +//! decoded into the caller's samples ([`Decoder`]), and the replies the +//! OTLP/HTTP specification asks for ([`export_response_body`], [`status_body`]). //! -//! Each data point becomes samples of Prometheus-style series: the metric's -//! name as `__name__`, plus the scope's, the resource's and the point's -//! attributes as labels (a later one replaces an earlier one of the same -//! name). Gauges and sums give one sample; histograms, exponential -//! histograms and summaries give `_sum` (when set) and -//! `_count`. Data points that carry a sketch payload attribute -//! (`kll.`, `cms.` or `countsketch.sketch_payload`) are skipped, as -//! ASAPQuery skips them. +//! # From OTLP to series +//! +//! The decoder maps data points to Prometheus-style series as Prometheus' +//! own OTLP receiver does with its default configuration (Prometheus 3.x, +//! `storage/remote/otlptranslator/prometheusremotewrite` and the `otlp:` +//! defaults in `config/config.go`): +//! +//! - A gauge or sum point is one sample of the series named by its metric. +//! A histogram, exponential histogram or summary point gives +//! `_sum` (when set) and `_count`; buckets and quantiles are +//! not read. A point without a value reads 0, as in Prometheus. +//! - The point's attributes are the series' labels, their names escaped as +//! Prometheus' default `UnderscoreEscapingWithSuffixes` strategy escapes +//! them (`http.method` is `http_method`). Attributes whose +//! names escape to the same label are joined with `;`, in the order of +//! their names; an empty value is no label. +//! - Resource attributes are not labels. `service.name` gives `job` +//! (`/` when the namespace is set) and +//! `service.instance.id` gives `instance`, over any point attribute of +//! that name. [`LabelOptions::promote_resource_attributes`] names resource +//! attributes that are also labels, as Prometheus' +//! `promote_resource_attributes` does; a point attribute of the same +//! label wins. No `target_info` series is written. +//! - The scope's name, version and attributes are not labels (Prometheus' +//! `promote_scope_metadata: false`). +//! - A sum with DELTA temporality is rejected, each point counted in +//! [`Decoded::rejected_points`]: its points are increments, not the +//! running total a cumulative sum and `rate` read (Prometheus drops them +//! with a warning). +//! - A point flagged "no recorded value" gives Prometheus' stale marker +//! (`StaleNaN`) for each sample it gives, as Prometheus writes it; the +//! Remote Write path keeps stale markers the same way. +//! +//! Where this differs from Prometheus' defaults: +//! +//! - Metric names are not translated (no escaping, no unit or `_total` +//! suffix). +//! - Histograms and exponential histograms give `_sum` and `_count` +//! whatever their temporality, and a sum of unspecified temporality is +//! read as cumulative (Prometheus drops both). +//! - An attribute whose name Prometheus refuses (empty, or only +//! underscores once escaped) is no label; Prometheus drops the point. +//! - Values print as Rust prints them: bytes as their debug text (`[1, 2]`, +//! Prometheus: base64), arrays and key-value lists as empty text, so no +//! label (Prometheus: JSON), doubles without an exponent (`1e21` is +//! `1000000000000000000000`, Prometheus `1e+21`). +//! - A body is read as protobuf whatever its `Content-Type` other than +//! `application/json` (Prometheus refuses other types), and OTLP/JSON is +//! not decoded. +//! - Points with a sketch payload attribute (`kll.`, `cms.` or +//! `countsketch.sketch_payload`) are skipped, as ASAPQuery skips them. +//! +//! # Decoding +//! +//! As the Remote Write decoder, [`Decoder`] walks the protobuf in place, +//! without building the request's messages, into the caller's +//! [`SampleBuilder`] series, and keeps a series cache between requests: a +//! point's series is looked up by the bytes of its resource's labels, its +//! metric name and its encoded attributes, so a known series costs a +//! compare (or a hash); only a new one is translated and interned. +use std::borrow::Cow; +use std::collections::btree_map::Entry; use std::collections::BTreeMap; use std::io::Read; -use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest; -use opentelemetry_proto::tonic::common::v1::{any_value, KeyValue}; -use opentelemetry_proto::tonic::metrics::v1::{metric::Data, number_data_point, Gauge, Sum}; +use prometheus_remote_write::series_cache::SeriesCache; +use prometheus_remote_write::wire::{Reader, Value}; +use prometheus_remote_write::RemoteWriteError; use prost::Message; +/// The caller's series and sample types, as the Remote Write decoder +/// takes them: the labels passed to [`SampleBuilder::intern`] are sorted +/// by name, each name once, `__name__` among them. +pub use prometheus_remote_write::SampleBuilder; + /// The OTLP protobuf messages, for senders and tests. pub use opentelemetry_proto::tonic as proto; @@ -29,6 +89,15 @@ pub struct Limits { pub max_points: usize, } +/// How resource attributes become labels. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct LabelOptions { + /// Resource attributes that are labels of every series of their + /// resource, by their OTLP names (`deployment.environment`), as + /// Prometheus' `otlp.promote_resource_attributes`. Empty: none. + pub promote_resource_attributes: Vec, +} + #[derive(Debug, thiserror::Error, PartialEq)] pub enum OtlpError { #[error("Gzip decode error: {0}")] @@ -41,48 +110,130 @@ pub enum OtlpError { TooManyPoints(usize), } -/// One sample of a series. -#[derive(Debug, Clone, PartialEq)] -pub struct Point { - /// `__name__` and the attributes, sorted by name, each name once. - pub labels: Vec<(String, String)>, - pub timestamp_ms: i64, - pub value: f64, +/// The protobuf reader's errors ([`RemoteWriteError::Protobuf`]). +impl From for OtlpError { + #[cold] + fn from(error: RemoteWriteError) -> Self { + match error { + RemoteWriteError::Protobuf(message) => OtlpError::Protobuf(message), + other => OtlpError::Protobuf(other.to_string()), + } + } +} + +/// A decoded request. +#[derive(Debug, PartialEq)] +pub struct Decoded { + /// The samples, in request order. + pub samples: Vec, + /// Data points refused, which the reply reports as rejected: the points + /// of sums with DELTA temporality. + pub rejected_points: u64, +} + +impl Decoded { + /// Why points were rejected, for the reply; `None` when none were. + pub fn rejection_message(&self) -> Option { + (self.rejected_points > 0).then(|| { + format!( + "{} data points of sums with DELTA aggregation temporality were rejected: \ + only cumulative sums are ingested", + self.rejected_points + ) + }) + } +} + +/// A decoder's state, kept between requests: its decompression buffer, its +/// series cache and the buffer it builds cache keys in. +pub struct Decoder { + decompressed: Vec, + series: SeriesCache, + builder: B, + /// Where a point's cache key is built, kept between points. + key_buffer: Vec, } -/// The points of an OTLP metrics request body, in request order. -/// `content_encoding` is the request's `Content-Encoding`: `gzip` bodies -/// are decompressed; any other encoding is read as is, as ASAPQuery does. -/// Errors: the body is not gzip (when it says so) or not an -/// `ExportMetricsServiceRequest`, or is over a limit. -pub fn decode( - body: &[u8], - content_encoding: Option<&str>, +impl Decoder { + pub fn new(builder: B) -> Self { + Self { + decompressed: Vec::new(), + series: SeriesCache::new(), + builder, + key_buffer: Vec::new(), + } + } + + /// The samples of an OTLP metrics request body, in request order. + /// `content_encoding` is the request's `Content-Encoding`: `gzip` bodies + /// are decompressed; any other encoding is read as is, as ASAPQuery + /// does. Errors: the body is not gzip (when it says so) or not an + /// `ExportMetricsServiceRequest`, or is over a limit. + pub fn decode( + &mut self, + body: &[u8], + content_encoding: Option<&str>, + options: &LabelOptions, + limits: &Limits, + ) -> Result, OtlpError> { + let gzip = content_encoding.is_some_and(|e| e.trim().eq_ignore_ascii_case("gzip")); + let Self { + decompressed, + series, + builder, + key_buffer, + } = self; + let decoded = if gzip { + gunzip(body, limits.max_decompressed_bytes, decompressed) + .and_then(|request| walk(request, series, builder, key_buffer, options, limits)) + } else if body.len() > limits.max_decompressed_bytes { + Err(OtlpError::DecompressedTooLarge( + limits.max_decompressed_bytes, + )) + } else { + walk(body, series, builder, key_buffer, options, limits) + }; + // An unusually large request's buffer is not kept, whether or not it + // decoded, as the Remote Write decoder does. + if decompressed.capacity() > prometheus_remote_write::KEPT_DECOMPRESSED_BYTES { + *decompressed = Vec::new(); + } + decoded + } +} + +/// The samples of the uncompressed request `request` ([`Decoder::decode`]). +fn walk( + request: &[u8], + series: &mut SeriesCache, + builder: &mut B, + key_buffer: &mut Vec, + options: &LabelOptions, limits: &Limits, -) -> Result, OtlpError> { - let gzip = content_encoding.is_some_and(|e| e.trim().eq_ignore_ascii_case("gzip")); - let decompressed; - let request = if gzip { - decompressed = gunzip(body, limits.max_decompressed_bytes)?; - &decompressed[..] - } else if body.len() > limits.max_decompressed_bytes { - return Err(OtlpError::DecompressedTooLarge( - limits.max_decompressed_bytes, - )); - } else { - body +) -> Result, OtlpError> { + let mut walk = Walk { + series, + builder, + key_buffer, + options, + max_points: limits.max_points, + decoded: Decoded { + // Room for one sample per 50 encoded bytes, about one gauge + // point with a few short attributes. + samples: Vec::with_capacity(request.len() / 50), + rejected_points: 0, + }, }; - let request = ExportMetricsServiceRequest::decode(request) - .map_err(|e| OtlpError::Protobuf(e.to_string()))?; - points(&request, limits.max_points) + walk.request(request)?; + Ok(walk.decoded) } -/// `body` gunzipped, reading at most one byte past `max_bytes`. -fn gunzip(body: &[u8], max_bytes: usize) -> Result, OtlpError> { - let mut out = Vec::new(); - flate2::read::GzDecoder::new(body) +/// `body` gunzipped into `out`, reading at most one byte past `max_bytes`. +fn gunzip<'a>(body: &[u8], max_bytes: usize, out: &'a mut Vec) -> Result<&'a [u8], OtlpError> { + out.clear(); + flate2::read::MultiGzDecoder::new(body) .take(max_bytes as u64 + 1) - .read_to_end(&mut out) + .read_to_end(out) .map_err(|e| OtlpError::Gzip(e.to_string()))?; if out.len() > max_bytes { return Err(OtlpError::DecompressedTooLarge(max_bytes)); @@ -90,464 +241,587 @@ fn gunzip(body: &[u8], max_bytes: usize) -> Result, OtlpError> { Ok(out) } -/// The points of `request`, at most `max_points`. -fn points( - request: &ExportMetricsServiceRequest, - max_points: usize, -) -> Result, OtlpError> { - let mut points = Vec::new(); - for resource_metrics in &request.resource_metrics { - let resource = resource_metrics.resource.as_ref(); - for scope_metrics in &resource_metrics.scope_metrics { - // The scope's attributes, then the resource's over them. - let mut scope_labels = BTreeMap::new(); - if let Some(scope) = &scope_metrics.scope { - insert_attributes(&mut scope_labels, &scope.attributes); - } - if let Some(resource) = resource { - insert_attributes(&mut scope_labels, &resource.attributes); +/// The labels a resource gives each of its series. +struct ResourceLabels { + job: Option, + instance: Option, + /// The promoted attributes, by label name. + promoted: Vec<(String, String)>, + /// These labels' bytes, the start of each of the resource's cache keys. + key_prefix: Vec, +} + +impl ResourceLabels { + /// The labels of the encoded `Resource` `resource`. + fn new(resource: &[u8], options: &LabelOptions) -> Result { + let mut name = None; + let mut namespace = None; + let mut instance = None; + let mut promoted = BTreeMap::new(); + let mut reader = Reader::new(resource); + while let Some((field, value)) = reader.field()? { + let (1, Value::Bytes(attribute)) = (field, value) else { + continue; + }; + let (key, value) = key_value(attribute)?; + match key { + "service.name" => name = Some(value.text().into_owned()), + "service.namespace" => namespace = Some(value.text().into_owned()), + "service.instance.id" => instance = Some(value.text().into_owned()), + _ => {} } - for metric in &scope_metrics.metrics { - if metric.name.is_empty() { - continue; - } - // One data point's samples: a value per name suffix (none - // when `None`), labeled by the point's attributes over the - // scope's and resource's. - let mut push = |attributes: &[KeyValue], - nanos: u64, - values: &[(&str, Option)]| - -> Result<(), OtlpError> { - if has_sketch_payload(attributes) { - return Ok(()); - } - let mut labels = scope_labels.clone(); - insert_attributes(&mut labels, attributes); - for &(suffix, value) in values { - let Some(value) = value else { continue }; - if points.len() >= max_points { - return Err(OtlpError::TooManyPoints(max_points)); - } - let name = format!("{}{suffix}", metric.name); - let mut labels = labels.clone(); - labels.insert("__name__".to_string(), name); - points.push(Point { - labels: labels.into_iter().collect(), - timestamp_ms: (nanos / 1_000_000) as i64, - value, - }); - } - Ok(()) - }; - match &metric.data { - Some(Data::Gauge(Gauge { data_points })) - | Some(Data::Sum(Sum { data_points, .. })) => { - for p in data_points { - push( - &p.attributes, - p.time_unix_nano, - &[("", Some(number(&p.value)))], - )?; - } - } - Some(Data::Histogram(histogram)) => { - for p in &histogram.data_points { - let count = Some(p.count as f64); - push( - &p.attributes, - p.time_unix_nano, - &[("_sum", p.sum), ("_count", count)], - )?; - } - } - Some(Data::ExponentialHistogram(histogram)) => { - for p in &histogram.data_points { - let count = Some(p.count as f64); - push( - &p.attributes, - p.time_unix_nano, - &[("_sum", p.sum), ("_count", count)], - )?; - } - } - Some(Data::Summary(summary)) => { - for p in &summary.data_points { - let count = Some(p.count as f64); - push( - &p.attributes, - p.time_unix_nano, - &[("_sum", Some(p.sum)), ("_count", count)], - )?; - } - } - None => {} + if options.promote_resource_attributes.iter().any(|p| p == key) + && !value.text().is_empty() + { + if let Some(label) = label_name(key) { + promoted.insert(label.into_owned(), value.text().into_owned()); } } } - } - Ok(points) -} - -/// Whether a data point carries a sketch in place of a value. -fn has_sketch_payload(attributes: &[KeyValue]) -> bool { - attributes.iter().any(|kv| { - matches!( - kv.key.as_str(), - "kll.sketch_payload" | "cms.sketch_payload" | "countsketch.sketch_payload" - ) && matches!( - kv.value.as_ref().and_then(|v| v.value.as_ref()), - Some(any_value::Value::BytesValue(_)) - ) - }) -} - -/// Inserts each attribute with a name into `labels`, its value as text. -fn insert_attributes(labels: &mut BTreeMap, attributes: &[KeyValue]) { - for kv in attributes { - if kv.key.is_empty() { - continue; + let job = name.map(|name| match namespace { + Some(namespace) => format!("{namespace}/{name}"), + None => name, + }); + let job = job.filter(|job| !job.is_empty()); + let instance = instance.filter(|instance| !instance.is_empty()); + let promoted: Vec<(String, String)> = promoted.into_iter().collect(); + let mut key_prefix = Vec::new(); + for text in [job.as_deref(), instance.as_deref()] { + push_length_prefixed(&mut key_prefix, text.unwrap_or("")); } - let value = match kv.value.as_ref().and_then(|v| v.value.as_ref()) { - Some(any_value::Value::StringValue(s)) => s.clone(), - Some(any_value::Value::IntValue(i)) => i.to_string(), - Some(any_value::Value::DoubleValue(d)) => d.to_string(), - Some(any_value::Value::BoolValue(b)) => b.to_string(), - Some(any_value::Value::BytesValue(bytes)) => format!("{bytes:?}"), - _ => String::new(), - }; - labels.insert(kv.key.clone(), value); + for (label, value) in &promoted { + push_length_prefixed(&mut key_prefix, label); + push_length_prefixed(&mut key_prefix, value); + } + // Ends the resource's part of a key: no label name is empty. + push_length_prefixed(&mut key_prefix, ""); + Ok(Self { + job, + instance, + promoted, + key_prefix, + }) } } -/// A number data point's value; 0 when it has none. -fn number(value: &Option) -> f64 { - match value { - Some(number_data_point::Value::AsDouble(x)) => *x, - Some(number_data_point::Value::AsInt(x)) => *x as f64, - None => 0.0, +/// Appends `text` to `key`, length first. +fn push_length_prefixed(key: &mut Vec, text: &str) { + key.extend_from_slice(&(text.len() as u32).to_le_bytes()); + key.extend_from_slice(text.as_bytes()); +} + +/// What a data point message gives: a gauge or sum point one sample; a +/// histogram, exponential histogram or summary point `_sum` and `_count` +/// (a summary's `_sum` always set, the histograms' only when present). +#[derive(Clone, Copy, PartialEq)] +enum PointKind { + Number, + Histogram, + ExponentialHistogram, + Summary, +} + +impl PointKind { + /// The field numbers of the point's attributes and of its flags. + fn attributes_and_flags_fields(self) -> (u64, u64) { + match self { + PointKind::Number => (7, 8), + PointKind::Histogram => (9, 10), + PointKind::ExponentialHistogram => (1, 10), + PointKind::Summary => (7, 8), + } } } -#[cfg(test)] -mod tests { - use super::*; - use opentelemetry_proto::tonic::common::v1::{AnyValue, InstrumentationScope}; +/// A metric's last point: its encoded attributes and the series of each of +/// its samples found so far. +struct PreviousPoint<'p, S> { + attributes: &'p [u8], + series: [Option; 2], +} - const LIMITS: Limits = Limits { - max_decompressed_bytes: 128 * 1024 * 1024, - max_points: 1_000_000, - }; +/// `DataPointFlags.FLAG_NO_RECORDED_VALUE_MASK`. +const FLAG_NO_RECORDED_VALUE: u64 = 1; +/// Prometheus' stale marker (`value.StaleNaN`), the value of each sample +/// of a point flagged "no recorded value". +const STALE_NAN: f64 = f64::from_bits(0x7ff0_0000_0000_0002); +/// `AggregationTemporality.AGGREGATION_TEMPORALITY_DELTA`. +const TEMPORALITY_DELTA: u64 = 1; - fn encode(request: &ExportMetricsServiceRequest) -> Vec { - request.encode_to_vec() - } - use opentelemetry_proto::tonic::metrics::v1::{ - ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, Histogram, HistogramDataPoint, - Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, Summary, SummaryDataPoint, - }; - use opentelemetry_proto::tonic::resource::v1::Resource; +/// One request's walk. +struct Walk<'a, B: SampleBuilder> { + series: &'a mut SeriesCache, + builder: &'a mut B, + key_buffer: &'a mut Vec, + options: &'a LabelOptions, + max_points: usize, + decoded: Decoded, +} - fn attribute(key: &str, value: any_value::Value) -> KeyValue { - KeyValue { - key: key.to_string(), - value: Some(AnyValue { value: Some(value) }), +impl Walk<'_, B> { + /// An encoded `ExportMetricsServiceRequest`. + fn request(&mut self, request: &[u8]) -> Result<(), OtlpError> { + let mut reader = Reader::new(request); + while let Some((field, value)) = reader.field()? { + if let (1, Value::Bytes(resource_metrics)) = (field, value) { + self.resource_metrics(resource_metrics)?; + } } + Ok(()) } - fn text(key: &str, value: &str) -> KeyValue { - attribute(key, any_value::Value::StringValue(value.to_string())) - } - - fn number_point( - attributes: Vec, - nanos: u64, - value: number_data_point::Value, - ) -> NumberDataPoint { - NumberDataPoint { - attributes, - time_unix_nano: nanos, - value: Some(value), - ..Default::default() + /// An encoded `ResourceMetrics`: its resource (field 1), then the + /// metrics of each of its scopes (field 2), in any order. + fn resource_metrics(&mut self, bytes: &[u8]) -> Result<(), OtlpError> { + let mut resource: &[u8] = &[]; + let mut reader = Reader::new(bytes); + while let Some((field, value)) = reader.field()? { + if let (1, Value::Bytes(found)) = (field, value) { + resource = found; + } } + let resource = ResourceLabels::new(resource, self.options)?; + let mut reader = Reader::new(bytes); + while let Some((field, value)) = reader.field()? { + let (2, Value::Bytes(scope_metrics)) = (field, value) else { + continue; + }; + let mut metrics = Reader::new(scope_metrics); + while let Some((field, value)) = metrics.field()? { + if let (2, Value::Bytes(metric)) = (field, value) { + self.metric(&resource, metric)?; + } + } + } + Ok(()) } - fn metric(name: &str, data: Data) -> Metric { - Metric { - name: name.to_string(), - data: Some(data), - ..Default::default() + /// An encoded `Metric`: its name (field 1) and its data, one of gauge + /// (5), sum (7), histogram (9), exponential histogram (10) or summary + /// (11), whose points (field 1) each give samples. + fn metric(&mut self, resource: &ResourceLabels, bytes: &[u8]) -> Result<(), OtlpError> { + let mut name = ""; + let mut data = None; + let mut reader = Reader::new(bytes); + while let Some((field, value)) = reader.field()? { + match (field, value) { + (1, Value::Bytes(text)) => name = utf8(text)?, + (5 | 7 | 9 | 10 | 11, Value::Bytes(found)) => data = Some((field, found)), + _ => {} + } } + let Some((field, data)) = data else { + return Ok(()); + }; + if name.is_empty() { + return Ok(()); + } + let kind = match field { + 5 | 7 => PointKind::Number, + 9 => PointKind::Histogram, + 10 => PointKind::ExponentialHistogram, + _ => PointKind::Summary, + }; + let delta_sum = field == 7 && { + let mut temporality = 0; + let mut reader = Reader::new(data); + while let Some((field, value)) = reader.field()? { + if let (2, Value::Varint(found)) = (field, value) { + temporality = found; + } + } + temporality == TEMPORALITY_DELTA + }; + let mut previous = None; + let mut reader = Reader::new(data); + while let Some((field, value)) = reader.field()? { + let (1, Value::Bytes(point)) = (field, value) else { + continue; + }; + if delta_sum { + self.decoded.rejected_points += 1; + } else { + self.point(resource, name, kind, point, &mut previous)?; + } + } + Ok(()) } - /// A request with one resource and one scope holding `metrics`. - fn request(metrics: Vec) -> ExportMetricsServiceRequest { - ExportMetricsServiceRequest { - resource_metrics: vec![ResourceMetrics { - resource: Some(Resource { - attributes: vec![text("service.name", "api-gateway")], - ..Default::default() - }), - scope_metrics: vec![ScopeMetrics { - scope: Some(InstrumentationScope { - name: "exporter".to_string(), - attributes: vec![text("scope", "s"), text("service.name", "scope's")], - ..Default::default() - }), - metrics, - ..Default::default() - }], - ..Default::default() - }], + /// An encoded data point of `kind` of metric `name`. `previous` is the + /// metric's point before it, whose series it takes when it has the same + /// encoded attributes, as a series' consecutive points do. + fn point<'p>( + &mut self, + resource: &ResourceLabels, + name: &str, + kind: PointKind, + point: &'p [u8], + previous: &mut Option>, + ) -> Result<(), OtlpError> { + let (attributes_field, flags_field) = kind.attributes_and_flags_fields(); + let mut time_nanos = 0u64; + let mut flags = 0u64; + let mut number = 0f64; + let mut count = 0u64; + let mut sum = (kind == PointKind::Summary).then_some(0f64); + // Where the encoded attributes are. + let mut attributes_start = None; + let mut attributes_end = 0; + let mut contiguous = true; + let mut reader = Reader::new(point); + while let Some((field, value)) = reader.field()? { + match (field, value) { + (field, Value::Bytes(_)) if field == attributes_field => { + match attributes_start { + None => attributes_start = Some(reader.field_start), + Some(_) if reader.field_start != attributes_end => contiguous = false, + Some(_) => {} + } + attributes_end = reader.position; + } + (3, Value::Fixed64(found)) => time_nanos = found, + (field, Value::Varint(found)) if field == flags_field => flags = found, + (4, Value::Fixed64(bits)) if kind == PointKind::Number => { + number = f64::from_bits(bits) + } + (6, Value::Fixed64(bits)) if kind == PointKind::Number => { + number = bits as i64 as f64 + } + (4, Value::Fixed64(found)) => count = found, + (5, Value::Fixed64(bits)) => sum = Some(f64::from_bits(bits)), + _ => {} + } + } + // The encoded attributes: one slice of `point` when contiguous, as + // senders write them; the metric's previous point's series serve + // the same slice. + let concatenated; + let attributes = match (attributes_start, contiguous) { + (None, _) | (Some(_), true) => { + let attributes = &point[attributes_start.unwrap_or(0)..attributes_end]; + if previous + .as_ref() + .is_none_or(|last| last.attributes != attributes) + { + *previous = Some(PreviousPoint { + attributes, + series: [None; 2], + }); + } + attributes + } + (Some(_), false) => { + // Rare: attributes interleaved with other fields; key by + // their concatenation. + *previous = None; + let mut joined = Vec::new(); + let mut reader = Reader::new(point); + while let Some((field, value)) = reader.field()? { + if let (field, Value::Bytes(_)) = (field, value) { + if field == attributes_field { + joined.extend_from_slice(&point[reader.field_start..reader.position]); + } + } + } + concatenated = joined; + &concatenated[..] + } + }; + let timestamp_ms = (time_nanos / 1_000_000) as i64; + let mut samples: [(&str, Option); 2] = match kind { + PointKind::Number => [("", Some(number)), ("", None)], + _ => [("_sum", sum), ("_count", Some(count as f64))], + }; + if flags & FLAG_NO_RECORDED_VALUE != 0 { + for (_, value) in &mut samples { + if value.is_some() { + *value = Some(STALE_NAN); + } + } + } + for (index, (suffix, value)) in samples.into_iter().enumerate() { + let Some(value) = value else { continue }; + let known = previous.as_ref().and_then(|last| last.series[index]); + let series = match known { + Some(series) => series, + None => { + let Some(series) = self.series(resource, name, suffix, attributes)? else { + // A sketch payload point. + return Ok(()); + }; + if let Some(last) = previous.as_mut() { + last.series[index] = Some(series); + } + series + } + }; + if self.decoded.samples.len() >= self.max_points { + return Err(OtlpError::TooManyPoints(self.max_points)); + } + self.decoded + .samples + .push(B::sample(series, timestamp_ms, value)); } + Ok(()) } - fn labels(pairs: &[(&str, &str)]) -> Vec<(String, String)> { - let mut labels: Vec<(String, String)> = pairs + /// The series of a point of metric `name` (with `suffix`) and the + /// encoded `attributes` (`KeyValue` fields), from the cache or + /// translated and interned; `None` for a point that carries a sketch + /// payload. + #[inline] + fn series( + &mut self, + resource: &ResourceLabels, + name: &str, + suffix: &str, + attributes: &[u8], + ) -> Result, OtlpError> { + let key = &mut *self.key_buffer; + key.clear(); + key.extend_from_slice(&resource.key_prefix); + key.extend_from_slice(&((name.len() + suffix.len()) as u32).to_le_bytes()); + key.extend_from_slice(name.as_bytes()); + key.extend_from_slice(suffix.as_bytes()); + key.extend_from_slice(attributes); + if let Some(series) = self.series.get(key) { + return Ok(Some(series)); + } + let mut pairs = Vec::new(); + let mut reader = Reader::new(attributes); + while let Some((_, value)) = reader.field()? { + if let Value::Bytes(attribute) = value { + pairs.push(key_value(attribute)?); + } + } + if pairs + .iter() + .any(|(key, value)| is_sketch_payload(key, value)) + { + return Ok(None); + } + let labels = series_labels(resource, &format!("{name}{suffix}"), &mut pairs); + let labels: Vec<(&str, &str)> = labels .iter() - .map(|(name, value)| (name.to_string(), value.to_string())) + .map(|(name, value)| (name.as_ref(), value.as_str())) .collect(); - labels.sort(); - labels + let series = self.builder.intern(&labels); + self.series.insert(key, series); + Ok(Some(series)) } +} + +/// Whether an attribute is a sketch payload: bytes under one of the +/// sketch payload keys. +fn is_sketch_payload(key: &str, value: &AttributeValue) -> bool { + matches!( + key, + "kll.sketch_payload" | "cms.sketch_payload" | "countsketch.sketch_payload" + ) && matches!(value, AttributeValue::Bytes(_)) +} - const NANOS: u64 = 1_700_000_000_123_456_789; - const MS: i64 = 1_700_000_000_123; - - /// Gauges and sums give one point each, labeled by the metric name and - /// the scope's, resource's and point's attributes (the resource's over - /// the scope's, the point's over both), at the point's time in ms. A - /// counter, a gauge and an up-down counter as the OTLP test exporter - /// sends them. - #[test] - fn gauges_and_sums_give_one_point_each() { - let body = encode(&request(vec![ - metric( - "http_requests_total", - Data::Sum(Sum { - data_points: vec![number_point( - vec![text("method", "GET"), text("status", "200")], - NANOS, - number_data_point::Value::AsInt(42), - )], - is_monotonic: true, - ..Default::default() - }), - ), - metric( - "http_active_connections", - Data::Gauge(Gauge { - data_points: vec![number_point( - vec![ - text("scope", "point's"), - attribute("shard", any_value::Value::IntValue(3)), - ], - NANOS, - number_data_point::Value::AsDouble(-1.5), - )], - }), - ), - ])); - let points = decode(&body, None, &LIMITS).unwrap(); - assert_eq!( - points, - vec![ - Point { - labels: labels(&[ - ("__name__", "http_requests_total"), - ("method", "GET"), - ("scope", "s"), - ("service.name", "api-gateway"), - ("status", "200"), - ]), - timestamp_ms: MS, - value: 42.0, - }, - Point { - labels: labels(&[ - ("__name__", "http_active_connections"), - ("scope", "point's"), - ("service.name", "api-gateway"), - ("shard", "3"), - ]), - timestamp_ms: MS, - value: -1.5, - }, - ] - ); +/// An attribute's value: its label text, or bytes, whose label text +/// ([`AttributeValue::text`]) is only built for a label. +enum AttributeValue<'a> { + Text(Cow<'a, str>), + Bytes(&'a [u8]), +} + +impl AttributeValue<'_> { + /// The value as label text: bytes as their debug text (`[1, 2]`). + fn text(&self) -> Cow<'_, str> { + match self { + AttributeValue::Text(text) => Cow::Borrowed(text), + AttributeValue::Bytes(bytes) => Cow::Owned(format!("{bytes:?}")), + } } +} - /// Histograms, exponential histograms and summaries give `_sum` (when - /// set) and `_count` points; buckets and quantiles are not read. - #[test] - fn distributions_give_sum_and_count_points() { - let body = encode(&request(vec![ - metric( - "http_request_duration_seconds", - Data::Histogram(Histogram { - data_points: vec![ - HistogramDataPoint { - time_unix_nano: NANOS, - count: 3, - sum: Some(0.45), - bucket_counts: vec![1, 2], - explicit_bounds: vec![0.1], - ..Default::default() - }, - HistogramDataPoint { - attributes: vec![text("method", "PUT")], - time_unix_nano: NANOS, - count: 1, - sum: None, - ..Default::default() - }, - ], - ..Default::default() - }), - ), - metric( - "size", - Data::ExponentialHistogram(ExponentialHistogram { - data_points: vec![ExponentialHistogramDataPoint { - time_unix_nano: NANOS, - count: 7, - sum: Some(70.0), - ..Default::default() - }], - ..Default::default() - }), - ), - metric( - "latency", - Data::Summary(Summary { - data_points: vec![SummaryDataPoint { - time_unix_nano: NANOS, - count: 2, - sum: 5.0, - ..Default::default() - }], - }), - ), - ])); - let points: Vec<(String, f64)> = decode(&body, None, &LIMITS) - .unwrap() - .into_iter() - .map(|point| { - let name = point.labels.iter().find(|(n, _)| n == "__name__").unwrap(); - (name.1.clone(), point.value) - }) - .collect(); - let expected: Vec<(String, f64)> = [ - ("http_request_duration_seconds_sum", 0.45), - ("http_request_duration_seconds_count", 3.0), - ("http_request_duration_seconds_count", 1.0), - ("size_sum", 70.0), - ("size_count", 7.0), - ("latency_sum", 5.0), - ("latency_count", 2.0), - ] - .into_iter() - .map(|(name, value)| (name.to_string(), value)) - .collect(); - assert_eq!(points, expected); +/// The key and value of an encoded `KeyValue`: its key (field 1) and its +/// `AnyValue` (field 2): a string as is, an integer, double or boolean +/// printed, bytes as bytes; an array, a key-value list or no value as empty +/// text. +fn key_value(bytes: &[u8]) -> Result<(&str, AttributeValue<'_>), OtlpError> { + let mut key = ""; + let mut value = AttributeValue::Text(Cow::Borrowed("")); + let mut reader = Reader::new(bytes); + while let Some((field, found)) = reader.field()? { + match (field, found) { + (1, Value::Bytes(text)) => key = utf8(text)?, + (2, Value::Bytes(any_value)) => value = attribute_value(any_value)?, + _ => {} + } } + Ok((key, value)) +} - /// Sketch payload points and unnamed metrics are skipped; a point with - /// no value reads 0, as in ASAPQuery. - #[test] - fn skips_sketch_payloads_and_unnamed_metrics() { - let sketch = attribute( - "kll.sketch_payload", - any_value::Value::BytesValue(vec![1, 2]), - ); - let body = encode(&request(vec![ - metric( - "m", - Data::Gauge(Gauge { - data_points: vec![ - number_point(vec![sketch], NANOS, number_data_point::Value::AsDouble(9.0)), - NumberDataPoint { - time_unix_nano: NANOS, - ..Default::default() - }, - ], - }), - ), - metric( - "", - Data::Gauge(Gauge { - data_points: vec![number_point( - vec![], - NANOS, - number_data_point::Value::AsDouble(1.0), - )], - }), - ), - ])); - let points = decode(&body, None, &LIMITS).unwrap(); - assert_eq!(points.len(), 1); - assert_eq!(points[0].value, 0.0); +/// An encoded `AnyValue` ([`key_value`]). +fn attribute_value(bytes: &[u8]) -> Result, OtlpError> { + let mut value = AttributeValue::Text(Cow::Borrowed("")); + let mut reader = Reader::new(bytes); + while let Some((field, found)) = reader.field()? { + value = match (field, found) { + (1, Value::Bytes(text)) => AttributeValue::Text(Cow::Borrowed(utf8(text)?)), + (2, Value::Varint(boolean)) => { + AttributeValue::Text(Cow::Borrowed(if boolean != 0 { "true" } else { "false" })) + } + (3, Value::Varint(integer)) => { + AttributeValue::Text(Cow::Owned((integer as i64).to_string())) + } + (4, Value::Fixed64(bits)) => { + AttributeValue::Text(Cow::Owned(f64::from_bits(bits).to_string())) + } + (7, Value::Bytes(bytes)) => AttributeValue::Bytes(bytes), + _ => AttributeValue::Text(Cow::Borrowed("")), + }; } + Ok(value) +} + +fn utf8(bytes: &[u8]) -> Result<&str, OtlpError> { + std::str::from_utf8(bytes).map_err(|e| OtlpError::Protobuf(format!("string is not UTF-8: {e}"))) +} - fn gzip(bytes: &[u8]) -> Vec { - use std::io::Write; - let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); - encoder.write_all(bytes).unwrap(); - encoder.finish().unwrap() +/// A series' labels, sorted by name: the point's `attributes` (sorted +/// here), then the resource's promoted attributes where no attribute gave +/// the label, then `job` and `instance` from the resource, then +/// `__name__`, as Prometheus' `createAttributes` merges them. +fn series_labels( + resource: &ResourceLabels, + name: &str, + attributes: &mut [(&str, AttributeValue)], +) -> Vec<(Cow<'static, str>, String)> { + attributes.sort_by(|a, b| a.0.cmp(b.0)); + let mut labels: BTreeMap, String> = BTreeMap::new(); + for (key, value) in attributes.iter() { + let Some(label) = label_name(key) else { + continue; + }; + match labels.entry(Cow::Owned(label.into_owned())) { + Entry::Occupied(mut joined) => { + joined.get_mut().push(';'); + joined.get_mut().push_str(&value.text()); + } + Entry::Vacant(_) if value.text().is_empty() => {} + Entry::Vacant(entry) => { + entry.insert(value.text().into_owned()); + } + } } + for (label, value) in &resource.promoted { + labels + .entry(Cow::Owned(label.clone())) + .or_insert_with(|| value.clone()); + } + if let Some(job) = &resource.job { + labels.insert(Cow::Borrowed("job"), job.clone()); + } + if let Some(instance) = &resource.instance { + labels.insert(Cow::Borrowed("instance"), instance.clone()); + } + labels.insert(Cow::Borrowed("__name__"), name.to_string()); + labels.into_iter().collect() +} + +/// An OTLP attribute name as a Prometheus label name, as Prometheus' OTLP +/// receiver escapes it by default (`otlptranslator.LabelNamer` with UTF-8 +/// names off, `label_name_underscore_sanitization: true` and +/// `label_name_preserve_multiple_underscores: true`): each character other +/// than an ASCII letter or digit becomes `_`; then a name that starts with +/// a digit gets `key_` before it, and one that starts with a single `_` +/// gets `key`. `None` for a name Prometheus refuses: empty, or only +/// underscores once escaped. +pub(crate) fn label_name(name: &str) -> Option> { + let first = *name.as_bytes().first()?; + let valid = |c: char| c.is_ascii_alphanumeric() || c == '_'; + let label = if name.chars().all(valid) && !first.is_ascii_digit() && !single_underscore(name) { + Cow::Borrowed(name) + } else { + let escaped: String = name + .chars() + .map(|c| if valid(c) { c } else { '_' }) + .collect(); + if escaped.as_bytes()[0].is_ascii_digit() { + Cow::Owned(format!("key_{escaped}")) + } else if single_underscore(&escaped) { + Cow::Owned(format!("key{escaped}")) + } else { + Cow::Owned(escaped) + } + }; + (!label.bytes().all(|b| b == b'_')).then_some(label) +} + +fn single_underscore(name: &str) -> bool { + name.starts_with('_') && !name.starts_with("__") +} + +/// How an OTLP/HTTP request's body is encoded, by its `Content-Type`; the +/// reply is encoded the same way. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Encoding { + /// `application/x-protobuf`, and any other or no content type. + Protobuf, + /// `application/json`. + Json, +} - fn one_gauge() -> Vec { - encode(&request(vec![metric( - "g", - Data::Gauge(Gauge { - data_points: vec![ - number_point(vec![], NANOS, number_data_point::Value::AsDouble(1.0)), - number_point(vec![], NANOS + 1, number_data_point::Value::AsDouble(2.0)), - ], - }), - )])) +impl Encoding { + pub fn of_content_type(content_type: Option<&str>) -> Self { + let media_type = content_type + .and_then(|value| value.split(';').next()) + .map(str::trim); + if media_type.is_some_and(|t| t.eq_ignore_ascii_case("application/json")) { + Encoding::Json + } else { + Encoding::Protobuf + } } - /// A gzip body decodes to the points of the same body uncompressed. - #[test] - fn gzip_bodies_decode_as_uncompressed_ones() { - let body = one_gauge(); - let limits = LIMITS; - assert_eq!( - decode(&gzip(&body), Some(" GZIP "), &limits), - decode(&body, None, &limits) - ); - assert!(matches!( - decode(&body, Some("gzip"), &limits), - Err(OtlpError::Gzip(_)) - )); + pub fn content_type(self) -> &'static str { + match self { + Encoding::Protobuf => "application/x-protobuf", + Encoding::Json => "application/json", + } } +} - /// Bodies that are not OTLP protobuf, and bodies over a limit, are - /// rejected. - #[test] - fn rejects_malformed_and_oversized_bodies() { - let limits = LIMITS; - assert!(matches!( - decode(&[0xff; 8], None, &limits), - Err(OtlpError::Protobuf(_)) - )); - let body = one_gauge(); - let small = Limits { - max_decompressed_bytes: 4, - ..LIMITS - }; - assert_eq!( - decode(&body, None, &small), - Err(OtlpError::DecompressedTooLarge(4)) - ); - assert_eq!( - decode(&gzip(&body), Some("gzip"), &small), - Err(OtlpError::DecompressedTooLarge(4)) - ); - let one = Limits { - max_points: 1, - ..LIMITS - }; - assert_eq!(decode(&body, None, &one), Err(OtlpError::TooManyPoints(1))); +/// The body of a 200 reply to a protobuf request: an encoded +/// `ExportMetricsServiceResponse`, with `partial_success` set to +/// `rejected_points` and `message` when points were rejected, as OTLP/HTTP +/// asks. The empty message (no `partial_success`) is no bytes. +pub fn export_response_body(rejected_points: u64, message: Option<&str>) -> Vec { + use proto::collector::metrics::v1::{ + ExportMetricsPartialSuccess, ExportMetricsServiceResponse, + }; + let partial_success = (rejected_points > 0).then(|| ExportMetricsPartialSuccess { + rejected_data_points: rejected_points as i64, + error_message: message.unwrap_or_default().to_string(), + }); + ExportMetricsServiceResponse { partial_success }.encode_to_vec() +} + +/// `google.rpc.Status`, the body of every 4xx and 5xx OTLP/HTTP reply, +/// with its `message` only: OTLP/HTTP does not use `code` (field 1), and +/// no `details` (field 3) are sent. +#[derive(Clone, PartialEq, Message)] +pub struct Status { + #[prost(string, tag = "2")] + pub message: String, +} + +/// The body of a 4xx or 5xx reply: a `Status` with `message`, encoded as +/// the request was. +pub fn status_body(encoding: Encoding, message: &str) -> Vec { + match encoding { + Encoding::Protobuf => Status { + message: message.to_string(), + } + .encode_to_vec(), + Encoding::Json => serde_json::to_vec(&serde_json::json!({ "message": message })) + .expect("a JSON object serializes"), } } + +#[cfg(test)] +mod tests; diff --git a/crates/adapters/ingest/otlp/src/tests.rs b/crates/adapters/ingest/otlp/src/tests.rs new file mode 100644 index 000000000..2658614ac --- /dev/null +++ b/crates/adapters/ingest/otlp/src/tests.rs @@ -0,0 +1,887 @@ +use super::*; +use proto::collector::metrics::v1::{ExportMetricsServiceRequest, ExportMetricsServiceResponse}; +use proto::common::v1::{any_value, AnyValue, InstrumentationScope, KeyValue}; +use proto::metrics::v1::{ + metric::Data, number_data_point, ExponentialHistogram, ExponentialHistogramDataPoint, Gauge, + Histogram, HistogramDataPoint, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, Sum, + Summary, SummaryDataPoint, +}; +use proto::resource::v1::Resource; + +const LIMITS: Limits = Limits { + max_decompressed_bytes: 128 * 1024 * 1024, + max_points: 1_000_000, +}; + +type Labels = Vec<(String, String)>; + +/// A builder whose series handle is an index into `series`, the labels of +/// each series it interned, in order. +#[derive(Default)] +struct Labeled { + series: Vec, +} + +impl SampleBuilder for Labeled { + type Series = usize; + type Sample = (usize, i64, f64); + + fn intern(&mut self, labels: &[(&str, &str)]) -> usize { + self.series.push( + labels + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(), + ); + self.series.len() - 1 + } + + fn sample(series: usize, timestamp_ms: i64, value: f64) -> Self::Sample { + (series, timestamp_ms, value) + } +} + +/// One sample, with its series' labels. +#[derive(Debug, PartialEq)] +struct Point { + labels: Labels, + timestamp_ms: i64, + value: f64, +} + +/// The points of `body`, decoded by a new decoder with `options`. +fn decode_with( + body: &[u8], + content_encoding: Option<&str>, + options: &LabelOptions, + limits: &Limits, +) -> Result, OtlpError> { + let mut decoder = Decoder::new(Labeled::default()); + let decoded = decoder.decode(body, content_encoding, options, limits)?; + let series = &decoder.builder.series; + Ok(Decoded { + samples: decoded + .samples + .into_iter() + .map(|(index, timestamp_ms, value)| Point { + labels: series[index].clone(), + timestamp_ms, + value, + }) + .collect(), + rejected_points: decoded.rejected_points, + }) +} + +fn decode(body: &[u8]) -> Vec { + decode_with(body, None, &LabelOptions::default(), &LIMITS) + .unwrap() + .samples +} + +fn encode(request: &ExportMetricsServiceRequest) -> Vec { + request.encode_to_vec() +} + +fn attribute(key: &str, value: any_value::Value) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { value: Some(value) }), + } +} + +fn text(key: &str, value: &str) -> KeyValue { + attribute(key, any_value::Value::StringValue(value.to_string())) +} + +fn number_point( + attributes: Vec, + nanos: u64, + value: number_data_point::Value, +) -> NumberDataPoint { + NumberDataPoint { + attributes, + time_unix_nano: nanos, + value: Some(value), + ..Default::default() + } +} + +fn gauge(name: &str, data_points: Vec) -> Metric { + metric(name, Data::Gauge(Gauge { data_points })) +} + +fn metric(name: &str, data: Data) -> Metric { + Metric { + name: name.to_string(), + data: Some(data), + ..Default::default() + } +} + +/// A request with one resource of `resource` attributes and one scope +/// holding `metrics`. +fn request_with(resource: Vec, metrics: Vec) -> ExportMetricsServiceRequest { + ExportMetricsServiceRequest { + resource_metrics: vec![ResourceMetrics { + resource: Some(Resource { + attributes: resource, + ..Default::default() + }), + scope_metrics: vec![ScopeMetrics { + scope: Some(InstrumentationScope { + name: "exporter".to_string(), + version: "1.0".to_string(), + attributes: vec![text("scope", "s")], + ..Default::default() + }), + metrics, + ..Default::default() + }], + ..Default::default() + }], + } +} + +/// A request from the `api-gateway` service. +fn request(metrics: Vec) -> ExportMetricsServiceRequest { + request_with(vec![text("service.name", "api-gateway")], metrics) +} + +fn labels(pairs: &[(&str, &str)]) -> Labels { + let mut labels: Labels = pairs + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(); + labels.sort(); + labels +} + +const NANOS: u64 = 1_700_000_000_123_456_789; +const MS: i64 = 1_700_000_000_123; + +/// Gauges and sums give one point each, labeled by the metric name, the +/// point's attributes and `job` from the resource's `service.name`, at +/// the point's time in ms. The scope's name, version and attributes are +/// not labels. A counter, a gauge and an up-down counter as the OTLP test +/// exporter sends them. +#[test] +fn gauges_and_sums_give_one_point_each() { + let body = encode(&request(vec![ + metric( + "http_requests_total", + Data::Sum(Sum { + data_points: vec![number_point( + vec![text("method", "GET"), text("status", "200")], + NANOS, + number_data_point::Value::AsInt(42), + )], + is_monotonic: true, + aggregation_temporality: 2, + }), + ), + gauge( + "http_active_connections", + vec![number_point( + vec![ + text("scope", "point's"), + attribute("shard", any_value::Value::IntValue(3)), + ], + NANOS, + number_data_point::Value::AsDouble(-1.5), + )], + ), + ])); + assert_eq!( + decode(&body), + vec![ + Point { + labels: labels(&[ + ("__name__", "http_requests_total"), + ("job", "api-gateway"), + ("method", "GET"), + ("status", "200"), + ]), + timestamp_ms: MS, + value: 42.0, + }, + Point { + labels: labels(&[ + ("__name__", "http_active_connections"), + ("job", "api-gateway"), + ("scope", "point's"), + ("shard", "3"), + ]), + timestamp_ms: MS, + value: -1.5, + }, + ] + ); +} + +/// Histograms, exponential histograms and summaries give `_sum` (when +/// set) and `_count` points; buckets and quantiles are not read. +#[test] +fn distributions_give_sum_and_count_points() { + let body = encode(&request(vec![ + metric( + "http_request_duration_seconds", + Data::Histogram(Histogram { + data_points: vec![ + HistogramDataPoint { + time_unix_nano: NANOS, + count: 3, + sum: Some(0.45), + bucket_counts: vec![1, 2], + explicit_bounds: vec![0.1], + ..Default::default() + }, + HistogramDataPoint { + attributes: vec![text("method", "PUT")], + time_unix_nano: NANOS, + count: 1, + sum: None, + ..Default::default() + }, + ], + ..Default::default() + }), + ), + metric( + "size", + Data::ExponentialHistogram(ExponentialHistogram { + data_points: vec![ExponentialHistogramDataPoint { + attributes: vec![text("method", "GET")], + time_unix_nano: NANOS, + count: 7, + sum: Some(70.0), + ..Default::default() + }], + ..Default::default() + }), + ), + metric( + "latency", + Data::Summary(Summary { + data_points: vec![ + SummaryDataPoint { + time_unix_nano: NANOS, + count: 2, + sum: 5.0, + ..Default::default() + }, + // A zero sum is not encoded, and still reads 0. + SummaryDataPoint { + time_unix_nano: NANOS, + count: 4, + sum: 0.0, + attributes: vec![text("method", "GET")], + ..Default::default() + }, + ], + }), + ), + ])); + let points: Vec<(String, Option, f64)> = decode(&body) + .into_iter() + .map(|point| { + let label = |name: &str| { + point + .labels + .iter() + .find(|(n, _)| n == name) + .map(|(_, value)| value.clone()) + }; + (label("__name__").unwrap(), label("method"), point.value) + }) + .collect(); + let get = Some("GET".to_string()); + let expected = vec![ + ("http_request_duration_seconds_sum", None, 0.45), + ("http_request_duration_seconds_count", None, 3.0), + ( + "http_request_duration_seconds_count", + Some("PUT".into()), + 1.0, + ), + ("size_sum", get.clone(), 70.0), + ("size_count", get.clone(), 7.0), + ("latency_sum", None, 5.0), + ("latency_count", None, 2.0), + ("latency_sum", get.clone(), 0.0), + ("latency_count", get, 4.0), + ]; + let expected: Vec<(String, Option, f64)> = expected + .into_iter() + .map(|(name, method, value)| (name.to_string(), method, value)) + .collect(); + assert_eq!(points, expected); +} + +/// Sketch payload points and unnamed metrics are skipped; a point with no +/// value reads 0, as in ASAPQuery and Prometheus. +#[test] +fn skips_sketch_payloads_and_unnamed_metrics() { + let sketch = attribute( + "kll.sketch_payload", + any_value::Value::BytesValue(vec![1, 2]), + ); + let body = encode(&request(vec![ + gauge( + "m", + vec![ + number_point(vec![sketch], NANOS, number_data_point::Value::AsDouble(9.0)), + NumberDataPoint { + time_unix_nano: NANOS, + ..Default::default() + }, + ], + ), + gauge( + "", + vec![number_point( + vec![], + NANOS, + number_data_point::Value::AsDouble(1.0), + )], + ), + ])); + let points = decode(&body); + assert_eq!(points.len(), 1); + assert_eq!(points[0].value, 0.0); +} + +/// Resource attributes are not labels: `service.name` gives `job`, as +/// `/` when the namespace is set, over a +/// point attribute `job`; `service.instance.id` gives `instance`. As +/// Prometheus' OTLP receiver does by default. +#[test] +fn resource_attributes_give_job_and_instance() { + let point = || { + gauge( + "g", + vec![number_point( + vec![text("job", "point's"), text("region", "eu")], + NANOS, + number_data_point::Value::AsDouble(1.0), + )], + ) + }; + let sdk_resource = vec![ + text("service.name", "cart"), + text("service.namespace", "shop"), + text("service.instance.id", "cart-7"), + text("host.name", "node-1"), + text("telemetry.sdk.language", "rust"), + ]; + let points = decode(&encode(&request_with(sdk_resource, vec![point()]))); + assert_eq!( + points[0].labels, + labels(&[ + ("__name__", "g"), + ("instance", "cart-7"), + ("job", "shop/cart"), + ("region", "eu"), + ]) + ); + // No `service.name`: the point's `job` stays. + let points = decode(&encode(&request_with( + vec![text("host.name", "node-1")], + vec![point()], + ))); + assert_eq!( + points[0].labels, + labels(&[("__name__", "g"), ("job", "point's"), ("region", "eu")]) + ); +} + +/// Promoted resource attributes are labels, their names escaped, unless a +/// point attribute gives the same label; resource attributes not named, or +/// absent, give nothing. +#[test] +fn promoted_resource_attributes_are_labels() { + let body = encode(&request_with( + vec![ + text("service.name", "cart"), + text("deployment.environment", "prod"), + text("region", "from-resource"), + text("host.name", "node-1"), + ], + vec![gauge( + "g", + vec![number_point( + vec![text("region", "eu")], + NANOS, + number_data_point::Value::AsDouble(1.0), + )], + )], + )); + let options = LabelOptions { + promote_resource_attributes: vec![ + "deployment.environment".into(), + "region".into(), + "k8s.pod.name".into(), + ], + }; + let points = decode_with(&body, None, &options, &LIMITS).unwrap().samples; + assert_eq!( + points[0].labels, + labels(&[ + ("__name__", "g"), + ("deployment_environment", "prod"), + ("job", "cart"), + ("region", "eu"), + ]) + ); +} + +/// Attribute names are escaped as Prometheus' default translation strategy +/// escapes them; names that escape to the same label join their values with +/// `;` in the order of the names; an empty value is no label. +#[test] +fn attribute_names_are_escaped_as_prometheus_does() { + for (name, label) in [ + ("http.method", Some("http_method")), + ("already_valid", Some("already_valid")), + ("a..b", Some("a__b")), + ("héllo", Some("h_llo")), + ("1st", Some("key_1st")), + ("_private", Some("key_private")), + ("__reserved__", Some("__reserved__")), + ("...", None), + ("", None), + ] { + assert_eq!(label_name(name).as_deref(), label, "{name:?}"); + } + let body = encode(&request_with( + vec![], + vec![gauge( + "g", + vec![number_point( + vec![ + text("a_b", "2"), + text("a.b", "1"), + text("empty", ""), + text("...", "dropped"), + attribute("on", any_value::Value::BoolValue(true)), + attribute("ratio", any_value::Value::DoubleValue(0.5)), + ], + NANOS, + number_data_point::Value::AsDouble(1.0), + )], + )], + )); + assert_eq!( + decode(&body)[0].labels, + labels(&[ + ("__name__", "g"), + ("a_b", "1;2"), + ("on", "true"), + ("ratio", "0.5"), + ]) + ); +} + +/// The points of a sum with DELTA temporality are rejected and counted, +/// those of cumulative sums (and of unspecified temporality) ingested. +/// Histograms are read whatever their temporality. +#[test] +fn delta_sums_are_rejected() { + let sum = |name: &str, temporality: i32, points: usize| { + metric( + name, + Data::Sum(Sum { + data_points: (0..points) + .map(|i| { + number_point( + vec![text("i", &i.to_string())], + NANOS, + number_data_point::Value::AsInt(i as i64), + ) + }) + .collect(), + aggregation_temporality: temporality, + is_monotonic: true, + }), + ) + }; + let delta_histogram = metric( + "h", + Data::Histogram(Histogram { + data_points: vec![HistogramDataPoint { + time_unix_nano: NANOS, + count: 1, + ..Default::default() + }], + aggregation_temporality: 1, + }), + ); + let body = encode(&request(vec![ + sum("cumulative", 2, 2), + sum("delta", 1, 3), + sum("unspecified", 0, 1), + delta_histogram, + ])); + let decoded = decode_with(&body, None, &LabelOptions::default(), &LIMITS).unwrap(); + let names: Vec<&str> = decoded + .samples + .iter() + .map(|point| { + point + .labels + .iter() + .find(|(n, _)| n == "__name__") + .unwrap() + .1 + .as_str() + }) + .collect(); + assert_eq!( + names, + ["cumulative", "cumulative", "unspecified", "h_count"] + ); + assert_eq!(decoded.rejected_points, 3); + assert!(decoded + .rejection_message() + .unwrap() + .starts_with("3 data points")); +} + +/// Prometheus' stale marker (`value.StaleNaN` in Prometheus' +/// `model/value`), as its bits. +const STALE_NAN_BITS: u64 = 0x7ff0_0000_0000_0002; + +/// Points flagged "no recorded value" give Prometheus' stale marker for +/// each sample the point gives, as Prometheus' OTLP receiver writes them +/// (`otlptranslator/prometheusremotewrite`: the value, a histogram's +/// `_sum` when set and `_count`, a summary's `_sum` and `_count`), not 0 +/// and not nothing. +#[test] +fn no_recorded_value_points_give_stale_markers() { + let flagged = |nanos| NumberDataPoint { + time_unix_nano: nanos, + flags: 1, + ..Default::default() + }; + let body = encode(&request(vec![ + gauge( + "g", + vec![ + number_point(vec![], NANOS, number_data_point::Value::AsDouble(1.0)), + flagged(NANOS + 1_000_000), + // A value set on a flagged point is not read. + NumberDataPoint { + value: Some(number_data_point::Value::AsDouble(5.0)), + ..flagged(NANOS + 2_000_000) + }, + ], + ), + metric( + "h", + Data::Histogram(Histogram { + data_points: vec![ + HistogramDataPoint { + time_unix_nano: NANOS, + flags: 1, + ..Default::default() + }, + HistogramDataPoint { + attributes: vec![text("method", "GET")], + time_unix_nano: NANOS, + flags: 1, + count: 4, + sum: Some(2.0), + ..Default::default() + }, + ], + aggregation_temporality: 2, + }), + ), + metric( + "s", + Data::Summary(Summary { + data_points: vec![SummaryDataPoint { + time_unix_nano: NANOS, + flags: 1, + ..Default::default() + }], + }), + ), + ])); + let decoded = decode_with(&body, None, &LabelOptions::default(), &LIMITS).unwrap(); + let samples: Vec<(&str, i64, u64)> = decoded + .samples + .iter() + .map(|point| { + let name = point.labels.iter().find(|(n, _)| n == "__name__").unwrap(); + (name.1.as_str(), point.timestamp_ms, point.value.to_bits()) + }) + .collect(); + let ms = (NANOS / 1_000_000) as i64; + assert_eq!( + samples, + [ + ("g", ms, 1.0f64.to_bits()), + ("g", ms + 1, STALE_NAN_BITS), + ("g", ms + 2, STALE_NAN_BITS), + // No `_sum`: the point has none. + ("h_count", ms, STALE_NAN_BITS), + ("h_sum", ms, STALE_NAN_BITS), + ("h_count", ms, STALE_NAN_BITS), + ("s_sum", ms, STALE_NAN_BITS), + ("s_count", ms, STALE_NAN_BITS), + ] + ); + assert_eq!(decoded.rejected_points, 0); + assert_eq!(decoded.rejection_message(), None); +} + +/// A decoder interns each series once: a second request with the same +/// series hits its cache. A series differs by its resource's labels, its +/// metric name and its attributes; resource attributes that are not labels +/// do not make another series. +#[test] +fn a_decoder_interns_each_series_once() { + let body = |resource: Vec, name: &str, value: &str| { + encode(&request_with( + resource, + vec![gauge( + name, + vec![number_point( + vec![text("a", value)], + NANOS, + number_data_point::Value::AsDouble(1.0), + )], + )], + )) + }; + let mut decoder = Decoder::new(Labeled::default()); + let mut series = |body: &[u8], options: &LabelOptions| { + let decoded = decoder.decode(body, None, options, &LIMITS).unwrap(); + decoded.samples[0].0 + }; + let none = LabelOptions::default(); + let job = || vec![text("service.name", "x"), text("host.name", "h")]; + let first = series(&body(job(), "g", "1"), &none); + assert_eq!(series(&body(job(), "g", "1"), &none), first); + assert_eq!( + series(&body(vec![text("service.name", "x")], "g", "1"), &none), + first + ); + let others = [ + series(&body(job(), "g", "2"), &none), + series(&body(job(), "g2", "1"), &none), + series(&body(vec![text("service.name", "y")], "g", "1"), &none), + series( + &body(job(), "g", "1"), + &LabelOptions { + promote_resource_attributes: vec!["host.name".into()], + }, + ), + ]; + assert_eq!(others, [1, 2, 3, 4]); + assert_eq!(decoder.builder.series.len(), 5); +} + +/// Attributes interleaved with a point's other fields decode as the same +/// attributes written together. +#[test] +fn interleaved_attributes_decode_as_contiguous_ones() { + let field = |number: u32, bytes: &[u8]| { + let mut out = Vec::new(); + prost::encoding::encode_key(number, prost::encoding::WireType::LengthDelimited, &mut out); + prost::encoding::encode_varint(bytes.len() as u64, &mut out); + out.extend_from_slice(bytes); + out + }; + let a = text("a", "1").encode_to_vec(); + let b = text("b", "2").encode_to_vec(); + let mut time = Vec::new(); + prost::encoding::fixed64::encode(3, &NANOS, &mut time); + let mut value = Vec::new(); + prost::encoding::double::encode(4, &5.0, &mut value); + let point = [field(7, &a), time, field(7, &b), value].concat(); + let gauge = field(1, &point); + let metric = [field(1, b"g"), field(5, &gauge)].concat(); + let scope_metrics = field(2, &metric); + let resource_metrics = field(2, &scope_metrics); + let body = field(1, &resource_metrics); + let expected = Point { + labels: labels(&[("__name__", "g"), ("a", "1"), ("b", "2")]), + timestamp_ms: MS, + value: 5.0, + }; + assert_eq!(decode(&body), vec![expected]); +} + +fn gzip(bytes: &[u8]) -> Vec { + use std::io::Write; + let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + encoder.write_all(bytes).unwrap(); + encoder.finish().unwrap() +} + +fn one_gauge() -> Vec { + encode(&request(vec![gauge( + "g", + vec![ + number_point(vec![], NANOS, number_data_point::Value::AsDouble(1.0)), + number_point(vec![], NANOS + 1, number_data_point::Value::AsDouble(2.0)), + ], + )])) +} + +/// A gzip body decodes to the points of the same body uncompressed. +#[test] +fn gzip_bodies_decode_as_uncompressed_ones() { + let body = one_gauge(); + let none = LabelOptions::default(); + assert_eq!( + decode_with(&gzip(&body), Some(" GZIP "), &none, &LIMITS), + decode_with(&body, None, &none, &LIMITS) + ); + assert!(matches!( + decode_with(&body, Some("gzip"), &none, &LIMITS), + Err(OtlpError::Gzip(_)) + )); +} + +/// Bodies that are not OTLP protobuf, and bodies over a limit, are +/// rejected. +#[test] +fn rejects_malformed_and_oversized_bodies() { + let none = LabelOptions::default(); + assert!(matches!( + decode_with(&[0xff; 8], None, &none, &LIMITS), + Err(OtlpError::Protobuf(_)) + )); + // A metric name that is not UTF-8. + let mut body = one_gauge(); + let at = body + .windows(3) + .position(|w| w == [0x0a, 0x01, b'g']) + .unwrap(); + body[at + 2] = 0xff; + assert!(matches!( + decode_with(&body, None, &none, &LIMITS), + Err(OtlpError::Protobuf(_)) + )); + let body = one_gauge(); + let small = Limits { + max_decompressed_bytes: 4, + ..LIMITS + }; + assert_eq!( + decode_with(&body, None, &none, &small), + Err(OtlpError::DecompressedTooLarge(4)) + ); + assert_eq!( + decode_with(&gzip(&body), Some("gzip"), &none, &small), + Err(OtlpError::DecompressedTooLarge(4)) + ); + let one = Limits { + max_points: 1, + ..LIMITS + }; + assert_eq!( + decode_with(&body, None, &none, &one), + Err(OtlpError::TooManyPoints(1)) + ); +} + +/// The replies decode as the OTLP messages: an empty +/// `ExportMetricsServiceResponse` on full success, its `partial_success` +/// with the rejected points otherwise, and a `Status` with the message for +/// errors, as protobuf or JSON. +#[test] +fn replies_are_otlp_messages() { + assert!(export_response_body(0, None).is_empty()); + assert_eq!( + ExportMetricsServiceResponse::decode(&export_response_body(0, None)[..]).unwrap(), + ExportMetricsServiceResponse::default() + ); + let partial = ExportMetricsServiceResponse::decode(&export_response_body(3, Some("why"))[..]) + .unwrap() + .partial_success + .unwrap(); + assert_eq!( + (partial.rejected_data_points, partial.error_message.as_str()), + (3, "why") + ); + let error = Status::decode(&status_body(Encoding::Protobuf, "bad body")[..]).unwrap(); + assert_eq!(error.message, "bad body"); + let error: serde_json::Value = + serde_json::from_slice(&status_body(Encoding::Json, "bad")).unwrap(); + assert_eq!(error, serde_json::json!({ "message": "bad" })); + for (content_type, encoding) in [ + (None, Encoding::Protobuf), + (Some("application/x-protobuf"), Encoding::Protobuf), + (Some("Application/JSON; charset=utf-8"), Encoding::Json), + (Some("text/plain"), Encoding::Protobuf), + ] { + assert_eq!(Encoding::of_content_type(content_type), encoding); + } +} + +/// Consecutive points with the same attributes take the previous point's +/// series; a point with other attributes, or of another metric, does not. +#[test] +fn consecutive_points_share_their_series() { + let point = |value: &str| { + number_point( + vec![text("a", value)], + NANOS, + number_data_point::Value::AsDouble(1.0), + ) + }; + let body = encode(&request_with( + vec![], + vec![ + gauge("g", vec![point("1"), point("1"), point("2"), point("1")]), + gauge("h", vec![point("1")]), + metric( + "d", + Data::Histogram(Histogram { + data_points: vec![ + HistogramDataPoint { + attributes: vec![text("a", "1")], + count: 1, + ..Default::default() + }, + HistogramDataPoint { + attributes: vec![text("a", "1")], + count: 2, + sum: Some(3.0), + ..Default::default() + }, + ], + aggregation_temporality: 2, + }), + ), + ], + )); + let names: Vec = decode(&body) + .into_iter() + .map(|point| { + point + .labels + .iter() + .map(|(name, value)| format!("{name}={value}")) + .collect::>() + .join(",") + }) + .collect(); + assert_eq!( + names, + [ + "__name__=g,a=1", + "__name__=g,a=1", + "__name__=g,a=2", + "__name__=g,a=1", + "__name__=h,a=1", + "__name__=d_count,a=1", + "__name__=d_sum,a=1", + "__name__=d_count,a=1", + ] + ); +} diff --git a/crates/adapters/ingest/prometheus-remote-write/Cargo.toml b/crates/adapters/ingest/prometheus-remote-write/Cargo.toml index 9224d9faa..e62407528 100644 --- a/crates/adapters/ingest/prometheus-remote-write/Cargo.toml +++ b/crates/adapters/ingest/prometheus-remote-write/Cargo.toml @@ -5,7 +5,9 @@ edition.workspace = true # Prometheus Remote Write v1: request decoding and validation. An adapter: # no workspace dependency, so it never sees an engine or a store. The -# caller interns each series into its own series type (`Decoder`). +# caller interns each series into its own series type (`Decoder`). Its +# in-place protobuf reader (`wire`) and series cache (`series_cache`) also +# serve the `otlp` decoder. [dependencies] prost = "0.13" snap = "1.1" diff --git a/crates/adapters/ingest/prometheus-remote-write/src/lib.rs b/crates/adapters/ingest/prometheus-remote-write/src/lib.rs index 2be8f7195..8fb6bf013 100644 --- a/crates/adapters/ingest/prometheus-remote-write/src/lib.rs +++ b/crates/adapters/ingest/prometheus-remote-write/src/lib.rs @@ -9,6 +9,12 @@ use prost::Message; +pub mod series_cache; +pub mod wire; + +use series_cache::SeriesCache; +use wire::{Reader, Value}; + #[derive(Clone, PartialEq, Message)] pub struct WriteRequest { #[prost(message, repeated, tag = "1")] @@ -97,14 +103,14 @@ pub struct Decoder { /// A request's decompressed bytes are written over the last one's, /// with no allocation, zeroing or page faults once it has grown. decompressed: Vec, - cache: SeriesCache, + interner: Interner, } impl Decoder { pub fn new(builder: B) -> Self { Self { decompressed: Vec::new(), - cache: SeriesCache::new(builder), + interner: Interner::new(builder), } } @@ -127,10 +133,10 @@ impl Decoder { ) -> Result, RemoteWriteError> { let Self { decompressed: buffer, - cache, + interner, } = self; let decoded = decompress_into(body, limits, buffer) - .and_then(|request| decode_request(request, cache, limits)); + .and_then(|request| decode_request(request, interner, limits)); // An unusually large request's buffer is not kept, whether or not the // request decoded: a short body claiming a large size and then failing // to decompress must not leave the decoder holding that buffer. @@ -156,7 +162,7 @@ impl Decoder { limits.max_decompressed_bytes, )); } - decode_request(request, &mut self.cache, limits) + decode_request(request, &mut self.interner, limits) } } @@ -167,7 +173,7 @@ impl Decoder { #[inline(always)] fn decode_request( request: &[u8], - cache: &mut SeriesCache, + cache: &mut Interner, limits: &Limits, ) -> Result, RemoteWriteError> { // Room for one sample per 40 encoded bytes: a sender's one-sample @@ -221,7 +227,7 @@ fn decompress_into<'a>( /// Appends the samples of one encoded `TimeSeries` to `samples`. fn decode_series( series: &[u8], - cache: &mut SeriesCache, + cache: &mut Interner, samples: &mut Vec, limits: &Limits, ) -> Result<(), RemoteWriteError> { @@ -360,96 +366,34 @@ fn sample_generic(sample: &[u8]) -> Result<(i64, f64), RemoteWriteError> { Ok((timestamp_ms, value)) } -/// A decoder's series by the bytes of their encoded labels. A sender -/// writes its series in the same order request after request, so each -/// entry remembers the entry looked up after it last time, and a lookup -/// first compares the key with that prediction: a hit costs one compare, -/// no hash. Every hit is a byte-for-byte match of the key. -struct SeriesCache { - entries: Vec>, - /// Entries by the hash of their key. - by_key: hashbrown::HashTable, - /// The entry looked up last. - last: Option, - /// Interns each series seen for the first time. +/// A decoder's series cache with the builder that interns a series seen +/// for the first time. +struct Interner { + cache: SeriesCache, builder: B, } -impl SeriesCache { +impl Interner { fn new(builder: B) -> Self { Self { - entries: Vec::new(), - by_key: hashbrown::HashTable::new(), - last: None, + cache: SeriesCache::new(), builder, } } -} -struct CacheEntry { - key: Box<[u8]>, - series: S, - /// The entry looked up right after this one, last time. - next: Option, -} - -impl SeriesCache { /// The series of the encoded labels `key` (a run of `TimeSeries` /// field-1 entries): from the cache, or parsed, validated and interned - /// by the builder. + /// by the builder. `#[inline(always)]`: without it, one series per + /// sample decodes about 3% slower than with the cache inside `lib.rs`. + #[inline(always)] fn get_or_intern(&mut self, key: &[u8]) -> Result { - if let Some(series) = self.get(key) { + if let Some(series) = self.cache.get(key) { return Ok(series); } let series = parse_labels(key, |labels| self.builder.intern(labels))?; - self.insert(key, series); + self.cache.insert(key, series); Ok(series) } - - fn hash(key: &[u8]) -> u64 { - static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); - STATE.get_or_init(ahash::RandomState::new).hash_one(key) - } - - #[inline] - fn get(&mut self, key: &[u8]) -> Option { - let predicted = self.last.and_then(|last| self.entries[last as usize].next); - if let Some(index) = predicted { - let entry = &self.entries[index as usize]; - if *entry.key == *key { - self.last = Some(index); - return Some(entry.series); - } - } - let entries = &self.entries; - let index = *self - .by_key - .find(Self::hash(key), |&i| *entries[i as usize].key == *key)?; - self.follow(index); - Some(self.entries[index as usize].series) - } - - fn insert(&mut self, key: &[u8], series: B::Series) { - let index = u32::try_from(self.entries.len()).expect("fewer than 2^32 series"); - self.entries.push(CacheEntry { - key: key.into(), - series, - next: None, - }); - let entries = &self.entries; - self.by_key.insert_unique(Self::hash(key), index, |&i| { - Self::hash(&entries[i as usize].key) - }); - self.follow(index); - } - - /// Records that `index` was looked up after the last entry. - fn follow(&mut self, index: u32) { - if let Some(last) = self.last { - self.entries[last as usize].next = Some(index); - } - self.last = Some(index); - } } /// Parses and validates the labels encoded in `key`, and interns them @@ -488,116 +432,6 @@ fn parse_labels( Ok(intern(&pairs)) } -/// One protobuf field value. -enum Value<'a> { - Varint(u64), - Fixed64(u64), - Bytes(&'a [u8]), - Fixed32, -} - -/// A protobuf reader over borrowed bytes. -struct Reader<'a> { - bytes: &'a [u8], - position: usize, - /// Where the field read last starts (its tag). - field_start: usize, -} - -impl<'a> Reader<'a> { - #[inline(always)] - fn new(bytes: &'a [u8]) -> Self { - Self { - bytes, - position: 0, - field_start: 0, - } - } - - #[cold] - fn error(message: &str) -> RemoteWriteError { - RemoteWriteError::Protobuf(message.into()) - } - - #[inline(always)] - fn varint(&mut self) -> Result { - // One byte: most tags and lengths. - if let Some(&byte) = self.bytes.get(self.position) { - if byte < 0x80 { - self.position += 1; - return Ok(u64::from(byte)); - } - } - let (value, position) = varint_slow(self.bytes, self.position)?; - self.position = position; - Ok(value) - } - - #[inline(always)] - fn take(&mut self, len: usize) -> Result<&'a [u8], RemoteWriteError> { - let end = self - .position - .checked_add(len) - .filter(|&end| end <= self.bytes.len()) - .ok_or_else(|| Self::error("field runs past the end of its message"))?; - let taken = &self.bytes[self.position..end]; - self.position = end; - Ok(taken) - } - - /// The next field number and value; `None` at the end. - #[inline(always)] - fn field(&mut self) -> Result)>, RemoteWriteError> { - if self.position == self.bytes.len() { - return Ok(None); - } - self.field_start = self.position; - let tag = self.varint()?; - let field = tag >> 3; - if field == 0 { - return Err(Self::error("field number 0")); - } - let value = match tag & 7 { - 0 => Value::Varint(self.varint()?), - 1 => Value::Fixed64(u64::from_le_bytes( - self.take(8)?.try_into().expect("8 bytes"), - )), - 2 => { - let len = - usize::try_from(self.varint()?).map_err(|_| Self::error("length too large"))?; - Value::Bytes(self.take(len)?) - } - 5 => { - self.take(4)?; - Value::Fixed32 - } - wire => return Err(Self::error(&format!("unsupported wire type {wire}"))), - }; - Ok(Some((field, value))) - } -} - -/// The varint at `position` of `bytes` and the position after it, for a -/// varint of more than one byte. A free function of plain values, not a -/// `Reader` method: the reader then never escapes to this out-of-line, -/// cross-crate call, so its position stays in a register in the callers' -/// loops. -#[inline(never)] -fn varint_slow(bytes: &[u8], mut position: usize) -> Result<(u64, usize), RemoteWriteError> { - let mut value = 0u64; - for shift in (0..64).step_by(7) { - let byte = *bytes - .get(position) - .ok_or_else(|| Reader::error("truncated varint"))?; - position += 1; - value |= u64::from(byte & 0x7f) << shift; - if byte < 0x80 { - return Ok((value, position)); - } - } - Err(Reader::error("varint too long")) -} - /// Snappy-compressed encoding of `request`, as a Remote Write sender sends it. pub fn encode(request: &WriteRequest) -> Vec { snap::raw::Encoder::new() @@ -672,7 +506,7 @@ mod tests { .into_iter() .map(|(series, timestamp_ms, value)| { ( - self.cache.builder.series[series].clone(), + self.interner.builder.series[series].clone(), timestamp_ms, value.to_bits(), ) @@ -811,7 +645,7 @@ mod tests { } // Each series interned once: the second request, and the repeated // series in the first, are cache hits. - assert_eq!(decoder.cache.builder.series.len(), 3); + assert_eq!(decoder.interner.builder.series.len(), 3); let unnamed = WriteRequest { timeseries: vec![series(&[("job", "api")], &[(1, 1.0)])], }; @@ -866,7 +700,7 @@ mod tests { .into_iter() .map(|(series, timestamp_ms, value)| { ( - decoder.cache.builder.series[series].clone(), + decoder.interner.builder.series[series].clone(), timestamp_ms, value.to_bits(), ) diff --git a/crates/adapters/ingest/prometheus-remote-write/src/series_cache.rs b/crates/adapters/ingest/prometheus-remote-write/src/series_cache.rs new file mode 100644 index 000000000..af5642b25 --- /dev/null +++ b/crates/adapters/ingest/prometheus-remote-write/src/series_cache.rs @@ -0,0 +1,81 @@ +//! A decoder's series cache: series handles by the bytes of a key, such as +//! a series' encoded labels, kept between requests. Shared with the other +//! ingest decoders that walk protobuf in place (`otlp`). + +/// Series handles by the bytes of their key. A sender writes its series in +/// the same order request after request, so each entry remembers the entry +/// looked up after it last time, and a lookup first compares the key with +/// that prediction: a hit costs one compare, no hash. Every hit is a +/// byte-for-byte match of the key. +pub struct SeriesCache { + entries: Vec>, + /// Entries by the hash of their key. + by_key: hashbrown::HashTable, + /// The entry looked up last. + last: Option, +} + +struct CacheEntry { + key: Box<[u8]>, + series: S, + /// The entry looked up right after this one, last time. + next: Option, +} + +impl SeriesCache { + #[allow(clippy::new_without_default)] + pub fn new() -> Self { + Self { + entries: Vec::new(), + by_key: hashbrown::HashTable::new(), + last: None, + } + } + + fn hash(key: &[u8]) -> u64 { + static STATE: std::sync::OnceLock = std::sync::OnceLock::new(); + STATE.get_or_init(ahash::RandomState::new).hash_one(key) + } + + /// The series of `key`, if cached. + #[inline] + pub fn get(&mut self, key: &[u8]) -> Option { + let predicted = self.last.and_then(|last| self.entries[last as usize].next); + if let Some(index) = predicted { + let entry = &self.entries[index as usize]; + if *entry.key == *key { + self.last = Some(index); + return Some(entry.series); + } + } + let entries = &self.entries; + let index = *self + .by_key + .find(Self::hash(key), |&i| *entries[i as usize].key == *key)?; + self.follow(index); + Some(self.entries[index as usize].series) + } + + /// Caches `series` under `key`, which is not cached yet. + pub fn insert(&mut self, key: &[u8], series: S) { + let index = u32::try_from(self.entries.len()).expect("fewer than 2^32 series"); + self.entries.push(CacheEntry { + key: key.into(), + series, + next: None, + }); + let entries = &self.entries; + self.by_key.insert_unique(Self::hash(key), index, |&i| { + Self::hash(&entries[i as usize].key) + }); + self.follow(index); + } + + /// Records that `index` was looked up after the last entry. + fn follow(&mut self, index: u32) { + if let Some(last) = self.last { + self.entries[last as usize].next = Some(index); + } + self.last = Some(index); + } +} diff --git a/crates/adapters/ingest/prometheus-remote-write/src/wire.rs b/crates/adapters/ingest/prometheus-remote-write/src/wire.rs new file mode 100644 index 000000000..a9953643a --- /dev/null +++ b/crates/adapters/ingest/prometheus-remote-write/src/wire.rs @@ -0,0 +1,117 @@ +//! A protobuf reader over borrowed bytes, for decoders that walk a request +//! in place instead of building its messages: Remote Write's, and the +//! other ingest decoders' (`otlp`). A malformed message is a +//! [`RemoteWriteError::Protobuf`]. + +use crate::RemoteWriteError; + +/// One protobuf field value. +pub enum Value<'a> { + Varint(u64), + Fixed64(u64), + Bytes(&'a [u8]), + Fixed32, +} + +/// A protobuf reader over borrowed bytes. +pub struct Reader<'a> { + bytes: &'a [u8], + /// Where the next field starts. + pub position: usize, + /// Where the field read last starts (its tag). + pub field_start: usize, +} + +impl<'a> Reader<'a> { + #[inline(always)] + pub fn new(bytes: &'a [u8]) -> Self { + Self { + bytes, + position: 0, + field_start: 0, + } + } + + #[cold] + fn error(message: &str) -> RemoteWriteError { + RemoteWriteError::Protobuf(message.into()) + } + + #[inline(always)] + fn varint(&mut self) -> Result { + // One byte: most tags and lengths. + if let Some(&byte) = self.bytes.get(self.position) { + if byte < 0x80 { + self.position += 1; + return Ok(u64::from(byte)); + } + } + let (value, position) = varint_slow(self.bytes, self.position)?; + self.position = position; + Ok(value) + } + + #[inline(always)] + fn take(&mut self, len: usize) -> Result<&'a [u8], RemoteWriteError> { + let end = self + .position + .checked_add(len) + .filter(|&end| end <= self.bytes.len()) + .ok_or_else(|| Self::error("field runs past the end of its message"))?; + let taken = &self.bytes[self.position..end]; + self.position = end; + Ok(taken) + } + + /// The next field number and value; `None` at the end. + #[inline(always)] + pub fn field(&mut self) -> Result)>, RemoteWriteError> { + if self.position == self.bytes.len() { + return Ok(None); + } + self.field_start = self.position; + let tag = self.varint()?; + let field = tag >> 3; + if field == 0 { + return Err(Self::error("field number 0")); + } + let value = match tag & 7 { + 0 => Value::Varint(self.varint()?), + 1 => Value::Fixed64(u64::from_le_bytes( + self.take(8)?.try_into().expect("8 bytes"), + )), + 2 => { + let len = + usize::try_from(self.varint()?).map_err(|_| Self::error("length too large"))?; + Value::Bytes(self.take(len)?) + } + 5 => { + self.take(4)?; + Value::Fixed32 + } + wire => return Err(Self::error(&format!("unsupported wire type {wire}"))), + }; + Ok(Some((field, value))) + } +} + +/// The varint at `position` of `bytes` and the position after it, for a +/// varint of more than one byte. A free function of plain values, not a +/// `Reader` method: the reader then never escapes to this out-of-line, +/// cross-crate call, so its position stays in a register in the callers' +/// loops. +#[inline(never)] +fn varint_slow(bytes: &[u8], mut position: usize) -> Result<(u64, usize), RemoteWriteError> { + let mut value = 0u64; + for shift in (0..64).step_by(7) { + let byte = *bytes + .get(position) + .ok_or_else(|| Reader::error("truncated varint"))?; + position += 1; + value |= u64::from(byte & 0x7f) << shift; + if byte < 0x80 { + return Ok((value, position)); + } + } + Err(Reader::error("varint too long")) +} diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index 57366176b..a447376b0 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -34,6 +34,7 @@ pub mod remote_write; #[cfg(test)] mod test_support; +use std::sync::atomic::Ordering; use std::sync::Arc; use std::time::Duration; @@ -66,6 +67,8 @@ pub struct DataPlane { pub queries: Vec, pub engine: EngineHandle, pub limits: prometheus_remote_write::Limits, + /// How OTLP resource attributes become labels (`/v1/metrics`). + otlp_label_options: otlp::LabelOptions, /// Never forward a query to Prometheus: a query the plan cannot answer /// gets an error with the reason ([`EngineOptions::no_forward`]). pub no_forward: bool, @@ -110,6 +113,7 @@ impl DataPlane { queries, engine, limits: prometheus_remote_write::Limits::default(), + otlp_label_options: otlp::LabelOptions::default(), fallback: PrometheusHttpFallback::new(&prometheus_url, DEFAULT_FORWARD_TIMEOUT), raw_forward: None, clickhouse_fallback: None, @@ -163,6 +167,13 @@ impl DataPlane { Ok(self) } + /// Labels OTLP series with the resource attributes `options` promotes + /// (`--otlp-promote-resource-attributes`). + pub fn with_otlp_label_options(mut self, options: otlp::LabelOptions) -> Self { + self.otlp_label_options = options; + self + } + /// Bounds each forwarded query by `timeout`, from sending the request to /// reading the whole response (default [`DEFAULT_FORWARD_TIMEOUT`]). pub fn with_forward_timeout(mut self, timeout: Duration) -> Self { @@ -422,7 +433,7 @@ async fn write(State(state): State>, body: Bytes) -> Response { None => None, }; if let Some(refused) = ingest(&state, samples, "Remote Write") { - return refused; + return refused.into_response(); } if let Some(reservation) = reservation { reservation.commit(body); @@ -444,7 +455,7 @@ async fn write_victoriametrics(State(state): State>, body: Bytes) }; if !samples.is_empty() { if let Some(refused) = ingest(&state, samples, "VictoriaMetrics Remote Write") { - return refused; + return refused.into_response(); } } StatusCode::NO_CONTENT.into_response() @@ -452,36 +463,70 @@ async fn write_victoriametrics(State(state): State>, body: Bytes) /// `POST /v1/metrics`: an OTLP/HTTP metrics body (protobuf, gzip when its /// `Content-Encoding` says so), each data point ingested as a sample -/// ([`otlp`]); 200 with `{"rejected": 0}` once the engine has them, as -/// ASAPQuery answers. Not served in forward mode (see [`router`]). +/// ([`otlp`]). Replies as OTLP/HTTP asks: 200 with an +/// `ExportMetricsServiceResponse` once the engine has the samples, its +/// `partial_success` counting the points rejected (sums with DELTA +/// temporality); 400 for a malformed body, 415 for OTLP/JSON, which is not +/// decoded, and 503 or 500 as Remote Write, each with a `google.rpc.Status` +/// body, encoded as the request was. Not served in forward mode (see +/// [`router`]). async fn write_otlp( State(state): State>, headers: HeaderMap, body: Bytes, ) -> Response { - let content_encoding = headers - .get(header::CONTENT_ENCODING) - .and_then(|value| value.to_str().ok()); - let samples = match remote_write::decode_otlp_samples(&body, content_encoding, &state.limits) { - Ok(samples) => samples, - Err(error) => return (StatusCode::BAD_REQUEST, error.to_string()).into_response(), + let header_text = |name| headers.get(name).and_then(|value| value.to_str().ok()); + let encoding = otlp::Encoding::of_content_type(header_text(header::CONTENT_TYPE)); + let failed = |status: StatusCode, message: &str| { + ( + status, + [(header::CONTENT_TYPE, encoding.content_type())], + otlp::status_body(encoding, message), + ) + .into_response() }; - if !samples.is_empty() { - if let Some(refused) = ingest(&state, samples, "OTLP") { - return refused; + if encoding == otlp::Encoding::Json { + return failed( + StatusCode::UNSUPPORTED_MEDIA_TYPE, + "OTLP/JSON is not supported: send application/x-protobuf", + ); + } + let timer = internal_metrics::Timer::start(); + let decoded = match remote_write::decode_otlp_samples( + &body, + header_text(header::CONTENT_ENCODING), + &state.otlp_label_options, + &state.limits, + ) { + Ok(decoded) => decoded, + Err(error) => return failed(StatusCode::BAD_REQUEST, &error.to_string()), + }; + let metrics = state.engine.metrics(); + metrics.otlp_decode.record(timer); + let reply = otlp::export_response_body( + decoded.rejected_points, + decoded.rejection_message().as_deref(), + ); + if !decoded.samples.is_empty() { + if let Some((status, message)) = ingest(&state, decoded.samples, "OTLP") { + return failed(status, &message); } } - axum::Json(serde_json::json!({ "rejected": 0 })).into_response() + // Counted once the request is accepted, so a retried 503 counts once. + metrics + .otlp_rejected_points + .fetch_add(decoded.rejected_points, Ordering::Relaxed); + ([(header::CONTENT_TYPE, encoding.content_type())], reply).into_response() } /// Hands decoded samples to the engine: `None` once it has them, or the -/// response refusing them when it is busy (503, which senders retry) or has -/// stopped (500). +/// status and reason refusing them when it is busy (503, which senders +/// retry) or has stopped (500). fn ingest( state: &DataPlane, samples: Vec, protocol: &str, -) -> Option { +) -> Option<(StatusCode, String)> { let refused = match state.engine.try_ingest(samples).err()? { IngestError::Busy => ( StatusCode::SERVICE_UNAVAILABLE, @@ -495,7 +540,7 @@ fn ingest( ) } }; - Some(refused.into_response()) + Some(refused) } /// `POST /api/v1/precompute/watermark?time_ms=T`: the producer states that diff --git a/crates/data-plane/src/main.rs b/crates/data-plane/src/main.rs index f80e55f85..b9fde7b4c 100644 --- a/crates/data-plane/src/main.rs +++ b/crates/data-plane/src/main.rs @@ -115,6 +115,13 @@ struct Args { /// does not answer to it. Cannot be used with `--no-forward`. #[arg(long, conflicts_with = "no_forward")] clickhouse_url: Option, + /// OTLP resource attributes, by their OTLP names, that are labels of + /// every series of their resource (comma-separated), as Prometheus' + /// `otlp.promote_resource_attributes`. Without it, a resource gives only + /// `job` (from `service.namespace` and `service.name`) and `instance` + /// (from `service.instance.id`). + #[arg(long, value_delimiter = ',')] + otlp_promote_resource_attributes: Vec, /// The database forwarded ClickHouse queries run in. #[arg(long, default_value = "default")] clickhouse_database: String, @@ -237,7 +244,15 @@ async fn main() -> anyhow::Result<()> { ..EngineOptions::default() }, )? - .with_forward_timeout(forward_timeout); + .with_forward_timeout(forward_timeout) + .with_otlp_label_options(otlp::LabelOptions { + promote_resource_attributes: args + .otlp_promote_resource_attributes + .iter() + .map(|name| name.trim().to_string()) + .filter(|name| !name.is_empty()) + .collect(), + }); if let Some(url) = &args.clickhouse_url { let fallback = clickhouse_http::fallback::ClickHouseHttpFallback::new( url, diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index e8e97f57c..65f67bdf7 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -58,6 +58,9 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { metrics .remote_write_decode .render(&mut out, "phase=\"remote_write_decode\""); + metrics + .otlp_decode + .render(&mut out, "phase=\"otlp_decode\""); metrics.append.render(&mut out, "phase=\"append\""); if let Some(tier) = gauges.view_tier { tier.decode.render(&mut out, "phase=\"view_decode\""); @@ -314,6 +317,11 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { "View windows loaded from the view files at startup.", load(&metrics.view_windows_loaded), ), + ( + "asap_otlp_rejected_points_total", + "OTLP data points rejected (reported in the reply's partial_success): points of sums with DELTA aggregation temporality.", + load(&metrics.otlp_rejected_points), + ), ] { family(&mut out, name, "counter", help); let _ = writeln!(out, "{name} {value}"); diff --git a/crates/data-plane/src/remote_write.rs b/crates/data-plane/src/remote_write.rs index 69cbe62d4..4656ee0a0 100644 --- a/crates/data-plane/src/remote_write.rs +++ b/crates/data-plane/src/remote_write.rs @@ -35,27 +35,29 @@ pub fn decode_victoriametrics_samples( DECODER.with(|decoder| decoder.borrow_mut().decode(body, limits)) } -/// The samples of an OTLP metrics body ([`otlp::decode`]), each point's -/// series interned, within Remote Write's decompressed size and sample -/// limits. `content_encoding` is the request's `Content-Encoding`. +/// The samples of an OTLP metrics body ([`otlp::Decoder::decode`]), each +/// point's series interned, within Remote Write's decompressed size and +/// sample limits, with the points it rejected and dropped. +/// `content_encoding` is the request's `Content-Encoding`. Each thread +/// keeps its own decoder, as [`decode_samples`] does. pub fn decode_otlp_samples( body: &[u8], content_encoding: Option<&str>, + options: &otlp::LabelOptions, limits: &Limits, -) -> Result, otlp::OtlpError> { +) -> Result, otlp::OtlpError> { + thread_local! { + static DECODER: RefCell> = RefCell::new(otlp::Decoder::new(Interned)); + } let limits = otlp::Limits { max_decompressed_bytes: limits.max_decompressed_bytes, max_points: limits.max_samples, }; - let points = otlp::decode(body, content_encoding, &limits)?; - Ok(points - .into_iter() - .map(|point| RawSample { - labels: intern_pairs(&point.labels), - timestamp_ms: point.timestamp_ms, - value: point.value, - }) - .collect()) + DECODER.with(|decoder| { + decoder + .borrow_mut() + .decode(body, content_encoding, options, &limits) + }) } /// Interns each series into the store's series table and builds the diff --git a/crates/data-plane/tests/ingest_protocols.rs b/crates/data-plane/tests/ingest_protocols.rs index c50e3b669..6d2427eee 100644 --- a/crates/data-plane/tests/ingest_protocols.rs +++ b/crates/data-plane/tests/ingest_protocols.rs @@ -11,11 +11,15 @@ use axum::http::{header, Request, StatusCode}; use axum::Router; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; -use otlp::proto::collector::metrics::v1::ExportMetricsServiceRequest; +use otlp::proto::collector::metrics::v1::{ + ExportMetricsServiceRequest, ExportMetricsServiceResponse, +}; use otlp::proto::common::v1::{any_value, AnyValue, KeyValue}; use otlp::proto::metrics::v1::{ metric::Data, number_data_point, Gauge, Metric, NumberDataPoint, ResourceMetrics, ScopeMetrics, + Sum, }; +use otlp::proto::resource::v1::Resource; use prometheus_remote_write::{Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -203,7 +207,8 @@ async fn victoriametrics_and_otlp_ingest_what_remote_write_ingests() { }; let (status, response) = post(&app, "/v1/metrics", encoding, body).await; assert_eq!(status, StatusCode::OK, "{response}"); - assert_eq!(response, r#"{"rejected":0}"#); + // An empty `ExportMetricsServiceResponse`: no bytes. + assert_eq!(response, ""); assert_eq!(answers(&state, &app).await, expected, "gzip: {gzipped}"); } } @@ -241,9 +246,11 @@ fn decoders_give_the_same_series_and_samples() { decode_otlp_samples( &prost::Message::encode_to_vec(&otlp_request()), None, + &otlp::LabelOptions::default(), &limits, ) - .unwrap(), + .unwrap() + .samples, ); // The OTLP request lists the same series and samples in the same order. assert_eq!(otlp, remote_write); @@ -264,3 +271,225 @@ async fn rejects_malformed_bodies() { } assert_eq!(state.engine.stats().samples_accepted, 0); } + +/// An OTLP request posted with `content_type`: the status, the reply's +/// content type and body. +async fn post_otlp( + app: &Router, + content_type: &str, + body: Vec, +) -> (StatusCode, Option, Vec) { + let request = Request::post("/v1/metrics") + .header(header::CONTENT_TYPE, content_type) + .body(Body::from(body)) + .unwrap(); + let response = app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let reply_type = response + .headers() + .get(header::CONTENT_TYPE) + .map(|value| value.to_str().unwrap().to_string()); + let body = response.into_body().collect().await.unwrap().to_bytes(); + (status, reply_type, body.to_vec()) +} + +fn text_attribute(key: &str, value: &str) -> KeyValue { + KeyValue { + key: key.to_string(), + value: Some(AnyValue { + value: Some(any_value::Value::StringValue(value.to_string())), + }), + } +} + +/// A `data` sum of `temporality` with one point per second from 1 s to +/// `points` s, for each of the six series. +fn otlp_sum(temporality: i32, points: i64) -> ExportMetricsServiceRequest { + let mut request = otlp_request(); + for metric in &mut request.resource_metrics[0].scope_metrics[0].metrics { + let Some(Data::Gauge(gauge)) = metric.data.take() else { + unreachable!() + }; + let mut data_points = gauge.data_points; + data_points.truncate(points as usize); + metric.data = Some(Data::Sum(Sum { + data_points, + aggregation_temporality: temporality, + is_monotonic: true, + })); + } + request +} + +/// The value of the `/metrics` line `name`. +async fn metric_value(app: &Router, name: &str) -> f64 { + let response = app + .clone() + .oneshot(Request::get("/metrics").body(Body::empty()).unwrap()) + .await + .unwrap(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let text = String::from_utf8(body.to_vec()).unwrap(); + text.lines() + .find_map(|line| line.strip_prefix(&format!("{name} "))) + .unwrap_or_else(|| panic!("{name} in {text}")) + .parse() + .unwrap() +} + +/// `/v1/metrics` replies as OTLP/HTTP asks: 200 with an +/// `ExportMetricsServiceResponse` in protobuf (what OTLP exporters parse), +/// its `partial_success` counting the rejected points of DELTA sums; 400 +/// with a `google.rpc.Status` for a malformed body; 415 with a JSON +/// `Status` for an OTLP/JSON body, which is not decoded. +#[tokio::test(flavor = "multi_thread")] +async fn otlp_replies_are_otlp_messages() { + let (state, app) = data_plane(); + let protobuf = "application/x-protobuf"; + let (status, reply_type, body) = post_otlp( + &app, + protobuf, + prost::Message::encode_to_vec(&otlp_request()), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(reply_type.as_deref(), Some(protobuf)); + let reply: ExportMetricsServiceResponse = prost::Message::decode(&body[..]).unwrap(); + assert_eq!(reply, ExportMetricsServiceResponse::default()); + + // Six series of 10 cumulative points and 20 delta points each. + let (state_delta, app_delta) = data_plane(); + let cumulative = prost::Message::encode_to_vec(&otlp_sum(2, 10)); + let (status, _, body) = post_otlp(&app_delta, protobuf, cumulative).await; + assert_eq!(status, StatusCode::OK); + assert!(body.is_empty()); + let delta = prost::Message::encode_to_vec(&otlp_sum(1, 20)); + let (status, reply_type, body) = post_otlp(&app_delta, protobuf, delta).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(reply_type.as_deref(), Some(protobuf)); + let reply: ExportMetricsServiceResponse = prost::Message::decode(&body[..]).unwrap(); + let partial = reply.partial_success.unwrap(); + assert_eq!(partial.rejected_data_points, 6 * 20); + assert!( + partial.error_message.contains("DELTA"), + "{}", + partial.error_message + ); + common::barrier(&app_delta, END_S * 1000).await; + assert_eq!(state_delta.engine.stats().samples_accepted, 6 * 10); + assert_eq!( + metric_value(&app_delta, "asap_otlp_rejected_points_total").await, + 120.0 + ); + assert_eq!( + metric_value(&app_delta, "asap_phase_runs_total{phase=\"otlp_decode\"}").await, + 2.0 + ); + + let (status, reply_type, body) = post_otlp(&app, protobuf, vec![0xff; 8]).await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(reply_type.as_deref(), Some(protobuf)); + let error: otlp::Status = prost::Message::decode(&body[..]).unwrap(); + assert!(error.message.contains("Protobuf"), "{}", error.message); + + let (status, reply_type, body) = post_otlp( + &app, + "application/json", + br#"{"resourceMetrics":[]}"#.to_vec(), + ) + .await; + assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE); + assert_eq!(reply_type.as_deref(), Some("application/json")); + let error: Value = serde_json::from_slice(&body).unwrap(); + assert!(error["message"].as_str().unwrap().contains("OTLP/JSON")); + common::barrier(&app, END_S * 1000).await; + assert_eq!( + state.engine.stats().samples_accepted, + SERIES as u64 * END_S as u64 + ); +} + +/// Points flagged "no recorded value" are ingested as Prometheus' stale +/// marker, as Prometheus' OTLP receiver writes them: the answers and the +/// samples accepted are those of a Remote Write request with a stale +/// marker in each place. +#[tokio::test(flavor = "multi_thread")] +async fn otlp_points_without_a_recorded_value_are_stale_markers() { + // The second of each series' point flagged, in the last minute. + let flagged = |series: usize| END_S - 5 * (series as i64 + 1); + let stale = f64::from_bits(0x7ff0_0000_0000_0002); + let (state, app) = data_plane(); + let mut request = remote_write_request(); + for (series, timeseries) in request.timeseries.iter_mut().enumerate() { + timeseries.samples[flagged(series) as usize - 1].value = stale; + } + let (status, error) = post( + &app, + "/api/v1/write", + None, + prometheus_remote_write::encode(&request), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT, "{error}"); + let expected = answers(&state, &app).await; + assert_eq!(expected.1, SERIES as u64 * END_S as u64); + + let (state, app) = data_plane(); + let mut request = otlp_request(); + for (series, metric) in request.resource_metrics[0].scope_metrics[0] + .metrics + .iter_mut() + .enumerate() + { + let Some(Data::Gauge(gauge)) = &mut metric.data else { + unreachable!() + }; + let point = &mut gauge.data_points[flagged(series) as usize - 1]; + point.flags = 1; + point.value = None; + } + let (status, _, _) = post_otlp( + &app, + "application/x-protobuf", + prost::Message::encode_to_vec(&request), + ) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(answers(&state, &app).await, expected); +} + +/// Resource attributes become `job` and `instance` as in Prometheus' OTLP +/// receiver (the `otlp` crate's tests cover the other rules): the planned +/// query sums by the `job` the resource names, over the point attributes'. +#[tokio::test(flavor = "multi_thread")] +async fn otlp_resource_attributes_give_job_and_instance() { + let mut request = otlp_request(); + let resource_metrics = &mut request.resource_metrics[0]; + resource_metrics.resource = Some(Resource { + attributes: vec![ + text_attribute("service.name", "cart"), + text_attribute("service.namespace", "shop"), + text_attribute("service.instance.id", "cart-7"), + text_attribute("host.name", "node-1"), + text_attribute("deployment.environment", "prod"), + ], + ..Default::default() + }); + resource_metrics.scope_metrics[0].scope = Some(otlp::proto::common::v1::InstrumentationScope { + name: "meter".into(), + attributes: vec![text_attribute("scope.attribute", "s")], + ..Default::default() + }); + let body = prost::Message::encode_to_vec(&request); + // One job, the sum of every series. + let (state, app) = data_plane(); + let (status, _, _) = post_otlp(&app, "application/x-protobuf", body).await; + assert_eq!(status, StatusCode::OK); + let (answers, accepted) = answers(&state, &app).await; + assert_eq!(accepted, SERIES as u64 * END_S as u64); + let newest = common::per_job(answers.last().unwrap()); + let sum: f64 = (0..SERIES) + .flat_map(|i| (END_S - 59..=END_S).map(move |s| value(i, s))) + .sum(); + assert_eq!(newest, vec![("shop/cart".to_string(), sum)]); +} diff --git a/crates/internal-metrics/src/lib.rs b/crates/internal-metrics/src/lib.rs index adf040e5f..b8a463e04 100644 --- a/crates/internal-metrics/src/lib.rs +++ b/crates/internal-metrics/src/lib.rs @@ -1,5 +1,5 @@ //! The data plane's own measurements, for profiling and benchmarks: thread -//! CPU time and wall time of each phase (Remote Write decode, append, +//! CPU time and wall time of each phase (Remote Write and OTLP decode, append, //! precompute per refresh group, query run per query text), query latency, //! the watermark, bytes held, and each thread's CPU time by name. The data //! plane renders them, with the stores' and the engine's gauges, on @@ -289,6 +289,10 @@ pub struct Metrics { pub push: Option, /// Remote Write decode and series interning, on the HTTP threads. pub remote_write_decode: PhaseStats, + /// OTLP decode and series interning, on the HTTP threads. + pub otlp_decode: PhaseStats, + /// OTLP data points rejected: points of sums with DELTA temporality. + pub otlp_rejected_points: AtomicU64, /// Storing one ingest command's samples on the ingest thread: routing, /// appending, closing windows, compacting and evicting panes. pub append: PhaseStats, @@ -330,6 +334,8 @@ impl Metrics { Self { push: None, remote_write_decode: PhaseStats::default(), + otlp_decode: PhaseStats::default(), + otlp_rejected_points: AtomicU64::new(0), append: PhaseStats::default(), precompute: groups .iter() diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 4800d4cf7..c091cea15 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -983,9 +983,10 @@ pub struct ViewStore { /// pool lets a group run ahead of its readers. readers: BTreeMap>, /// Per view, the start of the first window ever stored. With the - /// stream start declared, the view has no data at all before it, so a - /// read reaching back past it answers from the rows that exist, as - /// PromQL does over a range that starts before the first sample. + /// stream start declared, the view has no data at all before it or + /// before the stream start, whichever is earlier, so a read reaching + /// back past that answers from the rows that exist, as PromQL does over + /// a range that starts before the first sample. first_start: BTreeMap, /// Where the producer's stream starts, when declared: no view has data /// before it, so a view with no window yet reads as empty there. @@ -1291,15 +1292,18 @@ impl ViewStore { ) -> Result, Error> { let (requested_start, end) = request.time_range_ms; // With the stream start declared (and no restart since), a range - // reaching back before the view's first window reads the rows that - // exist (PromQL semantics while a window is still filling); a gap - // after the first window is still missing data. Otherwise the - // skipped first window had data, so it is missing too. + // reaching back before the view's first window, and before the + // stream start, reads the rows that exist (PromQL semantics while a + // window is still filling); a gap after the first window is still + // missing data. A first window starting after the stream start + // follows windows skipped as already past retention, which had + // data: a range reaching into them is missing data. Without a + // declared stream start, the skipped first window had data, so it + // is missing too. let floor = self.stream_start_ms.map(|start| { self.first_start .get(&view.node_id) - .copied() - .unwrap_or(start) + .map_or(start, |&first| first.min(start)) }); let start = match floor { Some(first) if requested_start < first => first.min(end), @@ -1879,6 +1883,54 @@ mod tests { } } + /// When the watermark jumps past a view's retention, its windows that + /// would already be dropped are never built, so its first stored window + /// starts after the stream start: the skipped windows had data, and a + /// range reaching back into them is missing data, not empty. Only a + /// range wholly before the stream start reads as empty. + #[test] + fn windows_skipped_after_the_stream_start_are_missing() { + let view: MaterializedView = serde_json::from_value(serde_json::json!({ + "node_id": 1, + "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, + "coverage": {"definition_id": "test-view", "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap(); + let mut views = ViewStore::default().with_stream_start(Some(0)); + for end in [270, 280] { + views.append(&view, (end - 10, end), Vec::new()).unwrap(); + } + let context = RunContext::new( + asap_executor::runtime::Scope::Query { + evaluation_time_ms: 280, + }, + asap_executor::runtime::Limits::default(), + ) + .unwrap(); + let schema = schema(); + for (range, tiled) in [ + ((0, 30), false), + ((250, 280), false), + ((260, 280), true), + ((-20, -10), true), + ] { + let request = MaterializedViewRequest { + time_range_ms: range, + schema: &schema, + }; + assert_eq!( + views.read(&view, &request, context.clone()).is_ok(), + tiled, + "{range:?}" + ); + } + } + /// Every window of a view keys its text columns into one shared values /// array: a series identity is stored once per view, the rows read back /// unchanged, and a series first seen in a later window is added diff --git a/docs/design/data-plane-demo.md b/docs/design/data-plane-demo.md index 385d6d871..7ae046d3c 100644 --- a/docs/design/data-plane-demo.md +++ b/docs/design/data-plane-demo.md @@ -764,7 +764,8 @@ deleted once every window in it is past its views' retention. `query-N`; Remote Write is decoded on the HTTP runtime's threads. - `GET /metrics` exports, in the Prometheus text format: - `asap_phase_cpu_seconds_total`, `asap_phase_wall_seconds_total` and - `asap_phase_runs_total` by `phase`: `remote_write_decode`, `append`, + `asap_phase_runs_total` by `phase`: `remote_write_decode`, + `otlp_decode`, `append`, `precompute` (per refresh group: `group`, `window_ms`, `views`) and `query` (per `query` text). Thread CPU time comes from `CLOCK_THREAD_CPUTIME_ID`. A shared query-time result is counted in the diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index ec8bea61c..2f9932af0 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -101,7 +101,7 @@ Folders use hyphens (`crates/control-plane`); package names use underscores crate depends on ------------- -------------------------------------------------- control-plane asap-planner -adapters/* common, nothing, or the adapter whose wire format they extend +adapters/* common, nothing, or prometheus-remote-write (whose wire format victoriametrics-remote-write extends, and whose protobuf reader and series cache otlp reuses) precompute common, storage, internal-metrics, asap-executor storage internal-metrics, asap-executor, asap_sketchlib query common, storage, internal-metrics, asap-executor @@ -116,10 +116,12 @@ data-plane common, precompute, storage, query, internal-metrics, every adapt - Adapters never see an engine or a store. In ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); a separate `common` crate closes that here. The ingest adapters need not even `common`: each - decodes into the caller's types (below), so `prometheus-remote-write` and - `otlp` depend on nothing in the workspace, and - `victoriametrics-remote-write` only on `prometheus-remote-write`, whose - protobuf it reads (zstd-compressed instead of snappy). + decodes into the caller's types (below), so `prometheus-remote-write` + depends on nothing in the workspace, `victoriametrics-remote-write` only + on `prometheus-remote-write`, whose protobuf it reads (zstd-compressed + instead of snappy), and `otlp` only on `prometheus-remote-write`, whose + `SampleBuilder`, in-place protobuf reader and series cache its decoder + uses. - `control-plane` is a dev-dependency of `data-plane`, `precompute` and `query` only: their tests plan workloads with it. - `precompute` and `query` do not depend on each other. Both depend on @@ -223,11 +225,9 @@ labels into a `QueryResult`. The same holds on the ingest side. An ingest adapter builds no boundary batch type: its decoder takes the caller's series and sample types (the Remote Write decoder's `SampleBuilder`, which -`victoriametrics-remote-write` reuses), so `data-plane` interns each new series into the store's series -table and a Remote Write request decodes straight into the ingest engine's -samples, with no label copied per sample. `otlp` returns each point's -labels as strings, which `data-plane` interns the same way; OTLP ingest is -not on the measured path, so it copies them. +`victoriametrics-remote-write` and `otlp` reuse), so `data-plane` interns each new series into the store's series +table and a Remote Write or OTLP request decodes straight into the ingest +engine's samples, with no label copied per sample. The Prometheus HTTP routes forward what the plan does not answer verbatim: `PrometheusHttpFallback::forward` sends the request's method, path, query