Skip to main content

micromegas_analytics/
payload.rs

1use anyhow::{Context, Result};
2use bumpalo::Bump;
3use micromegas_telemetry::{blob_storage::BlobStorage, compression::decompress};
4use micromegas_tracing::{parsing::make_custom_readers, prelude::*};
5use micromegas_transit::{CustomReaderMap, parse_object_buffer, read_dependencies, value::Value};
6use std::sync::Arc;
7
8use crate::metadata::StreamMetadata;
9
10/// Ceiling on each decompressed buffer (dependencies, objects) of one block. Real blocks are
11/// at most a few tens of MiB (a configured buffer size can be exceeded by the last object), and
12/// an incompressible image payload can't exceed the 100 MiB ingestion body limit. 128 MiB
13/// leaves headroom for both (a raw 8K RGBA frame is about 126.6 MiB) while capping a
14/// decompression bomb's footprint.
15pub const MAX_DECOMPRESSED_BLOCK_BUFFER_BYTES: usize = 128 * 1024 * 1024;
16
17thread_local! {
18    /// The custom-reader map is identical for every block, so build it once per
19    /// worker thread instead of rebuilding a `HashMap` of `Arc<dyn Fn>` on every
20    /// `parse_block` call.
21    static CUSTOM_READERS: CustomReaderMap = make_custom_readers();
22}
23
24/// Fetches the payload of a block from blob storage.
25#[span_fn]
26pub async fn fetch_block_payload(
27    blob_storage: Arc<BlobStorage>,
28    process_id: sqlx::types::Uuid,
29    stream_id: sqlx::types::Uuid,
30    block_id: sqlx::types::Uuid,
31) -> Result<micromegas_telemetry::block_wire_format::BlockPayload> {
32    let obj_path = format!("blobs/{process_id}/{stream_id}/{block_id}");
33    let buffer: Vec<u8> = blob_storage
34        .read_blob(&obj_path)
35        .await
36        .with_context(|| "reading block payload from blob storage")?
37        .into();
38    {
39        span_scope!("decode");
40        let payload: micromegas_telemetry::block_wire_format::BlockPayload =
41            ciborium::from_reader(&buffer[..])
42                .with_context(|| format!("reading payload {}", block_id))?;
43        Ok(payload)
44    }
45}
46
47/// Parses a block of telemetry data, calling a function for each object in the block.
48///
49/// Each parsed `Value` borrows from a per-block bump arena (and the decompressed
50/// buffers) that live only for the duration of this call. The higher-ranked
51/// `FnMut(Value<'_>)` bound forbids the callback from retaining a `Value` beyond
52/// its invocation — anything that must outlive the block (e.g. an Arrow append)
53/// must copy out inside the callback.
54// parse_block calls fun for each object in the block until fun returns `false`
55#[span_fn]
56pub fn parse_block<F>(
57    stream: &StreamMetadata,
58    payload: &micromegas_telemetry::block_wire_format::BlockPayload,
59    mut fun: F,
60) -> Result<bool>
61where
62    F: for<'a> FnMut(Value<'a>) -> Result<bool>,
63{
64    let dep_udts = &stream.dependencies_metadata;
65    let obj_udts = &stream.objects_metadata;
66    let process_id = stream.process_id;
67    let stream_id = stream.stream_id;
68    // A corrupt block is unexpected enough to be a potential attack indicator,
69    // so every occurrence is logged here regardless of what the caller does
70    // with the propagated `Err`.
71    let log_decompress_err = |e: &anyhow::Error| {
72        error!("corrupt block payload: process_id={process_id} stream_id={stream_id} error={e:?}");
73    };
74    // Bind the decompressed buffers and the arena to locals so every parsed
75    // Value borrows from storage that outlives the parse below.
76    let deps_buf = decompress(&payload.dependencies, MAX_DECOMPRESSED_BLOCK_BUFFER_BYTES)
77        .with_context(|| "decompressing dependencies payload")
78        .inspect_err(log_decompress_err)?;
79    let objs_buf = decompress(&payload.objects, MAX_DECOMPRESSED_BLOCK_BUFFER_BYTES)
80        .with_context(|| "decompressing objects payload")
81        .inspect_err(log_decompress_err)?;
82    let bump = Bump::new();
83    CUSTOM_READERS.with(|custom_readers| {
84        let log_parse_err = |e: &anyhow::Error| {
85            error!("corrupt block: process_id={process_id} stream_id={stream_id} error={e:?}");
86        };
87        let dependencies = read_dependencies(&bump, custom_readers, dep_udts, &deps_buf)
88            .with_context(|| "reading dependencies")
89            .inspect_err(log_parse_err)?;
90        let continue_iterating = parse_object_buffer(
91            &bump,
92            custom_readers,
93            &dependencies,
94            obj_udts,
95            &objs_buf,
96            &mut fun,
97        )
98        .with_context(|| "parsing object buffer")
99        .inspect_err(log_parse_err)?;
100        Ok(continue_iterating)
101    })
102}