1use crate::sql_telemetry_db::create_tables;
2use anyhow::{Context, Result};
3use micromegas_tracing::prelude::*;
4use sqlx::Executor;
5use sqlx::Row;
6
7pub const LATEST_DATA_LAKE_SCHEMA_VERSION: i32 = 14;
9
10pub async fn read_data_lake_schema_version(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> i32 {
12 match sqlx::query(
13 "SELECT version
14 FROM migration;",
15 )
16 .fetch_one(&mut **tr)
17 .await
18 {
19 Ok(row) => row.get("version"),
20 Err(e) => {
21 info!(
22 "Error reading data lake schema version, assuming version 0: {}",
23 e
24 );
25 0
26 }
27 }
28}
29
30pub async fn warn_if_data_lake_schema_stale(pool: &sqlx::Pool<sqlx::Postgres>) {
38 let version = match pool.begin().await {
39 Ok(mut tr) => read_data_lake_schema_version(&mut tr).await,
40 Err(e) => {
41 warn!("could not check data lake schema version: {e}");
42 return;
43 }
44 };
45 if version < 9 {
46 warn!(
47 "data lake schema is v{version}, behind the latest v{LATEST_DATA_LAKE_SCHEMA_VERSION}; \
48 the seeded 'public' audience_grants rows have not migrated in yet, so every query \
49 will resolve to an empty read scope and return zero rows until the schema is upgraded"
50 );
51 }
52 if version < 10 {
53 warn!(
54 "data lake schema is v{version}: the `groups`/`group_members` tables do not exist yet, \
55 so every request fails with a retryable 503 until the migration runs, because the \
56 group store cannot load"
57 );
58 }
59 if version < 12 {
60 warn!(
61 "data lake schema is v{version}: the `settings` table does not exist yet, so the \
62 settings store cannot load"
63 );
64 }
65}
66
67pub async fn upgrade_data_lake_schema_v2(
69 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
70) -> Result<()> {
71 tr.execute("ALTER TABLE blocks ADD insert_time TIMESTAMPTZ;")
72 .await
73 .with_context(|| "adding column insert_time to blocks table")?;
74 tr.execute("UPDATE blocks SET insert_time=end_time WHERE insert_time is NULL;")
75 .await
76 .with_context(|| "use end_time as insert_time to backfill missing data")?;
77 tr.execute("CREATE INDEX block_begin_time on blocks(begin_time);")
78 .await
79 .with_context(|| "adding index block_begin_time")?;
80 tr.execute("CREATE INDEX block_end_time on blocks(end_time);")
81 .await
82 .with_context(|| "adding index block_end_time")?;
83 tr.execute("CREATE INDEX block_insert_time on blocks(insert_time);")
84 .await
85 .with_context(|| "adding index block_insert_time")?;
86 tr.execute("CREATE INDEX process_insert_time on processes(insert_time);")
87 .await
88 .with_context(|| "adding index process_insert_time")?;
89 tr.execute("UPDATE migration SET version=2;")
90 .await
91 .with_context(|| "Updating data lake schema version to 2")?;
92 Ok(())
93}
94
95pub async fn upgrade_data_lake_schema_v3(
98 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
99) -> Result<()> {
100 tr.execute("DROP INDEX IF EXISTS process_id;")
101 .await
102 .with_context(|| "dropping old non-unique index process_id")?;
103 tr.execute("DROP INDEX IF EXISTS stream_id;")
104 .await
105 .with_context(|| "dropping old non-unique index stream_id")?;
106 tr.execute("DROP INDEX IF EXISTS block_id;")
107 .await
108 .with_context(|| "dropping old non-unique index block_id")?;
109 tr.execute("UPDATE migration SET version=3;")
110 .await
111 .with_context(|| "updating data lake schema version to 3")?;
112 Ok(())
113}
114
115pub async fn upgrade_data_lake_schema_v4(
118 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
119) -> Result<()> {
120 tr.execute("ALTER TABLE streams ADD COLUMN format TEXT NOT NULL DEFAULT 'micromegas-transit';")
121 .await
122 .with_context(|| "adding column format to streams table")?;
123 tr.execute("UPDATE migration SET version=4;")
124 .await
125 .with_context(|| "updating data lake schema version to 4")?;
126 Ok(())
127}
128
129pub async fn upgrade_data_lake_schema_v5(
138 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
139) -> Result<()> {
140 tr.execute(
141 "CREATE TABLE ingestion_api_keys (
142 key_id UUID PRIMARY KEY,
143 key_hash BYTEA NOT NULL,
144 name VARCHAR(255) NOT NULL,
145 created_at TIMESTAMPTZ NOT NULL,
146 created_by VARCHAR(255) NOT NULL,
147 last_used_at TIMESTAMPTZ,
148 revoked_at TIMESTAMPTZ,
149 revoked_by VARCHAR(255)
150 );",
151 )
152 .await
153 .with_context(|| "creating table ingestion_api_keys")?;
154 tr.execute("CREATE UNIQUE INDEX ingestion_api_keys_key_hash ON ingestion_api_keys(key_hash);")
155 .await
156 .with_context(|| "creating unique index ingestion_api_keys_key_hash")?;
157 tr.execute(
158 "CREATE TABLE analytics_api_keys (
159 key_id UUID PRIMARY KEY,
160 key_hash BYTEA NOT NULL,
161 name VARCHAR(255) NOT NULL,
162 created_at TIMESTAMPTZ NOT NULL,
163 created_by VARCHAR(255) NOT NULL,
164 last_used_at TIMESTAMPTZ,
165 revoked_at TIMESTAMPTZ,
166 revoked_by VARCHAR(255)
167 );",
168 )
169 .await
170 .with_context(|| "creating table analytics_api_keys")?;
171 tr.execute("CREATE UNIQUE INDEX analytics_api_keys_key_hash ON analytics_api_keys(key_hash);")
172 .await
173 .with_context(|| "creating unique index analytics_api_keys_key_hash")?;
174 tr.execute("UPDATE migration SET version=5;")
175 .await
176 .with_context(|| "updating data lake schema version to 5")?;
177 Ok(())
178}
179
180pub async fn upgrade_data_lake_schema_v6(
190 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
191) -> Result<()> {
192 tr.execute("ALTER TABLE ingestion_api_keys ADD COLUMN audience VARCHAR(255);")
193 .await
194 .with_context(|| "adding column audience to ingestion_api_keys table")?;
195 tr.execute("UPDATE ingestion_api_keys SET audience = 'public' WHERE audience IS NULL;")
196 .await
197 .with_context(|| "backfilling audience to 'public' on ingestion_api_keys")?;
198 tr.execute("ALTER TABLE ingestion_api_keys ALTER COLUMN audience SET NOT NULL;")
199 .await
200 .with_context(|| "setting audience NOT NULL on ingestion_api_keys")?;
201 tr.execute(
202 "ALTER TABLE ingestion_api_keys ADD CONSTRAINT ingestion_api_keys_audience_name \
203 CHECK (audience ~ '^[A-Za-z0-9_-]+$');",
204 )
205 .await
206 .with_context(|| "adding audience-name CHECK constraint on ingestion_api_keys")?;
207 tr.execute("UPDATE migration SET version=6;")
208 .await
209 .with_context(|| "updating data lake schema version to 6")?;
210 Ok(())
211}
212
213pub async fn upgrade_data_lake_schema_v7(
226 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
227) -> Result<()> {
228 tr.execute(
229 "CREATE TABLE audience_grants (
230 audience VARCHAR(255) NOT NULL,
231 axis VARCHAR(4) NOT NULL CHECK (axis IN ('read', 'mint')),
232 selector VARCHAR(255) NOT NULL,
233 created_at TIMESTAMPTZ NOT NULL,
234 created_by VARCHAR(255) NOT NULL,
235 PRIMARY KEY (audience, axis, selector),
236 CONSTRAINT audience_grants_audience_name CHECK (audience ~ '^[A-Za-z0-9_-]+$'),
237 CONSTRAINT audience_grants_selector_shape
238 CHECK (selector = '*' OR selector ~ '^(user|group):.+$')
239 );",
240 )
241 .await
242 .with_context(|| "creating table audience_grants")?;
243 tr.execute("UPDATE migration SET version=7;")
244 .await
245 .with_context(|| "updating data lake schema version to 7")?;
246 Ok(())
247}
248
249pub async fn upgrade_data_lake_schema_v8(
265 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
266) -> Result<()> {
267 tr.execute("ALTER TABLE processes ADD COLUMN audience VARCHAR(255);")
268 .await
269 .with_context(|| "adding column audience to processes table")?;
270 tr.execute("ALTER TABLE streams ADD COLUMN audience VARCHAR(255);")
271 .await
272 .with_context(|| "adding column audience to streams table")?;
273 tr.execute("ALTER TABLE blocks ADD COLUMN audience VARCHAR(255);")
274 .await
275 .with_context(|| "adding column audience to blocks table")?;
276 tr.execute(
277 "ALTER TABLE processes ADD CONSTRAINT processes_audience_name \
278 CHECK (audience ~ '^[A-Za-z0-9_-]+$') NOT VALID;",
279 )
280 .await
281 .with_context(|| "adding audience-name CHECK constraint on processes")?;
282 tr.execute(
283 "ALTER TABLE streams ADD CONSTRAINT streams_audience_name \
284 CHECK (audience ~ '^[A-Za-z0-9_-]+$') NOT VALID;",
285 )
286 .await
287 .with_context(|| "adding audience-name CHECK constraint on streams")?;
288 tr.execute(
289 "ALTER TABLE blocks ADD CONSTRAINT blocks_audience_name \
290 CHECK (audience ~ '^[A-Za-z0-9_-]+$') NOT VALID;",
291 )
292 .await
293 .with_context(|| "adding audience-name CHECK constraint on blocks")?;
294 tr.execute("UPDATE migration SET version=8;")
295 .await
296 .with_context(|| "updating data lake schema version to 8")?;
297 Ok(())
298}
299
300pub async fn upgrade_data_lake_schema_v9(
308 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
309) -> Result<()> {
310 tr.execute(
311 "INSERT INTO audience_grants (audience, axis, selector, created_at, created_by)
312 VALUES ('public', 'read', '*', now(), 'default'),
313 ('public', 'mint', '*', now(), 'default')
314 ON CONFLICT DO NOTHING;",
315 )
316 .await
317 .with_context(|| "seeding public read/mint grants")?;
318 tr.execute("UPDATE migration SET version=9;")
319 .await
320 .with_context(|| "updating data lake schema version to 9")?;
321 Ok(())
322}
323
324fn is_valid_group_name(name: &str) -> bool {
328 !name.is_empty()
329 && name.len() <= 255
330 && name
331 .bytes()
332 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
333}
334
335pub async fn upgrade_data_lake_schema_v10(
347 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
348) -> Result<()> {
349 tr.execute(
350 "CREATE TABLE groups (
351 name VARCHAR(255) PRIMARY KEY,
352 description TEXT,
353 created_at TIMESTAMPTZ NOT NULL,
354 created_by VARCHAR(255) NOT NULL,
355 CONSTRAINT groups_name CHECK (name ~ '^[A-Za-z0-9_-]+$')
356 );",
357 )
358 .await
359 .with_context(|| "creating table groups")?;
360 tr.execute(
361 "CREATE TABLE group_members (
362 group_name VARCHAR(255) NOT NULL REFERENCES groups(name) ON DELETE CASCADE,
363 member VARCHAR(255) NOT NULL,
364 created_at TIMESTAMPTZ NOT NULL,
365 created_by VARCHAR(255) NOT NULL,
366 PRIMARY KEY (group_name, member),
367 CONSTRAINT group_members_selector_shape CHECK (member = '*' OR member ~ '^(user|group):.+$')
368 );",
369 )
370 .await
371 .with_context(|| "creating table group_members")?;
372
373 tr.execute(
374 "INSERT INTO groups (name, description, created_at, created_by)
375 VALUES ('admins', 'Deployment administrators', now(), 'default')
376 ON CONFLICT (name) DO NOTHING;",
377 )
378 .await
379 .with_context(|| "seeding the admins group")?;
380
381 tr.execute(
382 "INSERT INTO group_members (group_name, member, created_at, created_by)
383 VALUES ('admins', '*', now(), 'default')
384 ON CONFLICT (group_name, member) DO NOTHING;",
385 )
386 .await
387 .with_context(|| "seeding the admins group with the wildcard member")?;
388
389 let rows =
390 sqlx::query("SELECT DISTINCT selector FROM audience_grants WHERE selector LIKE 'group:%';")
391 .fetch_all(&mut **tr)
392 .await
393 .with_context(|| "querying distinct group: selectors from audience_grants")?;
394 for row in rows {
395 let selector: String = row.try_get("selector").context("reading selector")?;
396 let name = selector
397 .strip_prefix("group:")
398 .expect("selector matched the LIKE 'group:%' filter");
399 if !is_valid_group_name(name) {
400 warn!(
401 "legacy audience_grants selector group:{name:?} does not match the group name \
402 charset [A-Za-z0-9_-]{{1,255}}; left as an inert grant row, not backfilled into \
403 a group"
404 );
405 continue;
406 }
407 sqlx::query(
408 "INSERT INTO groups (name, description, created_at, created_by)
409 VALUES ($1, NULL, now(), 'migration')
410 ON CONFLICT (name) DO NOTHING;",
411 )
412 .bind(name)
413 .execute(&mut **tr)
414 .await
415 .with_context(|| format!("backfilling empty group {name:?} from a legacy grant"))?;
416 info!("backfilled empty group {name:?} from a legacy audience_grants selector");
417 }
418
419 tr.execute("UPDATE migration SET version=10;")
420 .await
421 .with_context(|| "updating data lake schema version to 10")?;
422 Ok(())
423}
424
425pub async fn upgrade_data_lake_schema_v11(
431 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
432) -> Result<()> {
433 tr.execute("ALTER TABLE ingestion_api_keys ADD COLUMN allowed_cidrs TEXT[];")
434 .await
435 .with_context(|| "adding column allowed_cidrs to ingestion_api_keys table")?;
436 tr.execute("ALTER TABLE analytics_api_keys ADD COLUMN allowed_cidrs TEXT[];")
437 .await
438 .with_context(|| "adding column allowed_cidrs to analytics_api_keys table")?;
439 tr.execute("UPDATE migration SET version=11;")
440 .await
441 .with_context(|| "updating data lake schema version to 11")?;
442 Ok(())
443}
444
445pub async fn upgrade_data_lake_schema_v12(
449 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
450) -> Result<()> {
451 tr.execute(
452 "CREATE TABLE settings (
453 key VARCHAR(255) PRIMARY KEY,
454 value JSONB NOT NULL,
455 updated_at TIMESTAMPTZ NOT NULL,
456 updated_by VARCHAR(255) NOT NULL
457 );",
458 )
459 .await
460 .with_context(|| "creating settings table")?;
461 tr.execute("UPDATE migration SET version=12;")
462 .await
463 .with_context(|| "updating data lake schema version to 12")?;
464 Ok(())
465}
466
467pub async fn upgrade_data_lake_schema_v13(
472 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
473) -> Result<()> {
474 tr.execute(
475 "ALTER TABLE audience_grants DROP CONSTRAINT IF EXISTS audience_grants_selector_shape;",
476 )
477 .await
478 .with_context(|| "dropping audience_grants_selector_shape")?;
479 tr.execute("ALTER TABLE group_members DROP CONSTRAINT IF EXISTS group_members_selector_shape;")
480 .await
481 .with_context(|| "dropping group_members_selector_shape")?;
482 tr.execute("UPDATE migration SET version=13;")
483 .await
484 .with_context(|| "updating data lake schema version to 13")?;
485 Ok(())
486}
487
488pub async fn upgrade_data_lake_schema_v14(
494 tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
495) -> Result<()> {
496 tr.execute(
497 "ALTER TABLE audience_grants DROP CONSTRAINT IF EXISTS audience_grants_audience_name;",
498 )
499 .await
500 .with_context(|| "dropping audience_grants_audience_name")?;
501 tr.execute("ALTER TABLE audience_grants DROP CONSTRAINT IF EXISTS audience_grants_axis_check;")
502 .await
503 .with_context(|| "dropping audience_grants_axis_check")?;
504 tr.execute("ALTER TABLE groups DROP CONSTRAINT IF EXISTS groups_name;")
505 .await
506 .with_context(|| "dropping groups_name")?;
507 tr.execute("UPDATE migration SET version=14;")
508 .await
509 .with_context(|| "updating data lake schema version to 14")?;
510 Ok(())
511}
512
513async fn check_index_is_valid(pool: &sqlx::Pool<sqlx::Postgres>, index_name: &str) -> Result<bool> {
518 let row = sqlx::query(
519 "SELECT i.indisvalid
520 FROM pg_class c
521 JOIN pg_index i ON i.indexrelid = c.oid
522 WHERE c.relname = $1;",
523 )
524 .bind(index_name)
525 .fetch_optional(pool)
526 .await
527 .with_context(|| format!("querying pg_index for {index_name}"))?;
528
529 let row = row.with_context(|| format!("index {index_name} not found in pg_class"))?;
530 let is_valid: bool = row.get("indisvalid");
531
532 if !is_valid {
533 info!("index {index_name} is INVALID, dropping it");
534 sqlx::query(&format!("DROP INDEX IF EXISTS {index_name}"))
535 .execute(pool)
536 .await
537 .with_context(|| format!("dropping invalid index {index_name}"))?;
538 return Ok(false);
539 }
540
541 Ok(true)
542}
543
544async fn validate_unique_indexes(pool: &sqlx::Pool<sqlx::Postgres>) -> Result<()> {
547 let index_names = [
548 "processes_process_id_unique",
549 "streams_stream_id_unique",
550 "blocks_block_id_unique",
551 ];
552
553 let mut invalid_indexes = Vec::new();
554 for name in &index_names {
555 if !check_index_is_valid(pool, name).await? {
556 invalid_indexes.push(*name);
557 }
558 }
559
560 if !invalid_indexes.is_empty() {
561 anyhow::bail!(
562 "invalid indexes detected and dropped: {}. The migration will be retried on next startup.",
563 invalid_indexes.join(", ")
564 );
565 }
566
567 Ok(())
568}
569
570pub async fn execute_migration(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
572 let mut current_version = read_data_lake_schema_version(&mut pool.begin().await?).await;
573 if 0 == current_version {
574 info!("creating v1 data_lake_schema");
575 let mut tr = pool.begin().await?;
576 create_tables(&mut tr).await?;
577 current_version = read_data_lake_schema_version(&mut tr).await;
578 tr.commit().await?;
579 }
580 if 1 == current_version {
581 info!("upgrading data_lake_schema to v2");
582 let mut tr = pool.begin().await?;
583 upgrade_data_lake_schema_v2(&mut tr).await?;
584 current_version = read_data_lake_schema_version(&mut tr).await;
585 tr.commit().await?;
586 }
587 if 2 == current_version {
588 info!("upgrading data_lake_schema to v3");
589 sqlx::query("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS processes_process_id_unique ON processes(process_id);")
593 .execute(&pool)
594 .await
595 .with_context(|| "creating unique index on processes(process_id)")?;
596 sqlx::query("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS streams_stream_id_unique ON streams(stream_id);")
597 .execute(&pool)
598 .await
599 .with_context(|| "creating unique index on streams(stream_id)")?;
600 sqlx::query("CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS blocks_block_id_unique ON blocks(block_id);")
601 .execute(&pool)
602 .await
603 .with_context(|| "creating unique index on blocks(block_id)")?;
604
605 validate_unique_indexes(&pool).await?;
606
607 let mut tr = pool.begin().await?;
608 upgrade_data_lake_schema_v3(&mut tr).await?;
609 current_version = read_data_lake_schema_version(&mut tr).await;
610 tr.commit().await?;
611 }
612 if 3 == current_version {
613 info!("upgrading data_lake_schema to v4");
614 let mut tr = pool.begin().await?;
615 upgrade_data_lake_schema_v4(&mut tr).await?;
616 current_version = read_data_lake_schema_version(&mut tr).await;
617 tr.commit().await?;
618 }
619 if 4 == current_version {
620 info!("upgrading data_lake_schema to v5");
621 let mut tr = pool.begin().await?;
622 upgrade_data_lake_schema_v5(&mut tr).await?;
623 current_version = read_data_lake_schema_version(&mut tr).await;
624 tr.commit().await?;
625 }
626 if 5 == current_version {
627 info!("upgrading data_lake_schema to v6");
628 let mut tr = pool.begin().await?;
629 upgrade_data_lake_schema_v6(&mut tr).await?;
630 current_version = read_data_lake_schema_version(&mut tr).await;
631 tr.commit().await?;
632 }
633 if 6 == current_version {
634 info!("upgrading data_lake_schema to v7");
635 let mut tr = pool.begin().await?;
636 upgrade_data_lake_schema_v7(&mut tr).await?;
637 current_version = read_data_lake_schema_version(&mut tr).await;
638 tr.commit().await?;
639 }
640 if 7 == current_version {
641 info!("upgrading data_lake_schema to v8");
642 let mut tr = pool.begin().await?;
643 upgrade_data_lake_schema_v8(&mut tr).await?;
644 current_version = read_data_lake_schema_version(&mut tr).await;
645 tr.commit().await?;
646 }
647 if 8 == current_version {
648 info!("upgrading data_lake_schema to v9");
649 let mut tr = pool.begin().await?;
650 upgrade_data_lake_schema_v9(&mut tr).await?;
651 current_version = read_data_lake_schema_version(&mut tr).await;
652 tr.commit().await?;
653 }
654 if 9 == current_version {
655 info!("upgrading data_lake_schema to v10");
656 let mut tr = pool.begin().await?;
657 upgrade_data_lake_schema_v10(&mut tr).await?;
658 current_version = read_data_lake_schema_version(&mut tr).await;
659 tr.commit().await?;
660 }
661 if 10 == current_version {
662 info!("upgrading data_lake_schema to v11");
663 let mut tr = pool.begin().await?;
664 upgrade_data_lake_schema_v11(&mut tr).await?;
665 current_version = read_data_lake_schema_version(&mut tr).await;
666 tr.commit().await?;
667 }
668 if 11 == current_version {
669 info!("upgrading data_lake_schema to v12");
670 let mut tr = pool.begin().await?;
671 upgrade_data_lake_schema_v12(&mut tr).await?;
672 current_version = read_data_lake_schema_version(&mut tr).await;
673 tr.commit().await?;
674 }
675 if 12 == current_version {
676 info!("upgrading data_lake_schema to v13");
677 let mut tr = pool.begin().await?;
678 upgrade_data_lake_schema_v13(&mut tr).await?;
679 current_version = read_data_lake_schema_version(&mut tr).await;
680 tr.commit().await?;
681 }
682 if 13 == current_version {
683 info!("upgrading data_lake_schema to v14");
684 let mut tr = pool.begin().await?;
685 upgrade_data_lake_schema_v14(&mut tr).await?;
686 current_version = read_data_lake_schema_version(&mut tr).await;
687 tr.commit().await?;
688 }
689 assert_eq!(current_version, LATEST_DATA_LAKE_SCHEMA_VERSION);
690 Ok(())
691}