operon 0.7.0

A workflow engine for parallel, incremental scheduling of DAG-defined multiplex tasks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
use std::fmt::Display;
use std::hash::{Hash, Hasher};
use std::num::TryFromIntError;

use indoc::formatdoc;
use postgres_types::ToSql;
use tokio_postgres::Row;
use twox_hash::XxHash3_64;

use crate::schema::{TableShape, TicketStatus};

/// The primary key for the run footprint table.
pub(crate) const GLOBAL: &str = "global";

/// The footprint tables' schema version.
///
/// Whenever reading/writing the footprint changes, this is bumped to a new version.
/// The footprint tables are dropped and rebuilt when the running version and the recorded version
/// differ.
///
/// Every version stores the run's `run_id` and `updated_at`, which a rebuild carries over.
pub(crate) const FOOTPRINT_VERSION: u32 = 1;

/// An optional schema prefix with a `Display` impl.
#[derive(Debug, Clone, Copy)]
pub struct SchemaPrefix<'a>(pub Option<&'a str>);

/// An optional owned schema prefix with a `Display` impl.
#[derive(Debug, Clone)]
pub struct SchemaPrefixOwned(pub Option<String>);

impl SchemaPrefix<'_> {
    /// Converts this borrowed prefix into an owned one.
    pub fn into_owned(self) -> SchemaPrefixOwned {
        SchemaPrefixOwned(self.0.map(|s| s.to_owned()))
    }
}

impl Display for SchemaPrefix<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(schema) = self.0 {
            write!(f, "{schema}.")
        } else {
            Ok(())
        }
    }
}

impl Display for SchemaPrefixOwned {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(schema) = &self.0 {
            write!(f, "{schema}.")
        } else {
            Ok(())
        }
    }
}

/// Values that can be used as sql parameter.
pub(crate) trait SqlParam: ToSql + Display + Send + Sync + 'static {
    /// Borrows the value as the trait object `tokio_postgres` takes its parameters as.
    fn as_param(&self) -> &(dyn ToSql + Sync + 'static);
}

impl SqlParam for String {
    fn as_param(&self) -> &(dyn ToSql + Sync + 'static) {
        self
    }
}
impl SqlParam for i64 {
    fn as_param(&self) -> &(dyn ToSql + Sync + 'static) {
        self
    }
}
impl SqlParam for serde_json::Value {
    fn as_param(&self) -> &(dyn ToSql + Sync + 'static) {
        self
    }
}
impl SqlParam for TicketStatus {
    fn as_param(&self) -> &(dyn ToSql + Sync + 'static) {
        self
    }
}

/// A list of sql parameters.
#[repr(transparent)]
pub(crate) struct SqlParams(Vec<Box<dyn SqlParam>>);

impl SqlParams {
    pub(crate) fn new(params: Vec<Box<dyn SqlParam>>) -> Self {
        Self(params)
    }

    pub(crate) fn from_usize(
        items: impl IntoIterator<Item = usize>,
    ) -> Result<Self, TryFromIntError> {
        let items = items
            .into_iter()
            .map(|item| i64::try_from(item).map(box_sql))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self(items))
    }

    pub(crate) fn extend(mut self, params: Vec<Box<dyn SqlParam>>) -> Self {
        self.0.extend(params);
        self
    }

    pub(crate) fn borrow(&self) -> Vec<&(dyn ToSql + Sync + 'static)> {
        self.0.iter().map(|x| x.as_param()).collect()
    }

    pub(crate) fn to_copy_string(&self) -> String {
        let mut out = self
            .0
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(",");
        out.push('\n');
        out
    }
}

pub(crate) fn box_sql<T: SqlParam>(value: T) -> Box<dyn SqlParam> {
    Box::new(value)
}

/// Renders `values` as a quoted, comma-separated SQL list.
pub(crate) fn sql_value_list<T: Display>(values: impl IntoIterator<Item = T>) -> String {
    values
        .into_iter()
        .map(|value| format!("'{value}'"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Compacts metadata of any length into a shape ID.
pub(crate) fn hash_metadata<T: Hash>(metadata: &T) -> String {
    let mut hasher = XxHash3_64::new();
    metadata.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// The maximum length of a PostgreSQL identifier.
const PSQL_MAX_IDENTIFIER_LENGTH: usize = 63;

/// The number of characters to take from the original ID for human readability.
const PSQL_ID_PREFIX_LENGTH: usize = 4;

/// The length threshold above which IDs are hashed to fit within PostgreSQL's identifier limit.
const PSQL_ID_CLAMP_THRESHOLD: usize = 20;

/// Generates a PostgreSQL-safe identifier from a user-provided ID.
///
/// Postgres limits identifiers to 63 bytes, so this function hashes the ID to ensure it fits.
/// The output consists of:
/// - The provided `prefix`.
/// - The first 4 characters of the provided `id`.
/// - A 16-character hash of the provided `id`.
///
/// in the format `{prefix}_{id_prefix}_{hash}`.
pub(crate) fn psql_identifier(prefix: &str, id: &str) -> String {
    let id = if id.len() <= PSQL_ID_CLAMP_THRESHOLD {
        id.to_owned()
    } else {
        let id_prefix: String = id.chars().take(PSQL_ID_PREFIX_LENGTH).collect();
        let hash = hash_str(id);
        format!("{id_prefix}_{hash}")
    };

    let result = format!("{prefix}_{id}");
    debug_assert!(
        result.len() <= PSQL_MAX_IDENTIFIER_LENGTH,
        "PSQL identifier may exceed 63 bytes: {result} (length: {})",
        result.len(),
    );

    result
}

/// Hashes a string into a 16-character hex string.
fn hash_str(s: &str) -> String {
    let mut hasher = XxHash3_64::new();
    s.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

/// The table the shape IDs are recorded in.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ShapeTable<'a> {
    /// The table the shape IDs are recorded in.
    pub table: &'a str,
    /// The column a shape ID is held in.
    pub column: &'a str,
}

impl<'a> ShapeTable<'a> {
    /// The row of this table holding `id`'s shape ID.
    pub(crate) const fn record(self, id: &'a str) -> ShapeRecord<'a> {
        ShapeRecord { table: self, id }
    }
}

/// The specification to find a shape ID in the database.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ShapeRecord<'a> {
    /// The table the shape ID is recorded in.
    pub table: ShapeTable<'a>,
    /// The primary key value to match in `WHERE id = {id}`.
    pub id: &'a str,
}

/// The table holding each storage's footprint version.
///
/// Giving each storage a different [`record`](ShapeTable::record) lets one schema hold both
/// footprints.
pub(crate) const FOOTPRINT_SHAPES: ShapeTable<'static> = ShapeTable {
    table: "_footprint_version",
    column: "version",
};

/// Creates the table shape IDs are recorded in.
pub(crate) fn init_shape_table_query(
    shape_table: ShapeTable<'_>,
    schema_prefix: SchemaPrefix<'_>,
) -> String {
    let ShapeTable { table, column } = shape_table;

    formatdoc! {"
        CREATE TABLE IF NOT EXISTS {schema_prefix}{table} (
            id TEXT PRIMARY KEY,
            {column} TEXT NOT NULL
        );"
    }
}

/// The SQL conditions for each of `tables` existing, joined by `connective`.
fn tables_present(tables: &[&str], schema_prefix: SchemaPrefix<'_>, connective: &str) -> String {
    tables
        .iter()
        .map(|table| format!("to_regclass('{schema_prefix}{table}') IS NOT NULL"))
        .collect::<Vec<_>>()
        .join(connective)
}

/// The SQL condition for any of `tables` existing.
fn any_table_present(tables: &[&str], schema_prefix: SchemaPrefix<'_>) -> String {
    tables_present(tables, schema_prefix, " OR ")
}

/// The SQL condition for all of `tables` existing.
fn all_tables_present(tables: &[&str], schema_prefix: SchemaPrefix<'_>) -> String {
    tables_present(tables, schema_prefix, " AND ")
}

/// Which tables of a group exist in the database.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TablesPresent {
    /// None of the tables exist.
    None,
    /// Some, but not all, of the tables exist.
    Partial,
    /// All of the tables exist.
    All,
}

impl TablesPresent {
    /// Reads the presence columns of a [`shape_query`] row.
    fn from_row(row: &Row) -> Self {
        let any: bool = row.get("any_present");
        let all: bool = row.get("all_present");

        match (any, all) {
            (_, true) => Self::All,
            (true, false) => Self::Partial,
            (false, false) => Self::None,
        }
    }
}

/// The query for the shape ID `record` points to and which of `tables` exist.
///
/// Returns one row, with the columns `shape_id`, `any_present`, and `all_present`.
pub(crate) fn shape_query(
    record: ShapeRecord<'_>,
    tables: &[&str],
    schema_prefix: SchemaPrefix<'_>,
) -> String {
    let ShapeRecord {
        table: ShapeTable { table, column },
        id,
    } = record;
    let any_present = any_table_present(tables, schema_prefix);
    let all_present = all_tables_present(tables, schema_prefix);

    formatdoc! {"
        SELECT
            (SELECT {column} FROM {schema_prefix}{table} WHERE id = '{id}') AS shape_id,
            ({any_present}) AS any_present,
            ({all_present}) AS all_present;"
    }
}

/// What action to take when initializing a table group via [`build_tables`].
/// Found by comparing the shape ID in the database with the current one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShapeAction {
    /// The tables need no changes.
    Keep,
    /// The tables can be built without dropping anything.
    Build,
    /// The tables carry a mismatching shape ID, and should be dropped before being built.
    Rebuild,
}

impl ShapeAction {
    /// The action to take, given what the database holds.
    ///
    /// A group is rebuilt when its recorded shape ID differs, or when only some of its tables
    /// exist.
    pub fn new(recorded: Option<&str>, present: TablesPresent, shape_id: &str) -> Self {
        match (recorded, present) {
            (_, TablesPresent::None) => Self::Build,
            (Some(recorded), TablesPresent::All) if recorded == shape_id => Self::Keep,
            _ => Self::Rebuild,
        }
    }

    /// [`ShapeAction::new`] over a [`shape_query`] row.
    pub fn from_row(row: Option<&Row>, shape_id: &str) -> Self {
        row.map_or(Self::Build, |row| {
            Self::new(row.get("shape_id"), TablesPresent::from_row(row), shape_id)
        })
    }
}

impl From<ShapeAction> for TableShape {
    fn from(action: ShapeAction) -> Self {
        match action {
            ShapeAction::Rebuild => Self::STALE,
            ShapeAction::Keep | ShapeAction::Build => Self::CURRENT,
        }
    }
}

/// A query that wraps `init_query` and records `shape_id` in the specified `record`.
/// Depending on `action`, it also drops outdated tables or skips redundant queries.
///
/// # Assumptions
///
/// `init_query` should perform the correct initialization (`CREATE TABLE` and other necessary
/// statements) for the tables in `tables`.
///
/// # Output query behaviour by `action`
///
/// - [`Keep`](`ShapeAction::Keep`): no-op (`None`).
/// - [`Build`](`ShapeAction::Build`): Runs `init_query` and records `shape_id`.
/// - [`Rebuild`](`ShapeAction::Rebuild`): Drops the tables in `tables`, runs `init_query`, and
///   records `shape_id`.
pub(crate) fn build_tables(
    record: ShapeRecord<'_>,
    tables: &[&str],
    shape_id: &str,
    schema_prefix: SchemaPrefix<'_>,
    action: ShapeAction,
    init_query: impl Display,
) -> Option<String> {
    let ShapeRecord {
        table: ShapeTable { table, column },
        id,
    } = record;

    // Cross-referencing tables should be dropped in a single statement.
    let qualified = tables
        .iter()
        .map(|table| format!("{schema_prefix}{table}"))
        .collect::<Vec<_>>()
        .join(", ");
    let drop_tables = format!("DROP TABLE IF EXISTS {qualified};");
    let record_shape = formatdoc! {"
        INSERT INTO {schema_prefix}{table} (id, {column})
        VALUES ('{id}', '{shape_id}')
        ON CONFLICT (id) DO UPDATE SET {column} = EXCLUDED.{column};"
    };

    match action {
        ShapeAction::Keep => None,
        ShapeAction::Build => Some(format!("{init_query}\n\n{record_shape}")),
        ShapeAction::Rebuild => Some(format!("{drop_tables}\n\n{init_query}\n\n{record_shape}")),
    }
}

#[cfg(test)]
pub(crate) mod fixtures {
    use std::fmt::Display;
    use std::path::{Path, PathBuf};

    use pretty_assertions::assert_eq;

    use super::FOOTPRINT_VERSION;

    /// The environment variable that makes a test record the current shape instead of comparing
    /// against it.
    const BLESS: &str = "BLESS_FOOTPRINT_SHAPE";

    #[derive(Debug, Clone, Copy)]
    pub(crate) enum FootprintStore {
        Data,
        Meta,
    }
    impl FootprintStore {
        const ALL: [Self; 2] = [Self::Data, Self::Meta];
    }
    impl Display for FootprintStore {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                FootprintStore::Data => write!(f, "data"),
                FootprintStore::Meta => write!(f, "meta"),
            }
        }
    }

    /// Asserts that `stmt` matches the shape recorded for the current [`FOOTPRINT_VERSION`].
    ///
    /// Set `BLESS_FOOTPRINT_SHAPE` to record `stmt` for a [`FOOTPRINT_VERSION`] that has no
    /// fixture yet.
    /// A version that already has a fixture keeps it.
    /// Changing the shape of a released version therefore needs a version bump, since schemas
    /// built by that release still hold the old shape.
    pub(crate) fn assert_footprint_shape(store: FootprintStore, stmt: &str) {
        let path = fixture_path(FOOTPRINT_VERSION, store);
        let blessing = std::env::var_os(BLESS).is_some();

        let recorded = match std::fs::read_to_string(&path) {
            Ok(recorded) => recorded,
            Err(e) if blessing && e.kind() == std::io::ErrorKind::NotFound => {
                return record(&path, stmt);
            }
            Err(e) => panic!(
                "Could not read {}: {e}\nRun the tests with {BLESS}=1 to record it.",
                path.display()
            ),
        };
        assert_eq!(
            tokens(stmt),
            tokens(&recorded),
            "The {store} footprint no longer matches the shape recorded for \
             v{FOOTPRINT_VERSION}. Raise FOOTPRINT_VERSION to {next} and re-run the tests with \
             {BLESS}=1 to record the new shape. If v{FOOTPRINT_VERSION} has not shipped, delete \
             {} and re-run with {BLESS}=1 instead.",
            path.display(),
            next = FOOTPRINT_VERSION + 1,
        );
    }

    /// Writes `stmt` into the fixture at `path`, creating its version directory.
    fn record(path: &Path, stmt: &str) {
        let dir = path
            .parent()
            .expect("the fixture sits in a version directory");
        std::fs::create_dir_all(dir)
            .unwrap_or_else(|e| panic!("Could not create {}: {e}", dir.display()));
        std::fs::write(path, format!("{stmt}\n"))
            .unwrap_or_else(|e| panic!("Could not write {}: {e}", path.display()));
    }

    /// A SQL statement split for whitespace-insensitive comparison.
    fn tokens(stmt: &str) -> Vec<&str> {
        stmt.split_whitespace().collect()
    }

    fn fixture_path(version: u32, store: FootprintStore) -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("fixtures/footprint")
            .join(format!("v{version}"))
            .join(format!("{store}.sql"))
    }

    #[test]
    fn test_all_fixtures_present() {
        if std::env::var_os(BLESS).is_some() {
            return;
        }

        for version in 1..=FOOTPRINT_VERSION {
            for store in FootprintStore::ALL {
                let path = fixture_path(version, store);
                assert!(
                    path.exists(),
                    "Missing footprint fixture for v{version} {store}: {}",
                    path.display()
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    #[case::short("short_id", "ticket_short_id")]
    #[case::long(
        "this_is_a_very_long_task_name_that_would_exceed_postgresql_limits",
        "ticket_this_738f27982fd1f340"
    )]
    fn test_psql_identifier_long_id_fits(#[case] id: &str, #[case] expected: &str) {
        let result = psql_identifier("ticket", id);
        assert_eq!(result, expected);
    }

    #[rstest]
    #[case::unbuilt(None, TablesPresent::None, ShapeAction::Build)]
    #[case::unrecorded(None, TablesPresent::All, ShapeAction::Rebuild)]
    #[case::matching(Some("1"), TablesPresent::All, ShapeAction::Keep)]
    #[case::diverged(Some("2"), TablesPresent::All, ShapeAction::Rebuild)]
    #[case::matching_but_dropped(Some("1"), TablesPresent::None, ShapeAction::Build)]
    #[case::diverged_and_dropped(Some("2"), TablesPresent::None, ShapeAction::Build)]
    #[case::matching_but_partial(Some("1"), TablesPresent::Partial, ShapeAction::Rebuild)]
    #[case::unrecorded_and_partial(None, TablesPresent::Partial, ShapeAction::Rebuild)]
    #[case::diverged_and_partial(Some("2"), TablesPresent::Partial, ShapeAction::Rebuild)]
    fn test_shape_action_new(
        #[case] recorded: Option<&str>,
        #[case] present: TablesPresent,
        #[case] expected: ShapeAction,
    ) {
        assert_eq!(ShapeAction::new(recorded, present, "1"), expected);
    }

    #[rstest]
    #[case::build(ShapeAction::Build, false)]
    #[case::rebuild(ShapeAction::Rebuild, true)]
    fn test_build_tables_drops_named_tables_together(
        #[case] action: ShapeAction,
        #[case] drops: bool,
    ) {
        let stmt = build_tables(
            FOOTPRINT_SHAPES.record("runs"),
            &["run_executions", "runs"],
            "1",
            SchemaPrefix(Some("test_meta")),
            action,
            "CREATE TABLE test_meta.runs ();",
        )
        .expect("a statement to run");
        assert_eq!(
            stmt.contains("DROP TABLE IF EXISTS test_meta.run_executions, test_meta.runs;"),
            drops,
            "{stmt}"
        );
    }
}