Skip to main content

micromegas_analytics/lakehouse/
images_view.rs

1use super::{
2    batch_update::PartitionCreationStrategy,
3    block_partition_spec::{BlockProcessor, BlockProcessorMap},
4    dataframe_time_bounds::{DataFrameTimeBounds, NamedColumnsTimeBounds},
5    image_block_processor::ImageBlockProcessor,
6    jit_partitions::update_insert_time_jit_view,
7    lakehouse_context::LakehouseContext,
8    partition_cache::PartitionCache,
9    partitioned_execution_plan::ScanOrdering,
10    view::{PartitionSpec, View},
11    view_factory::ViewMaker,
12};
13use crate::{
14    images_table::images_table_schema,
15    metadata::find_process,
16    time::{TimeRange, datetime_to_scalar},
17};
18use anyhow::{Context, Result};
19use async_trait::async_trait;
20use chrono::{DateTime, TimeDelta, Utc};
21use datafusion::{
22    arrow::datatypes::Schema,
23    logical_expr::{Between, Expr, col},
24};
25use micromegas_ingestion::web_ingestion_service::FORMAT_TRANSIT;
26use micromegas_tracing::prelude::*;
27use std::collections::HashMap;
28use std::sync::Arc;
29use uuid::Uuid;
30
31const VIEW_SET_NAME: &str = "images";
32const SCHEMA_VERSION: u8 = 2;
33
34lazy_static::lazy_static! {
35    static ref TIME_COLUMN: Arc<String> = Arc::new(String::from("time"));
36}
37
38fn image_processors() -> Arc<BlockProcessorMap> {
39    let mut m: BlockProcessorMap = HashMap::new();
40    m.insert(
41        FORMAT_TRANSIT,
42        Arc::new(ImageBlockProcessor {}) as Arc<dyn BlockProcessor>,
43    );
44    Arc::new(m)
45}
46
47#[derive(Debug)]
48pub struct ImagesViewMaker {}
49
50impl ViewMaker for ImagesViewMaker {
51    fn make_view(&self, view_instance_id: &str) -> Result<Arc<dyn View>> {
52        Ok(Arc::new(ImagesView::new(view_instance_id)?))
53    }
54
55    fn get_schema_hash(&self) -> Vec<u8> {
56        vec![SCHEMA_VERSION]
57    }
58
59    fn get_schema(&self) -> Arc<Schema> {
60        Arc::new(images_table_schema())
61    }
62
63    fn get_scan_output_ordering(&self) -> ScanOrdering {
64        ScanOrdering::Unordered
65    }
66}
67
68#[derive(Clone, Debug)]
69pub struct ImagesView {
70    view_set_name: Arc<String>,
71    view_instance_id: Arc<String>,
72    process_id: sqlx::types::Uuid,
73}
74
75impl ImagesView {
76    pub fn new(view_instance_id: &str) -> Result<Self> {
77        if view_instance_id == "global" {
78            anyhow::bail!("ImagesView does not support global view access");
79        }
80        let process_id = Uuid::parse_str(view_instance_id).with_context(|| "Uuid::parse_str")?;
81        Ok(Self {
82            view_set_name: Arc::new(String::from(VIEW_SET_NAME)),
83            view_instance_id: Arc::new(view_instance_id.into()),
84            process_id,
85        })
86    }
87}
88
89#[async_trait]
90impl View for ImagesView {
91    fn get_view_set_name(&self) -> Arc<String> {
92        self.view_set_name.clone()
93    }
94
95    fn get_view_instance_id(&self) -> Arc<String> {
96        self.view_instance_id.clone()
97    }
98
99    async fn make_batch_partition_spec(
100        &self,
101        _lakehouse: Arc<LakehouseContext>,
102        _existing_partitions: Arc<PartitionCache>,
103        _insert_range: TimeRange,
104    ) -> Result<Arc<dyn PartitionSpec>> {
105        anyhow::bail!("ImagesView does not support batch partition specs")
106    }
107
108    fn get_file_schema_hash(&self) -> Vec<u8> {
109        vec![SCHEMA_VERSION]
110    }
111
112    fn get_file_schema(&self) -> Arc<Schema> {
113        Arc::new(images_table_schema())
114    }
115
116    #[span_fn]
117    async fn jit_update(
118        &self,
119        lakehouse: Arc<LakehouseContext>,
120        query_range: Option<TimeRange>,
121    ) -> Result<()> {
122        let process = Arc::new(
123            find_process(
124                &lakehouse.lake().db_pool,
125                &self.process_id,
126                &lakehouse.default_audience(),
127            )
128            .await
129            .with_context(|| "find_process")?,
130        );
131        let query_range =
132            query_range.unwrap_or_else(|| TimeRange::new(process.start_time, chrono::Utc::now()));
133        update_insert_time_jit_view(
134            lakehouse,
135            Arc::new(self.clone()),
136            process,
137            query_range,
138            "image",
139            image_processors(),
140        )
141        .await
142    }
143
144    fn make_time_filter(&self, begin: DateTime<Utc>, end: DateTime<Utc>) -> Result<Vec<Expr>> {
145        Ok(vec![Expr::Between(Between::new(
146            col("time").into(),
147            false,
148            Expr::Literal(datetime_to_scalar(begin), None).into(),
149            Expr::Literal(datetime_to_scalar(end), None).into(),
150        ))])
151    }
152
153    fn get_time_bounds(&self) -> Arc<dyn DataFrameTimeBounds> {
154        Arc::new(NamedColumnsTimeBounds::new(
155            TIME_COLUMN.clone(),
156            TIME_COLUMN.clone(),
157        ))
158    }
159
160    fn get_update_group(&self) -> Option<i32> {
161        None
162    }
163
164    fn get_max_partition_time_delta(&self, _strategy: &PartitionCreationStrategy) -> TimeDelta {
165        TimeDelta::hours(1)
166    }
167}