micromegas_analytics/
delete.rs1use anyhow::{Context, Result};
2use chrono::{DateTime, Days, Utc};
3use micromegas_ingestion::data_lake_connection::DataLakeConnection;
4use micromegas_tracing::prelude::*;
5use sqlx::{Row, query};
6use std::collections::{BTreeMap, BTreeSet};
7use uuid::Uuid;
8
9use crate::lakehouse::write_partition::retire_expired_partitions;
10
11pub const MAX_RETENTION_DAYS: u32 = 36_500;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
16pub enum RetentionHorizon {
17 Days(u32),
18 Forever,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct PayloadRetention {
24 pub default_days: u32,
25 pub by_stream_tag: BTreeMap<String, RetentionHorizon>,
26}
27
28#[derive(Debug, PartialEq, Eq)]
30pub struct BlockDeletePass {
31 pub cutoff: DateTime<Utc>,
32 pub include_tags: Option<Vec<String>>,
34 pub exclude_tags: Vec<String>,
36}
37
38fn cutoff_for(now: DateTime<Utc>, days: u32) -> Result<DateTime<Utc>> {
39 now.checked_sub_days(Days::new(days as u64))
40 .with_context(|| "computing expiration date/time")
41}
42
43impl PayloadRetention {
44 pub fn default_cutoff(&self, now: DateTime<Utc>) -> Result<DateTime<Utc>> {
46 cutoff_for(now, self.default_days)
47 }
48
49 pub fn block_delete_passes(&self, now: DateTime<Utc>) -> Result<Vec<BlockDeletePass>> {
52 let mut passes = vec![BlockDeletePass {
53 cutoff: self.default_cutoff(now)?,
54 include_tags: None,
55 exclude_tags: self.by_stream_tag.keys().cloned().collect(),
56 }];
57 let finite: BTreeSet<u32> = self
58 .by_stream_tag
59 .values()
60 .filter_map(|h| match h {
61 RetentionHorizon::Days(d) => Some(*d),
62 RetentionHorizon::Forever => None,
63 })
64 .collect();
65 for days in finite {
66 let horizon = RetentionHorizon::Days(days);
67 let include_tags = self
68 .by_stream_tag
69 .iter()
70 .filter(|(_, h)| **h == horizon)
71 .map(|(t, _)| t.clone())
72 .collect();
73 let exclude_tags = self
74 .by_stream_tag
75 .iter()
76 .filter(|(_, h)| **h > horizon)
77 .map(|(t, _)| t.clone())
78 .collect();
79 passes.push(BlockDeletePass {
80 cutoff: cutoff_for(now, days)?,
81 include_tags: Some(include_tags),
82 exclude_tags,
83 });
84 }
85 Ok(passes)
86 }
87}
88
89#[span_fn]
92pub async fn delete_expired_blocks_batch(
93 lake: &DataLakeConnection,
94 pass: &BlockDeletePass,
95) -> Result<bool> {
96 let batch_size: i32 = 1000;
97 let mut transaction = lake.db_pool.begin().await?;
98 let rows = match &pass.include_tags {
99 None => {
100 query(
101 "DELETE FROM blocks
102 WHERE block_id IN (
103 SELECT b.block_id FROM blocks b
104 WHERE b.insert_time <= $1
105 AND NOT EXISTS (SELECT 1 FROM streams s WHERE s.stream_id = b.stream_id AND s.tags && $3)
106 LIMIT $2
107 )
108 RETURNING process_id, stream_id, block_id;",
109 )
110 .bind(pass.cutoff)
111 .bind(batch_size)
112 .bind(&pass.exclude_tags)
113 .fetch_all(&mut *transaction)
114 .await?
115 }
116 Some(include_tags) => {
117 query(
118 "DELETE FROM blocks
119 WHERE block_id IN (
120 SELECT b.block_id FROM streams s JOIN blocks b ON b.stream_id = s.stream_id
121 WHERE s.tags && $3 AND NOT (s.tags && $4) AND b.insert_time <= $1
122 LIMIT $2
123 )
124 RETURNING process_id, stream_id, block_id;",
125 )
126 .bind(pass.cutoff)
127 .bind(batch_size)
128 .bind(include_tags)
129 .bind(&pass.exclude_tags)
130 .fetch_all(&mut *transaction)
131 .await?
132 }
133 };
134 if rows.is_empty() {
135 return Ok(false);
136 }
137 let mut paths = vec![];
138 for r in &rows {
139 let process_id: Uuid = r.try_get("process_id")?;
140 let stream_id: Uuid = r.try_get("stream_id")?;
141 let block_id: Uuid = r.try_get("block_id")?;
142 let path = format!("blobs/{process_id}/{stream_id}/{block_id}");
143 paths.push(path);
144 }
145 lake.blob_storage.delete_batch(&paths).await?;
146 transaction.commit().await.with_context(|| "commit")?;
147 for path in &paths {
148 debug!("deleted blob {path}");
149 }
150 info!("deleted {} blocks", paths.len());
151 Ok(paths.len() == batch_size as usize)
152}
153
154#[span_fn]
156pub async fn delete_expired_blocks(
157 lake: &DataLakeConnection,
158 pass: &BlockDeletePass,
159) -> Result<()> {
160 while delete_expired_blocks_batch(lake, pass).await? {}
161 Ok(())
162}
163
164#[span_fn]
167pub async fn delete_empty_streams_batch(
168 lake: &DataLakeConnection,
169 expiration: DateTime<Utc>,
170) -> Result<bool> {
171 let batch_size: i32 = 1000;
172 let rows = query(
173 "WITH batch AS (
174 SELECT stream_id FROM streams
175 WHERE insert_time <= $1
176 AND NOT EXISTS (SELECT 1 FROM blocks WHERE blocks.stream_id = streams.stream_id LIMIT 1)
177 LIMIT $2
178 )
179 DELETE FROM streams
180 WHERE stream_id IN (SELECT stream_id FROM batch)
181 RETURNING stream_id;",
182 )
183 .bind(expiration)
184 .bind(batch_size)
185 .fetch_all(&lake.db_pool)
186 .await?;
187 if rows.is_empty() {
188 return Ok(false);
189 }
190 for r in &rows {
191 let stream_id: Uuid = r.try_get("stream_id")?;
192 debug!("deleted stream {stream_id}");
193 }
194 let count = rows.len();
195 info!("deleted {count} empty streams");
196 Ok(count == batch_size as usize)
197}
198
199#[span_fn]
201pub async fn delete_empty_streams(
202 lake: &DataLakeConnection,
203 expiration: DateTime<Utc>,
204) -> Result<()> {
205 while delete_empty_streams_batch(lake, expiration).await? {}
206 Ok(())
207}
208
209#[span_fn]
212pub async fn delete_empty_processes_batch(
213 lake: &DataLakeConnection,
214 expiration: DateTime<Utc>,
215) -> Result<bool> {
216 let batch_size: i32 = 1000;
217 let rows = query(
218 "WITH batch AS (
219 SELECT process_id FROM processes
220 WHERE insert_time <= $1
221 AND NOT EXISTS (SELECT 1 FROM streams WHERE streams.process_id = processes.process_id LIMIT 1)
222 LIMIT $2
223 )
224 DELETE FROM processes
225 WHERE process_id IN (SELECT process_id FROM batch)
226 RETURNING process_id;",
227 )
228 .bind(expiration)
229 .bind(batch_size)
230 .fetch_all(&lake.db_pool)
231 .await?;
232 if rows.is_empty() {
233 return Ok(false);
234 }
235 for r in &rows {
236 let process_id: Uuid = r.try_get("process_id")?;
237 debug!("deleted process {process_id}");
238 }
239 let count = rows.len();
240 info!("deleted {count} empty processes");
241 Ok(count == batch_size as usize)
242}
243
244#[span_fn]
246pub async fn delete_empty_processes(
247 lake: &DataLakeConnection,
248 expiration: DateTime<Utc>,
249) -> Result<()> {
250 while delete_empty_processes_batch(lake, expiration).await? {}
251 Ok(())
252}
253
254#[span_fn]
256pub async fn delete_old_data(
257 lake: &DataLakeConnection,
258 retention: &PayloadRetention,
259) -> Result<()> {
260 let now = Utc::now();
261 let expiration = retention.default_cutoff(now)?;
262 for pass in retention.block_delete_passes(now)? {
263 delete_expired_blocks(lake, &pass)
264 .await
265 .with_context(|| "delete_expired_blocks")?;
266 }
267 delete_empty_streams(lake, expiration)
268 .await
269 .with_context(|| "delete_empty_streams")?;
270 delete_empty_processes(lake, expiration)
271 .await
272 .with_context(|| "delete_empty_processes")?;
273 retire_expired_partitions(lake, expiration)
274 .await
275 .with_context(|| "retire_expired_partitions")?;
276 Ok(())
277}