Skip to main content

micromegas_analytics/lakehouse/
log_view.rs

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