Skip to main content

micromegas_analytics/lakehouse/otel/
histograms_view.rs

1use super::{
2    histograms_block_processor::OtelHistogramsBlockProcessor,
3    histograms_table::otel_histograms_table_schema,
4};
5use crate::{
6    metadata::find_process,
7    time::{TimeRange, datetime_to_scalar},
8};
9
10use crate::lakehouse::{
11    batch_update::PartitionCreationStrategy,
12    block_partition_spec::{
13        BlockPartitionSpec, BlockProcessor, BlockProcessorMap, SkipBlockProcessor,
14    },
15    dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
16    jit_partitions::update_insert_time_jit_view,
17    lakehouse_context::LakehouseContext,
18    partition_cache::PartitionCache,
19    partition_source_data::fetch_partition_source_data,
20    partitioned_execution_plan::ScanOrdering,
21    view::{PartitionSpec, View, ViewMetadata},
22    view_factory::ViewMaker,
23    write_partition::RetireMatch,
24};
25use anyhow::{Context, Result};
26use async_trait::async_trait;
27use chrono::{DateTime, TimeDelta, Utc};
28use datafusion::{
29    arrow::datatypes::Schema,
30    logical_expr::{Between, Expr, col},
31};
32use micromegas_ingestion::web_ingestion_service::{FORMAT_OTLP_METRICS, FORMAT_TRANSIT};
33use micromegas_tracing::info;
34use micromegas_tracing::prelude::*;
35use std::collections::HashMap;
36use std::sync::Arc;
37use uuid::Uuid;
38
39const VIEW_SET_NAME: &str = "otel_histograms";
40const SCHEMA_VERSION: u8 = 1;
41lazy_static::lazy_static! {
42    static ref TIME_COLUMN: Arc<String> = Arc::new( String::from("time"));
43}
44
45/// The `metrics` stream tag also covers native transit streams, which have no histogram rows;
46/// skipping them explicitly avoids a warning per native block.
47pub fn histograms_processors() -> Arc<BlockProcessorMap> {
48    let mut m: BlockProcessorMap = HashMap::new();
49    m.insert(
50        FORMAT_OTLP_METRICS,
51        Arc::new(OtelHistogramsBlockProcessor {}) as Arc<dyn BlockProcessor>,
52    );
53    m.insert(
54        FORMAT_TRANSIT,
55        Arc::new(SkipBlockProcessor {}) as Arc<dyn BlockProcessor>,
56    );
57    Arc::new(m)
58}
59
60#[derive(Debug)]
61pub struct OtelHistogramsViewMaker {}
62
63impl ViewMaker for OtelHistogramsViewMaker {
64    fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>> {
65        Ok(Arc::new(OtelHistogramsView::new(view_instance_id)?))
66    }
67
68    fn get_schema_hash(&self) -> Vec<u8> {
69        vec![SCHEMA_VERSION]
70    }
71
72    fn get_schema(&self) -> Arc<Schema> {
73        Arc::new(otel_histograms_table_schema())
74    }
75
76    fn get_scan_output_ordering(&self) -> ScanOrdering {
77        ScanOrdering::Unordered
78    }
79}
80
81#[derive(Clone, Debug)]
82pub struct OtelHistogramsView {
83    view_set_name: Arc<String>,
84    view_instance_id: Arc<String>,
85    process_id: Option<sqlx::types::Uuid>,
86}
87
88impl OtelHistogramsView {
89    pub fn new(view_instance_id: &str) -> Result<Self> {
90        let process_id = if view_instance_id == "global" {
91            None
92        } else {
93            Some(Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?)
94        };
95        Ok(Self {
96            view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
97            view_instance_id: Arc::new(view_instance_id.into()),
98            process_id,
99        })
100    }
101}
102
103#[async_trait]
104impl View for OtelHistogramsView {
105    fn get_view_set_name(&self) -> Arc<String> {
106        self.view_set_name.clone()
107    }
108
109    fn get_view_instance_id(&self) -> Arc<String> {
110        self.view_instance_id.clone()
111    }
112
113    async fn make_batch_partition_spec(
114        &self,
115        lakehouse: Arc<LakehouseContext>,
116        existing_partitions: Arc<PartitionCache>,
117        insert_range: TimeRange,
118    ) -> Result<Arc<dyn PartitionSpec>> {
119        if *self.view_instance_id != "global" {
120            anyhow::bail!("not supported for jit queries... should it?");
121        }
122        let source_data = Arc::new(
123            fetch_partition_source_data(
124                lakehouse.clone(),
125                existing_partitions,
126                insert_range,
127                "metrics",
128            )
129            .await
130            .with_context(|| "fetch_partition_source_data")?,
131        );
132        Ok(Arc::new(BlockPartitionSpec {
133            view_metadata: ViewMetadata {
134                view_set_name: self.view_set_name.clone(),
135                view_instance_id: self.view_instance_id.clone(),
136                file_schema_hash: self.get_file_schema_hash(),
137            },
138            schema: self.get_file_schema(),
139            insert_range,
140            source_data,
141            block_processors: histograms_processors(),
142            retire_match: RetireMatch::Containment,
143            same_run_ranges: vec![],
144        }))
145    }
146
147    fn get_file_schema_hash(&self) -> Vec<u8> {
148        vec![SCHEMA_VERSION]
149    }
150
151    fn get_file_schema(&self) -> Arc<Schema> {
152        Arc::new(otel_histograms_table_schema())
153    }
154
155    #[span_fn]
156    async fn jit_update(
157        &self,
158        lakehouse: Arc<LakehouseContext>,
159        query_range: Option<TimeRange>,
160    ) -> Result<()> {
161        if *self.view_instance_id == "global" {
162            // this view instance is updated using the deamon
163            return Ok(());
164        }
165        info!("find_process");
166        let process = Arc::new(
167            find_process(
168                &lakehouse.lake().db_pool,
169                &self
170                    .process_id
171                    .with_context(|| "getting a view's process_id")?,
172                &lakehouse.default_audience(),
173            )
174            .await
175            .with_context(|| "find_process")?,
176        );
177
178        //todo: use last_update_time in process
179        let query_range =
180            query_range.unwrap_or_else(|| TimeRange::new(process.start_time, chrono::Utc::now()));
181
182        update_insert_time_jit_view(
183            lakehouse,
184            Arc::new(self.clone()),
185            process,
186            query_range,
187            "metrics",
188            histograms_processors(),
189        )
190        .await
191    }
192
193    fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
194        Ok(vec![Expr::Between(Between::new(
195            col("time").into(),
196            false,
197            Expr::Literal(datetime_to_scalar(begin), None).into(),
198            Expr::Literal(datetime_to_scalar(end), None).into(),
199        ))])
200    }
201
202    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
203        Arc::new(NamedColumnsTimeBounds::new(
204            TIME_COLUMN.clone(),
205            TIME_COLUMN.clone(),
206        ))
207    }
208
209    fn get_update_group(&self) -> Option<i32> {
210        if *(self.get_view_instance_id()) == "global" {
211            Some(2000)
212        } else {
213            None
214        }
215    }
216
217    fn get_max_partition_time_delta(&self, _strategy: &PartitionCreationStrategy) -> TimeDelta {
218        TimeDelta::hours(1)
219    }
220}