micromegas_analytics/lakehouse/otel/
spans_view.rs1use super::spans_block_processor::OtelSpansBlockProcessor;
13use super::spans_table::otel_spans_table_schema;
14use crate::lakehouse::{
15 batch_update::PartitionCreationStrategy,
16 block_partition_spec::{BlockProcessor, BlockProcessorMap},
17 dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
18 jit_partitions::update_insert_time_jit_view,
19 lakehouse_context::LakehouseContext,
20 partition_cache::PartitionCache,
21 partitioned_execution_plan::ScanOrdering,
22 view::{PartitionSpec, View},
23 view_factory::ViewMaker,
24};
25use crate::{
26 metadata::find_process,
27 time::{TimeRange, datetime_to_scalar},
28};
29use anyhow::{Context, Result};
30use async_trait::async_trait;
31use chrono::{DateTime, TimeDelta, Utc};
32use datafusion::{
33 arrow::datatypes::Schema,
34 logical_expr::{BinaryExpr, Expr, Operator, col},
35};
36use micromegas_ingestion::web_ingestion_service::FORMAT_OTLP_TRACES;
37use micromegas_tracing::prelude::*;
38use std::collections::HashMap;
39use std::sync::Arc;
40use uuid::Uuid;
41
42const VIEW_SET_NAME: &str = "otel_spans";
43const SCHEMA_VERSION: u8 = 1;
44lazy_static::lazy_static! {
45 static ref TIME_COLUMN: Arc<String> = Arc::new(String::from("start_time"));
46 static ref END_TIME_COLUMN: Arc<String> = Arc::new(String::from("end_time"));
47}
48
49#[derive(Debug)]
51pub struct OtelSpansViewMaker {}
52
53impl ViewMaker for OtelSpansViewMaker {
54 fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>> {
55 Ok(Arc::new(OtelSpansView::new(view_instance_id)?))
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(otel_spans_table_schema())
64 }
65
66 fn get_scan_output_ordering(&self) -> ScanOrdering {
67 ScanOrdering::Unordered
68 }
69}
70
71#[derive(Clone, Debug)]
72pub struct OtelSpansView {
73 view_set_name: Arc<String>,
74 view_instance_id: Arc<String>,
75 process_id: sqlx::types::Uuid,
76}
77
78impl OtelSpansView {
79 pub fn new(view_instance_id: &str) -> Result<Self> {
80 if view_instance_id == "global" {
81 anyhow::bail!("OtelSpansView does not support global view access");
82 }
83 let process_id = Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?;
84 Ok(Self {
85 view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
86 view_instance_id: Arc::new(view_instance_id.into()),
87 process_id,
88 })
89 }
90}
91
92#[async_trait]
93impl View for OtelSpansView {
94 fn get_view_set_name(&self) -> Arc<String> {
95 self.view_set_name.clone()
96 }
97
98 fn get_view_instance_id(&self) -> Arc<String> {
99 self.view_instance_id.clone()
100 }
101
102 async fn make_batch_partition_spec(
103 &self,
104 _lakehouse: Arc<LakehouseContext>,
105 _existing_partitions: Arc<PartitionCache>,
106 _insert_range: TimeRange,
107 ) -> Result<Arc<dyn PartitionSpec>> {
108 anyhow::bail!("OtelSpansView does not support batch partition specs");
109 }
110
111 fn get_file_schema_hash(&self) -> Vec<u8> {
112 vec![SCHEMA_VERSION]
113 }
114
115 fn get_file_schema(&self) -> Arc<Schema> {
116 Arc::new(otel_spans_table_schema())
117 }
118
119 #[span_fn]
120 async fn jit_update(
121 &self,
122 lakehouse: Arc<LakehouseContext>,
123 query_range: Option<TimeRange>,
124 ) -> Result<()> {
125 let process = Arc::new(
126 find_process(
127 &lakehouse.lake().db_pool,
128 &self.process_id,
129 &lakehouse.default_audience(),
130 )
131 .await
132 .with_context(|| "find_process")?,
133 );
134 let query_range =
135 query_range.unwrap_or_else(|| TimeRange::new(process.start_time, chrono::Utc::now()));
136
137 let mut block_processors: BlockProcessorMap = HashMap::new();
138 block_processors.insert(
139 FORMAT_OTLP_TRACES,
140 Arc::new(OtelSpansBlockProcessor {}) as Arc<dyn BlockProcessor>,
141 );
142 let block_processors = Arc::new(block_processors);
143
144 update_insert_time_jit_view(
145 lakehouse,
146 Arc::new(self.clone()),
147 process,
148 query_range,
149 "trace",
150 block_processors,
151 )
152 .await
153 }
154
155 fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
156 Ok(vec![
161 Expr::BinaryExpr(BinaryExpr::new(
162 col("start_time").into(),
163 Operator::LtEq,
164 Expr::Literal(datetime_to_scalar(end), None).into(),
165 )),
166 Expr::BinaryExpr(BinaryExpr::new(
167 col("end_time").into(),
168 Operator::GtEq,
169 Expr::Literal(datetime_to_scalar(begin), None).into(),
170 )),
171 ])
172 }
173
174 fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
175 Arc::new(NamedColumnsTimeBounds::new(
176 TIME_COLUMN.clone(),
177 END_TIME_COLUMN.clone(),
178 ))
179 }
180
181 fn get_update_group(&self) -> Option<i32> {
182 None }
184
185 fn get_max_partition_time_delta(&self, _strategy: &PartitionCreationStrategy) -> TimeDelta {
186 TimeDelta::hours(1)
187 }
188}