Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
315 changes: 235 additions & 80 deletions asap-precompute-rs/src/otap/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1478,28 +1478,181 @@ pub fn decode_pdata_to_observations(pdata: OtapPdata) -> Result<DecodeOutcome, C
/// OTLP bytes are read in place ([`RawMetricsData`]), not converted to OTAP
/// Arrow records first.
pub fn decode_each(pdata: OtapPdata, f: impl FnMut(&Observation)) -> Result<usize, CodecError> {
decode_into(
pdata,
ObservationSink {
scratch: Observation::default(),
f,
},
)
}

/// Walks `pdata` like [`decode_each`], passing only its float points to `f`,
/// each as a [`ScalarPoint`] whose labels are still the encoded
/// [`ScalarPoint::identity`]: no label is copied or checked as UTF-8 unless
/// the caller asks for it ([`ScalarPoint::labels`]). A point carrying a
/// sketch envelope is checked as [`decode_each`] checks it, then skipped.
pub fn decode_each_scalar(
pdata: OtapPdata,
f: impl FnMut(&ScalarPoint<'_>),
) -> Result<usize, CodecError> {
decode_into(pdata, ScalarSink(f))
}

/// [`decode_each`] and [`decode_each_scalar`] over either representation.
fn decode_into(pdata: OtapPdata, sink: impl PointSink) -> Result<usize, CodecError> {
let (_context, payload) = pdata.into_parts();
match payload.into_data() {
PayloadData::OtlpBytes(OtlpProtoBytes::ExportMetricsRequest(bytes)) => {
let view =
RawMetricsData::try_new(&bytes).map_err(|e| CodecError::Decode(format!("{e}")))?;
decode_view(&view, f)
decode_view(&view, sink)
}
PayloadData::OtlpBytes(_) => Ok(0),
PayloadData::OtapArrowRecords(records @ OtapArrowRecords::Metrics(_)) => {
let view = OtapMetricsView::try_from(&records)
.map_err(|e| CodecError::Decode(format!("{e}")))?;
decode_view(&view, f)
decode_view(&view, sink)
}
PayloadData::OtapArrowRecords(_) => Ok(0),
}
}

/// One float data point, read in place: its labels stay encoded in
/// [`Self::identity`] until [`Self::labels`] decodes them.
pub struct ScalarPoint<'a> {
/// Metric name.
pub metric: &'a str,
/// Point timestamp (ms).
pub timestamp_ms: u64,
/// The value (an integer point's, as `f64`).
pub value: f64,
/// The Resource's string attributes, as [`Observation::resource_labels`].
pub resource_labels: &'a [KeyValue],
/// As [`Observation::source`].
pub source: &'a Arc<SourceDescriptor>,
/// The point's series identity: its resource labels, its series scope
/// labels and its string attributes, in received order, each section a
/// `u32` count of `(u32 length, key, u32 length, value)` pairs (the
/// attributes' section runs to the end without a count). Two points of
/// equal identity are of one series; the converse holds only for
/// attributes received in the same order.
pub identity: &'a [u8],
/// The series scope's labels ([`Observation::labels`] starts with them).
series_labels: &'a [KeyValue],
/// Where the point's attributes start in `identity`.
attributes_at: usize,
}

impl ScalarPoint<'_> {
/// [`Observation::labels`] of this point: the series scope's labels,
/// then each string attribute (read as UTF-8 lossily).
pub fn labels(&self) -> Vec<KeyValue> {
let mut labels = Vec::new();
self.write_labels(&mut labels);
labels
}

/// Writes [`Self::labels`] into `labels`, reusing its buffers.
fn write_labels(&self, labels: &mut Vec<KeyValue>) {
for (index, label) in self.series_labels.iter().enumerate() {
set_label(labels, index, label.key.as_bytes(), label.value.as_bytes());
}
let mut count = self.series_labels.len();
for (key, value) in identity_pairs(&self.identity[self.attributes_at..]) {
set_label(labels, count, key, value);
count += 1;
}
labels.truncate(count);
}
}

/// Appends one `(key, value)` pair to an identity (see
/// [`ScalarPoint::identity`]).
fn push_identity_pair(identity: &mut Vec<u8>, key: &[u8], value: &[u8]) {
for part in [key, value] {
identity.extend_from_slice(&(part.len() as u32).to_le_bytes());
identity.extend_from_slice(part);
}
}

/// Appends one counted section of labels to an identity.
fn push_identity_labels(identity: &mut Vec<u8>, labels: &[KeyValue]) {
identity.extend_from_slice(&(labels.len() as u32).to_le_bytes());
for label in labels {
push_identity_pair(identity, label.key.as_bytes(), label.value.as_bytes());
}
}

/// The `(key, value)` pairs of an identity's uncounted attribute section.
fn identity_pairs(mut bytes: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
let mut part = move || {
let (len, rest) = bytes.split_first_chunk::<4>()?;
let (part, rest) = rest.split_at(u32::from_le_bytes(*len) as usize);
bytes = rest;
Some(part)
};
std::iter::from_fn(move || Some((part()?, part()?)))
}

/// Where the walk passes each data point.
trait PointSink {
/// A float point.
fn scalar(&mut self, point: &ScalarPoint<'_>);
/// A point carrying a sketch envelope (any metric type).
fn envelope(&mut self, observation: &Observation);
}

/// [`decode_each`]'s sink: every point as an [`Observation`], rewritten in
/// one buffer.
struct ObservationSink<F> {
scratch: Observation,
f: F,
}

impl<F: FnMut(&Observation)> PointSink for ObservationSink<F> {
fn scalar(&mut self, point: &ScalarPoint<'_>) {
let obs = &mut self.scratch;
point.write_labels(&mut obs.labels);
obs.value = ObservationValue::float(point.value);
obs.timestamp_ms = point.timestamp_ms;
if obs.metric != point.metric {
obs.metric.clear();
obs.metric.push_str(point.metric);
}
if !Arc::ptr_eq(&obs.source, point.source) {
obs.source = Arc::clone(point.source);
}
if obs.resource_labels.as_slice() != point.resource_labels {
obs.resource_labels.clear();
obs.resource_labels.extend_from_slice(point.resource_labels);
}
(self.f)(obs);
}

fn envelope(&mut self, observation: &Observation) {
(self.f)(observation);
}
}

/// [`decode_each_scalar`]'s sink.
struct ScalarSink<F>(F);

impl<F: FnMut(&ScalarPoint<'_>)> PointSink for ScalarSink<F> {
fn scalar(&mut self, point: &ScalarPoint<'_>) {
(self.0)(point);
}

fn envelope(&mut self, _: &Observation) {}
}

/// [`decode_each`] over either representation's view.
fn decode_view<V: MetricsView>(view: &V, f: impl FnMut(&Observation)) -> Result<usize, CodecError> {
fn decode_view<V: MetricsView, S: PointSink>(view: &V, sink: S) -> Result<usize, CodecError> {
let mut acc = DecodeAccumulator {
identity: Vec::new(),
identity_prefix: 0,
scratch: Observation::default(),
sink: f,
sink,
};
let mut skipped_non_scalar = 0usize;

Expand Down Expand Up @@ -1558,6 +1711,10 @@ fn decode_view<V: MetricsView>(view: &V, f: impl FnMut(&Observation)) -> Result<
}
}
}
acc.identity.clear();
push_identity_labels(&mut acc.identity, &resource_labels);
push_identity_labels(&mut acc.identity, &series_labels);
acc.identity_prefix = acc.identity.len();
for metric in scope.metrics() {
let name = String::from_utf8_lossy(metric.name()).into_owned();
let Some(data) = metric.data() else {
Expand Down Expand Up @@ -1654,10 +1811,14 @@ fn set_text(text: &mut String, bytes: &[u8]) {
/// point body twice, or trying to unify their different concrete
/// iterator types into one `Vec` first (which doesn't compile —
/// `gauge`/`sum` would need to outlive the branch that produced them).
struct DecodeAccumulator<F> {
/// Rewritten for each data point.
struct DecodeAccumulator<S> {
/// The data point's [`ScalarPoint::identity`], rewritten for each one
/// after the scope's `identity_prefix` bytes.
identity: Vec<u8>,
identity_prefix: usize,
/// Rewritten for each data point carrying a sketch envelope.
scratch: Observation,
sink: F,
sink: S,
}

/// Parses an optional `sketch.type` value; absent means `Unspecified`.
Expand Down Expand Up @@ -1815,7 +1976,7 @@ fn decode_lineage(
Ok(Some(lineage))
}

impl<F: FnMut(&Observation)> DecodeAccumulator<F> {
impl<S: PointSink> DecodeAccumulator<S> {
fn push_summary_data_point<D: SummaryDataPointView>(
&mut self,
dp: D,
Expand Down Expand Up @@ -1892,7 +2053,7 @@ impl<F: FnMut(&Observation)> DecodeAccumulator<F> {
ObservationValue::envelope(envelope),
);
observation.source = Arc::clone(&metric.source);
(self.sink)(&observation);
self.sink.envelope(&observation);
Ok(())
}

Expand All @@ -1918,95 +2079,89 @@ impl<F: FnMut(&Observation)> DecodeAccumulator<F> {
let timestamp_ms = dp.time_unix_nano() / 1_000_000;

let mut envelope_bytes: Option<Vec<u8>> = None;
let mut sketch_type_raw = inherited_schema.sketch_type.clone();
// `Some` once the point names its own sketch type.
let mut sketch_type_raw: Option<Option<String>> = None;
let mut schema_version = inherited_schema.schema_version;
let mut window_start_ms: Option<u64> = None;
let mut window_end_ms: Option<u64> = None;
let obs = &mut self.scratch;
for (index, label) in series_labels.iter().enumerate() {
set_label(
&mut obs.labels,
index,
label.key.as_bytes(),
label.value.as_bytes(),
);
}
let mut label_count = series_labels.len();
self.identity.truncate(self.identity_prefix);

for attr in dp.attributes() {
let Some(val) = attr.value() else { continue };
let key = attr.key();
match std::str::from_utf8(key).unwrap_or_default() {
ATTR_ENVELOPE => envelope_bytes = val.as_bytes().map(<[u8]>::to_vec),
ATTR_SKETCH_TYPE => {
sketch_type_raw = val
.as_string()
.map(|s| String::from_utf8_lossy(s).into_owned());
}
ATTR_SCHEMA_VERSION => {
schema_version = val.as_int64().filter(|v| *v >= 0).map(|v| v as u32);
}
ATTR_WINDOW_START_MS => {
window_start_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64);
}
ATTR_WINDOW_END_MS => {
window_end_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64);
}
_ => {
// Non-reserved: treated as a per-row label. Only
// string-typed values are representable as a label;
// a non-string, non-reserved attribute is dropped.
if let Some(s) = val.as_string() {
set_label(&mut obs.labels, label_count, key, s);
label_count += 1;
}
}
// Compared as bytes: a key that is not UTF-8 is no reserved one.
if key == ATTR_ENVELOPE.as_bytes() {
envelope_bytes = val.as_bytes().map(<[u8]>::to_vec);
} else if key == ATTR_SKETCH_TYPE.as_bytes() {
sketch_type_raw = Some(
val.as_string()
.map(|s| String::from_utf8_lossy(s).into_owned()),
);
} else if key == ATTR_SCHEMA_VERSION.as_bytes() {
schema_version = val.as_int64().filter(|v| *v >= 0).map(|v| v as u32);
} else if key == ATTR_WINDOW_START_MS.as_bytes() {
window_start_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64);
} else if key == ATTR_WINDOW_END_MS.as_bytes() {
window_end_ms = val.as_int64().filter(|v| *v >= 0).map(|v| v as u64);
} else if let Some(s) = val.as_string() {
// Non-reserved: treated as a per-row label. Only
// string-typed values are representable as a label;
// a non-string, non-reserved attribute is dropped.
push_identity_pair(&mut self.identity, key, s);
}
}
obs.labels.truncate(label_count);

let point = ScalarPoint {
metric: &metric.name,
timestamp_ms,
value,
resource_labels,
source: &metric.source,
identity: &self.identity,
series_labels,
attributes_at: self.identity_prefix,
};
// An empty `sketch.envelope` from some other producer routes to
// the scalar path rather than an empty-payload envelope.
obs.value = match envelope_bytes.filter(|b| !b.is_empty()) {
Some(payload) => {
let sketch_type = match &metric.view {
Some(_) => metric.sketch_type(inherited_schema)?,
None => parse_sketch_type(sketch_type_raw.as_deref())?,
};
validate_self_describing_payload(sketch_type, &payload)
.map_err(CodecError::Decode)?;
ObservationValue::envelope(SketchEnvelope {
schema_version: schema_version.unwrap_or(0),
sketch_type,
view: metric.view.clone(),
resource_labels: Vec::new(),
labels: obs.labels.clone(),
source: Arc::clone(&metric.source),
window_start_ms: window_start_ms.unwrap_or(0),
window_end_ms: window_end_ms.unwrap_or(0),
payload,
metric_name: metric.name.clone(),
count: 0,
aggregation_temporality: 0,
value,
lineage: None,
})
}
None => ObservationValue::float(value),
let Some(payload) = envelope_bytes.filter(|b| !b.is_empty()) else {
self.sink.scalar(&point);
return Ok(());
};
let sketch_type = match &metric.view {
Some(_) => metric.sketch_type(inherited_schema)?,
None => match &sketch_type_raw {
Some(raw) => parse_sketch_type(raw.as_deref())?,
None => parse_sketch_type(inherited_schema.sketch_type.as_deref())?,
},
};
validate_self_describing_payload(sketch_type, &payload).map_err(CodecError::Decode)?;
let obs = &mut self.scratch;
point.write_labels(&mut obs.labels);
obs.value = ObservationValue::envelope(SketchEnvelope {
schema_version: schema_version.unwrap_or(0),
sketch_type,
view: metric.view.clone(),
resource_labels: Vec::new(),
labels: obs.labels.clone(),
source: Arc::clone(&metric.source),
window_start_ms: window_start_ms.unwrap_or(0),
window_end_ms: window_end_ms.unwrap_or(0),
payload,
metric_name: metric.name.clone(),
count: 0,
aggregation_temporality: 0,
value,
lineage: None,
});
obs.timestamp_ms = timestamp_ms;
if obs.metric != metric.name {
obs.metric.clear();
obs.metric.push_str(&metric.name);
}
if !Arc::ptr_eq(&obs.source, &metric.source) {
obs.source = Arc::clone(&metric.source);
}
if obs.resource_labels.as_slice() != resource_labels {
obs.resource_labels.clear();
obs.resource_labels.extend_from_slice(resource_labels);
}
(self.sink)(obs);
obs.source = Arc::clone(&metric.source);
obs.resource_labels.clear();
obs.resource_labels.extend_from_slice(resource_labels);
self.sink.envelope(obs);
Ok(())
}
}
Expand Down
Loading
Loading