Skip to main content

micromegas_analytics/lakehouse/
block_partition_spec.rs

1use super::{
2    partition_source_data::{PartitionBlocksSource, PartitionSourceBlock},
3    view::{PartitionSpec, ViewMetadata},
4    write_partition::{PartitionRowSet, RetireMatch, write_partition_from_rows},
5};
6use crate::{response_writer::Logger, time::TimeRange};
7use anyhow::{Context, Result};
8use async_trait::async_trait;
9use datafusion::arrow::datatypes::Schema;
10use futures::StreamExt;
11use micromegas_ingestion::data_lake_connection::DataLakeConnection;
12use micromegas_telemetry::blob_storage::BlobStorage;
13use micromegas_tracing::prelude::*;
14use std::collections::HashMap;
15use std::fmt::Debug;
16use std::sync::Arc;
17
18/// BlockProcessor transforms a single block of telemetry into a set of rows
19#[async_trait]
20pub trait BlockProcessor: Send + Sync + Debug {
21    /// Processes a single block of telemetry.
22    async fn process(
23        &self,
24        blob_storage: Arc<BlobStorage>,
25        src_block: Arc<PartitionSourceBlock>,
26    ) -> Result<Option<PartitionRowSet>>;
27}
28
29/// Accepts a block format without producing rows or fetching the payload. A view whose source
30/// tag covers formats it has no rows for registers this to avoid the per-block "no block
31/// processor" warning.
32#[derive(Debug)]
33pub struct SkipBlockProcessor {}
34
35#[async_trait]
36impl BlockProcessor for SkipBlockProcessor {
37    async fn process(
38        &self,
39        _blob_storage: Arc<BlobStorage>,
40        _src_block: Arc<PartitionSourceBlock>,
41    ) -> Result<Option<PartitionRowSet>> {
42        Ok(None)
43    }
44}
45
46/// Map from `streams.format` to the processor that handles that wire format.
47/// Views register one entry per format they understand (e.g. log entries register
48/// both `"micromegas-transit"` and `"otlp/v1/logs"`).
49pub type BlockProcessorMap = HashMap<&'static str, Arc<dyn BlockProcessor>>;
50
51/// BlockPartitionSpec processes blocks individually and out of order
52/// which works fine for measures & log entries.
53///
54/// Per-block dispatch keys on `PartitionSourceBlock::format` so a single view can
55/// materialize blocks coming from heterogeneous wire formats (native CBOR + OTLP).
56/// Unknown formats are warned and skipped.
57#[derive(Debug)]
58pub struct BlockPartitionSpec {
59    pub view_metadata: ViewMetadata,
60    pub schema: Arc<Schema>,
61    pub insert_range: TimeRange,
62    pub source_data: Arc<dyn PartitionBlocksSource>,
63    pub block_processors: Arc<BlockProcessorMap>,
64    /// Which existing partitions the write replaces; see `RetireMatch`.
65    pub retire_match: RetireMatch,
66    /// Insert ranges a `RetireMatch::Overlap` write must leave alone; empty for `Containment`.
67    pub same_run_ranges: Vec<TimeRange>,
68}
69
70#[async_trait]
71impl PartitionSpec for BlockPartitionSpec {
72    fn is_empty(&self) -> bool {
73        self.source_data.is_empty()
74    }
75
76    fn get_source_data_hash(&self) -> Vec<u8> {
77        self.source_data.get_source_data_hash()
78    }
79
80    #[span_fn]
81    async fn write(&self, lake: Arc<DataLakeConnection>, logger: Arc<dyn Logger>) -> Result<()> {
82        let desc = format!(
83            "[{}, {}] {} {}",
84            self.view_metadata.view_set_name,
85            self.view_metadata.view_instance_id,
86            self.insert_range.begin.to_rfc3339(),
87            self.insert_range.end.to_rfc3339()
88        );
89        instrument_named!(
90            logger.write_log_entry(format!("writing {desc}")),
91            "log_write_start"
92        )
93        .await?;
94
95        instrument_named!(
96            logger.write_log_entry(format!(
97                "reading {} blocks",
98                self.source_data.get_nb_blocks()
99            )),
100            "log_reading_blocks"
101        )
102        .await?;
103
104        // Allow empty source data - write_partition_from_rows will create
105        // an empty partition record if no data is sent through the channel
106        let (tx, rx) = tokio::sync::mpsc::channel(1);
107        let join_handle = spawn_with_context(write_partition_from_rows(
108            lake.clone(),
109            self.view_metadata.clone(),
110            self.schema.clone(),
111            self.insert_range,
112            self.source_data.get_source_data_hash(),
113            None,
114            self.retire_match,
115            self.same_run_ranges.clone(),
116            rx,
117            logger.clone(),
118        ));
119
120        // If source data is empty, just close the channel to create an empty partition
121        if self.source_data.is_empty() {
122            drop(tx);
123            instrument_named!(join_handle, "write_partition_from_rows_join").await??;
124            return Ok(());
125        }
126
127        let max_size = self.source_data.get_max_payload_size() as usize;
128        let mut nb_tasks = (100 * 1024 * 1024) / max_size; // try to download up to 100 MB of payloads
129        nb_tasks = nb_tasks.clamp(1, 64);
130
131        let mut stream =
132            instrument_named!(self.source_data.get_blocks_stream(), "get_blocks_stream")
133                .await
134                .map(|src_block_res| async {
135                    let src_block = src_block_res.with_context(|| "get_blocks_stream")?;
136                    // Per-block dispatch on `streams.format`. A view that doesn't register
137                    // a processor for some format silently skips matching blocks instead of
138                    // erroring — keeps the partition build moving when an unknown format
139                    // shows up alongside known ones.
140                    let Some(block_processor) = self
141                        .block_processors
142                        .get(src_block.format.as_str())
143                        .cloned()
144                    else {
145                        warn!(
146                            "no block processor for format={} (view={}/{}); skipping block_id={}",
147                            src_block.format,
148                            self.view_metadata.view_set_name,
149                            self.view_metadata.view_instance_id,
150                            src_block.block.block_id
151                        );
152                        return Ok::<Option<PartitionRowSet>, anyhow::Error>(None);
153                    };
154                    let blob_storage = lake.blob_storage.clone();
155                    let handle = spawn_with_context(async move {
156                        block_processor
157                            .process(blob_storage, src_block)
158                            .await
159                            .with_context(|| "processing source block")
160                    });
161                    instrument_named!(handle, "block_processor_task_join")
162                        .await
163                        .with_context(|| "handle.await")?
164                })
165                .buffer_unordered(nb_tasks);
166
167        while let Some(res_opt_rows) = instrument_named!(stream.next(), "blocks_stream_next").await
168        {
169            match res_opt_rows {
170                Err(e) => {
171                    error!("{e:?}");
172                    instrument_named!(logger.write_log_entry(format!("{e:?}")), "log_block_error")
173                        .await?;
174                }
175                Ok(Some(row_set)) => {
176                    instrument_named!(tx.send(Ok(row_set)), "row_set_channel_send").await?;
177                }
178                Ok(None) => {
179                    debug!("empty block");
180                }
181            }
182        }
183        drop(tx);
184        instrument_named!(join_handle, "write_partition_from_rows_join").await??;
185        Ok(())
186    }
187}