Skip to main content

micromegas_analytics/lakehouse/
async_events_view.rs

1use super::{
2    batch_update::PartitionCreationStrategy,
3    block_partition_spec::{BlockProcessor, BlockProcessorMap},
4    dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
5    jit_partitions::update_insert_time_jit_view,
6    lakehouse_context::LakehouseContext,
7    partition_cache::PartitionCache,
8    partitioned_execution_plan::ScanOrdering,
9    view::{PartitionSpec, View},
10    view_factory::{ViewFactory, ViewMaker},
11};
12use crate::{
13    async_events_table::async_events_table_schema,
14    metadata::find_process_with_latest_timing,
15    time::{TimeRange, datetime_to_scalar, make_time_converter_from_latest_timing},
16};
17use anyhow::{Context, Result};
18use async_trait::async_trait;
19use chrono::{DateTime, TimeDelta, Utc};
20use datafusion::{
21    arrow::datatypes::Schema,
22    logical_expr::{Between, Expr, col},
23};
24use micromegas_ingestion::web_ingestion_service::FORMAT_TRANSIT;
25use micromegas_tracing::prelude::*;
26use std::collections::HashMap;
27use std::sync::Arc;
28use uuid::Uuid;
29
30use super::async_events_block_processor::AsyncEventsBlockProcessor;
31
32const VIEW_SET_NAME: &str = "async_events";
33const SCHEMA_VERSION: u8 = 4; // Version 4: added properties; version 3: widened dictionary keys to Int32
34lazy_static::lazy_static! {
35    static ref TIME_COLUMN: Arc<String> = Arc::new(String::from("time"));
36}
37
38/// A `ViewMaker` for creating `AsyncEventsView` instances.
39#[derive(Debug)]
40pub struct AsyncEventsViewMaker {
41    view_factory: Arc<ViewFactory>,
42}
43
44impl AsyncEventsViewMaker {
45    pub fn new(view_factory: Arc<ViewFactory>) -> Self {
46        Self { view_factory }
47    }
48}
49
50impl ViewMaker for AsyncEventsViewMaker {
51    fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>> {
52        Ok(Arc::new(AsyncEventsView::new(
53            view_instance_id,
54            self.view_factory.clone(),
55        )?))
56    }
57
58    fn get_schema_hash(&self) -> Vec<u8> {
59        vec![SCHEMA_VERSION]
60    }
61
62    fn get_schema(&self) -> Arc<Schema> {
63        Arc::new(async_events_table_schema())
64    }
65
66    fn get_scan_output_ordering(&self) -> ScanOrdering {
67        ScanOrdering::Unordered
68    }
69}
70
71/// A view of async span events.
72#[derive(Clone, Debug)]
73pub struct AsyncEventsView {
74    view_set_name: Arc<String>,
75    view_instance_id: Arc<String>,
76    process_id: Option<sqlx::types::Uuid>,
77    view_factory: Arc<ViewFactory>,
78}
79
80impl AsyncEventsView {
81    pub fn new(view_instance_id: &str, view_factory: Arc<ViewFactory>) -> Result<Self> {
82        if view_instance_id == "global" {
83            anyhow::bail!("AsyncEventsView does not support global view access");
84        }
85
86        let process_id =
87            Some(Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?);
88
89        Ok(Self {
90            view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
91            view_instance_id: Arc::new(view_instance_id.into()),
92            process_id,
93            view_factory,
94        })
95    }
96}
97
98#[async_trait]
99impl View for AsyncEventsView {
100    fn get_view_set_name(&self) -> Arc<String> {
101        self.view_set_name.clone()
102    }
103
104    fn get_view_instance_id(&self) -> Arc<String> {
105        self.view_instance_id.clone()
106    }
107
108    async fn make_batch_partition_spec(
109        &self,
110        _lakehouse: Arc<LakehouseContext>,
111        _existing_partitions: Arc<PartitionCache>,
112        _insert_range: TimeRange,
113    ) -> Result<Arc<dyn PartitionSpec>> {
114        anyhow::bail!("AsyncEventsView does not support batch partition specs");
115    }
116
117    fn get_file_schema_hash(&self) -> Vec<u8> {
118        vec![SCHEMA_VERSION]
119    }
120
121    fn get_file_schema(&self) -> Arc<Schema> {
122        Arc::new(async_events_table_schema())
123    }
124
125    #[span_fn]
126    async fn jit_update(
127        &self,
128        lakehouse: Arc<LakehouseContext>,
129        query_range: Option<TimeRange>,
130    ) -> Result<()> {
131        let (process, last_block_end_ticks, last_block_end_time) = find_process_with_latest_timing(
132            lakehouse.clone(),
133            self.view_factory.clone(),
134            &self
135                .process_id
136                .with_context(|| "getting a view's process_id")?,
137            query_range,
138        )
139        .await
140        .with_context(|| "find_process_with_latest_timing")?;
141
142        let process = Arc::new(process);
143        let query_range =
144            query_range.unwrap_or_else(|| TimeRange::new(process.start_time, last_block_end_time));
145
146        // Create a consistent ConvertTicks using the latest timing information
147        let convert_ticks = Arc::new(
148            make_time_converter_from_latest_timing(
149                &process,
150                last_block_end_ticks,
151                last_block_end_time,
152            )
153            .with_context(|| "make_time_converter_from_latest_timing")?,
154        );
155
156        // async_events only sources native transit streams (tagged "cpu");
157        // OTel spans go to the dedicated otel_spans view.
158        let mut block_processors: BlockProcessorMap = HashMap::new();
159        block_processors.insert(
160            FORMAT_TRANSIT,
161            Arc::new(AsyncEventsBlockProcessor::new(convert_ticks.clone()))
162                as Arc<dyn BlockProcessor>,
163        );
164        update_insert_time_jit_view(
165            lakehouse,
166            Arc::new(self.clone()),
167            process,
168            query_range,
169            "cpu",
170            Arc::new(block_processors),
171        )
172        .await
173    }
174
175    fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
176        Ok(vec![Expr::Between(Between::new(
177            col("time").into(),
178            false,
179            Expr::Literal(datetime_to_scalar(begin), None).into(),
180            Expr::Literal(datetime_to_scalar(end), None).into(),
181        ))])
182    }
183
184    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
185        Arc::new(NamedColumnsTimeBounds::new(
186            TIME_COLUMN.clone(),
187            TIME_COLUMN.clone(),
188        ))
189    }
190
191    fn get_update_group(&self) -> Option<i32> {
192        None // Process-specific views don't use update groups
193    }
194
195    fn get_max_partition_time_delta(&self, _strategy: &PartitionCreationStrategy) -> TimeDelta {
196        TimeDelta::hours(1)
197    }
198}