rustango 0.61.13

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! `delete` audit rows for the audited rows an FK `ON DELETE CASCADE`
//! removes, `update` rows for the ones `SET NULL` / `SET DEFAULT` changes.
//! Read before the delete, written after it for the rows it took or changed.

use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;

use crate::core::{
    CountQuery, DeleteQuery, Filter, ModelEntry, ModelSchema, OnDeleteAction, Op, Relation,
    SelectQuery, SqlValue, WhereExpr,
};
use crate::sql::{ExecError, PoolTx};

use super::{emit_many_tx, pk_in, AuditOp, PendingEntry, Via, BULK_AUDIT_CHUNK};

/// `child.fk_column` references `parent.on` with `ON DELETE CASCADE`, or
/// with `SET NULL` / `SET DEFAULT` to an audited child (`sets`).
struct Edge {
    child: &'static ModelEntry,
    fk_column: &'static str,
    on: &'static str,
    sets: bool,
}

/// The cascade edges out of `table` that lead to an audited model.
fn edges(table: &str) -> &'static [Edge] {
    static GRAPH: OnceLock<HashMap<&'static str, Vec<Edge>>> = OnceLock::new();
    GRAPH
        .get_or_init(build_graph)
        .get(table)
        .map_or(&[], Vec::as_slice)
}

/// One registry entry per table: a project model over a framework one,
/// then the first by model name, so the pick does not depend on link order.
fn canonical_entries() -> Vec<&'static ModelEntry> {
    let mut by_table: HashMap<&'static str, &'static ModelEntry> = HashMap::new();
    for entry in crate::core::inventory::iter::<ModelEntry> {
        let key = |e: &ModelEntry| (e.is_framework(), e.schema.name);
        by_table
            .entry(entry.schema.table)
            .and_modify(|kept| {
                if key(entry) < key(kept) {
                    *kept = entry;
                }
            })
            .or_insert(entry);
    }
    by_table.into_values().collect()
}

fn build_graph() -> HashMap<&'static str, Vec<Edge>> {
    let entries = canonical_entries();
    let mut graph: HashMap<&'static str, Vec<Edge>> = HashMap::new();
    for &entry in &entries {
        let audited = entry.schema.audit_track.is_some();
        for field in entry.schema.fields {
            let (Some(action), Some(Relation::Fk { to, on } | Relation::O2O { to, on })) =
                (field.fk_on_delete, field.relation)
            else {
                continue;
            };
            let sets = match action {
                OnDeleteAction::Cascade => false,
                OnDeleteAction::SetNull | OnDeleteAction::SetDefault if audited => true,
                _ => continue,
            };
            graph.entry(to).or_default().push(Edge {
                child: entry,
                fk_column: field.column,
                on,
                sets,
            });
        }
    }
    // Tables whose cascade reaches an audited model, to a fixed point.
    let mut reaches: HashSet<&str> = entries
        .iter()
        .filter(|e| e.schema.audit_track.is_some())
        .map(|e| e.schema.table)
        .collect();
    reaches.extend(
        graph
            .iter()
            .filter(|(_, es)| es.iter().any(|e| e.sets))
            .map(|(t, _)| *t),
    );
    loop {
        let grown: Vec<&'static str> = graph
            .iter()
            .filter(|(t, es)| {
                !reaches.contains(*t)
                    && es
                        .iter()
                        .any(|e| !e.sets && reaches.contains(e.child.schema.table))
            })
            .map(|(t, _)| *t)
            .collect();
        if grown.is_empty() {
            break;
        }
        reaches.extend(grown);
    }
    for es in graph.values_mut() {
        es.retain(|e| e.sets || reaches.contains(e.child.schema.table));
    }
    graph.retain(|_, es| !es.is_empty());
    graph
}

/// An audited table a truncate of `table` changes: rows it takes, or, for a
/// MySQL/SQLite `DELETE`, the FK it sets to NULL / default (`set`).
pub(crate) struct Reached {
    schema: &'static ModelSchema,
    set: Option<&'static str>,
    before: i64,
}

/// The audited tables a truncate of `table` reaches besides it: PG's
/// `TRUNCATE … CASCADE` empties every FK child, a `DELETE` only follows
/// `ON DELETE CASCADE` and sets the `SET NULL` / `SET DEFAULT` children.
fn truncate_reach(
    table: &str,
    every_fk: bool,
) -> Vec<(&'static ModelSchema, Option<&'static str>)> {
    let entries = canonical_entries();
    let mut out = Vec::new();
    let mut done: HashSet<&str> = HashSet::from([table]);
    let mut frontier = vec![table.to_owned()];
    let mut sets = Vec::new();
    while let Some(parent) = frontier.pop() {
        for entry in &entries {
            let schema = entry.schema;
            let refs = |f: &&crate::core::FieldSchema| matches!(f.relation, Some(Relation::Fk { to, .. } | Relation::O2O { to, .. }) if to == parent);
            let by_field = schema
                .fields
                .iter()
                .filter(refs)
                .any(|f| every_fk || f.fk_on_delete == Some(OnDeleteAction::Cascade));
            let by_composite =
                every_fk && schema.composite_relations.iter().any(|r| r.to == parent);
            if !every_fk && schema.audit_track.is_some() {
                sets.extend(
                    schema
                        .fields
                        .iter()
                        .filter(refs)
                        .filter(|f| {
                            matches!(
                                f.fk_on_delete,
                                Some(OnDeleteAction::SetNull | OnDeleteAction::SetDefault)
                            )
                        })
                        .map(|f| (schema, f.column)),
                );
            }
            if (by_field || by_composite) && done.insert(schema.table) {
                if schema.audit_track.is_some() {
                    out.push((schema, None));
                }
                frontier.push(schema.table.to_owned());
            }
        }
    }
    // A child the truncate also deletes from is counted as removed.
    for (schema, column) in sets {
        if !done.contains(schema.table) {
            out.push((schema, Some(column)));
        }
    }
    out
}

/// The audited tables a truncate of `table` reaches through its FKs, with
/// their counts; taken before it runs, for [`emit_truncated`].
pub(crate) async fn truncate_counts(
    tx: &mut PoolTx<'_>,
    table: &str,
) -> Result<Vec<Reached>, ExecError> {
    let every_fk = crate::sql::truncate_cascades_every_fk(tx.dialect());
    let mut out = Vec::new();
    for (schema, set) in truncate_reach(table, every_fk) {
        let before = row_count(tx, schema, set).await?;
        out.push(Reached {
            schema,
            set,
            before,
        });
    }
    Ok(out)
}

/// `schema`'s rows, or those whose `set` FK is not NULL.
async fn row_count(
    tx: &mut PoolTx<'_>,
    schema: &'static ModelSchema,
    set: Option<&'static str>,
) -> Result<i64, ExecError> {
    let mut select = SelectQuery::new(schema);
    if let Some(column) = set {
        select = select.where_clause(WhereExpr::Predicate(Filter::new(
            column,
            Op::IsNull,
            SqlValue::Bool(false),
        )));
    }
    crate::sql::count_rows_on(&mut *tx, &CountQuery::from_select(select)).await
}

/// One bulk entry per audited table the truncate of `table` changed: a
/// `delete` for rows taken, an `update` for an FK it set.
pub(crate) async fn emit_truncated(
    tx: &mut PoolTx<'_>,
    table: &str,
    before: Vec<Reached>,
) -> Result<(), ExecError> {
    let mut entries = Vec::new();
    for r in before {
        if r.before > 0 && row_count(tx, r.schema, r.set).await? < r.before {
            let (operation, changes) = match r.set {
                None => (
                    AuditOp::Delete,
                    serde_json::json!({ "bulk": "truncate", "cascade_from": table }),
                ),
                Some(column) => (
                    AuditOp::Update,
                    serde_json::json!({ "bulk": "truncate", "cascade_from": table, "set": column }),
                ),
            };
            entries.push(PendingEntry {
                entity_table: r.schema.table,
                entity_pk: String::new(),
                operation,
                source: super::current_source(),
                changes,
            });
        }
    }
    emit_many_tx(tx, Via::Scoped, &entries).await
}

/// Whether deleting `model` rows may cascade to an audited model.
pub(crate) fn reaches_audited(model: &ModelSchema) -> bool {
    !edges(model.table).is_empty()
}

/// Audited rows a delete will cascade to, with their entries, and the
/// audited rows whose FK it will set.
struct Pending {
    removed: Vec<(&'static ModelSchema, Vec<(SqlValue, PendingEntry)>)>,
    set: Vec<SetRows>,
}

/// Audited `child` rows `pks` whose `fk_column` holds one of `keys`.
struct SetRows {
    child: &'static ModelEntry,
    fk_column: &'static str,
    keys: Vec<SqlValue>,
    pks: Vec<SqlValue>,
}

/// Delete `query`'s rows in chunks of roots, each with the audited rows it
/// cascades to: read them locked, delete the chunk, emit for the rows gone.
/// Memory holds one chunk's cascade, plus the keys of the rows seen.
pub(crate) async fn delete_with_audit(
    tx: &mut PoolTx<'_>,
    query: &DeleteQuery,
) -> Result<u64, ExecError> {
    let mut seen: HashSet<(&'static str, String)> = HashSet::new();
    let Some(pk) = query.model.primary_key() else {
        return delete_chunk(tx, query, &mut seen).await;
    };
    // Locked up front, so the chunks cover exactly the rows `query` matches.
    let roots = column_values(tx, query.model, query.where_clause.clone(), pk.column).await?;
    // An audited model's own rows are audited by its delete path.
    if query.model.audit_track.is_some() {
        seen.extend(roots.iter().map(|k| (query.model.table, format!("{k:?}"))));
    }
    let mut affected = 0;
    for chunk in roots.chunks(BULK_AUDIT_CHUNK) {
        let part = DeleteQuery {
            model: query.model,
            where_clause: pk_in(query.model, chunk.to_vec())?,
        };
        affected += delete_chunk(tx, &part, &mut seen).await?;
    }
    Ok(affected)
}

async fn delete_chunk(
    tx: &mut PoolTx<'_>,
    query: &DeleteQuery,
    seen: &mut HashSet<(&'static str, String)>,
) -> Result<u64, ExecError> {
    let pending = snapshot(tx, query, seen).await?;
    let plan = crate::sql::compile_delete_plan(tx.dialect(), query)?;
    let affected = crate::sql::run_delete_statements_tx(tx, plan).await?;
    emit_set(tx, pending.set, seen).await?;
    emit_removed(tx, pending.removed).await?;
    Ok(affected)
}

/// Read, locked, every audited row deleting `query`'s rows would cascade to.
async fn snapshot(
    tx: &mut PoolTx<'_>,
    query: &DeleteQuery,
    seen: &mut HashSet<(&'static str, String)>,
) -> Result<Pending, ExecError> {
    let mut out: Vec<(&'static ModelSchema, Vec<(SqlValue, PendingEntry)>)> = Vec::new();
    let mut set = Vec::new();
    let mut frontier = vec![(query.model, query.where_clause.clone())];
    while let Some((model, rows)) = frontier.pop() {
        for edge in edges(model.table) {
            let keys = column_values(tx, model, rows.clone(), edge.on).await?;
            let child = edge.child.schema;
            let pk = child
                .primary_key()
                .ok_or(ExecError::MissingPrimaryKey { table: child.table })?;
            for chunk in keys.chunks(BULK_AUDIT_CHUNK) {
                let child_rows = WhereExpr::Predicate(Filter::new(
                    edge.fk_column,
                    Op::In,
                    SqlValue::List(chunk.to_vec()),
                ));
                if edge.sets {
                    let pks = column_values(tx, child, child_rows, pk.column).await?;
                    if !pks.is_empty() {
                        set.push(SetRows {
                            child: edge.child,
                            fk_column: edge.fk_column,
                            keys: chunk.to_vec(),
                            pks,
                        });
                    }
                    continue;
                }
                let found: Vec<(SqlValue, Option<PendingEntry>)> = if child.audit_track.is_some() {
                    let read = edge
                        .child
                        .audited_cascade()
                        .ok_or(ExecError::AuditUnsupported {
                            table: child.table,
                            reason: "its registry entry has no cascade recorder",
                        })?;
                    let rows = read(tx, child_rows).await?;
                    rows.into_iter().map(|(k, e)| (k, Some(e))).collect()
                } else {
                    let pks = column_values(tx, child, child_rows, pk.column).await?;
                    pks.into_iter().map(|k| (k, None)).collect()
                };
                let mut fresh = Vec::new();
                let mut entries = Vec::new();
                for (key, entry) in found {
                    if seen.insert((child.table, format!("{key:?}"))) {
                        fresh.push(key.clone());
                        entries.extend(entry.map(|e| (key, e)));
                    }
                }
                if !entries.is_empty() {
                    out.push((child, entries));
                }
                if reaches_audited(child) {
                    for part in fresh.chunks(BULK_AUDIT_CHUNK) {
                        frontier.push((child, pk_in(child, part.to_vec())?));
                    }
                }
            }
        }
    }
    Ok(Pending { removed: out, set })
}

/// Emit an `update` entry for each audited row the delete set the FK of:
/// still there (no other edge removed it), no longer pointing at a key.
async fn emit_set(
    tx: &mut PoolTx<'_>,
    set: Vec<SetRows>,
    seen: &mut HashSet<(&'static str, String)>,
) -> Result<(), ExecError> {
    for rows in set {
        let child = rows.child.schema;
        let read = rows
            .child
            .audited_cascade()
            .ok_or(ExecError::AuditUnsupported {
                table: child.table,
                reason: "its registry entry has no cascade recorder",
            })?;
        let pk = child
            .primary_key()
            .ok_or(ExecError::MissingPrimaryKey { table: child.table })?;
        let mut entries = Vec::new();
        for part in rows.pks.chunks(BULK_AUDIT_CHUNK) {
            // A missing FK (or SQLite with `foreign_keys` off) sets nothing.
            let unchanged = WhereExpr::And(vec![
                pk_in(child, part.to_vec())?,
                WhereExpr::Predicate(Filter::new(
                    rows.fk_column,
                    Op::In,
                    SqlValue::List(rows.keys.clone()),
                )),
            ]);
            let left: HashSet<String> = column_values(tx, child, unchanged, pk.column)
                .await?
                .iter()
                .map(|k| format!("{k:?}"))
                .collect();
            for (key, mut entry) in read(tx, pk_in(child, part.to_vec())?).await? {
                let key = format!("{key:?}");
                if !left.contains(&key) && seen.insert((child.table, format!("set {key}"))) {
                    entry.operation = AuditOp::Update;
                    entries.push(entry);
                }
            }
        }
        emit_many_tx(tx, Via::Scoped, &entries).await?;
    }
    Ok(())
}

/// Emit the entries of the snapshot rows the delete removed.
async fn emit_removed(
    tx: &mut PoolTx<'_>,
    removed: Vec<(&'static ModelSchema, Vec<(SqlValue, PendingEntry)>)>,
) -> Result<(), ExecError> {
    for (model, rows) in removed {
        let pk = model
            .primary_key()
            .ok_or(ExecError::MissingPrimaryKey { table: model.table })?;
        let keys: Vec<SqlValue> = rows.iter().map(|(k, _)| k.clone()).collect();
        // A missing FK (or SQLite with `foreign_keys` off) cascades nothing.
        let mut left = HashSet::new();
        for part in keys.chunks(BULK_AUDIT_CHUNK) {
            let found = column_values(tx, model, pk_in(model, part.to_vec())?, pk.column).await?;
            left.extend(found.iter().map(|k| format!("{k:?}")));
        }
        let entries: Vec<PendingEntry> = rows
            .into_iter()
            .filter(|(k, _)| !left.contains(&format!("{k:?}")))
            .map(|(_, e)| e)
            .collect();
        emit_many_tx(tx, Via::Scoped, &entries).await?;
    }
    Ok(())
}

/// `column` of `model`'s rows matching `rows`, locked on PG / MySQL.
async fn column_values(
    tx: &mut PoolTx<'_>,
    model: &'static ModelSchema,
    rows: WhereExpr,
    column: &'static str,
) -> Result<Vec<SqlValue>, ExecError> {
    let mut select = SelectQuery::new(model).where_clause(rows);
    select.projection = Some(vec![column]);
    select.lock_mode = Some(crate::core::LockMode {
        silent_on_sqlite: true,
        ..crate::core::LockMode::default()
    });
    let rows = crate::sql::fetch_values_list_on(tx, &select).await?;
    Ok(rows
        .into_iter()
        .filter_map(|r| r.into_iter().next())
        .collect())
}

/// Run `fut`, a delete through `pool`, so cascade entries keep the source.
pub(crate) async fn via_pool<F: std::future::Future>(pool: &crate::sql::Pool, fut: F) -> F::Output {
    super::writing_via(pool, fut).await
}

/// Warn once that a delete on a single-statement executor cascaded to an
/// audited model without audit rows.
pub(crate) fn warn_unaudited(table: &str) {
    static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
    if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
        tracing::warn!(
            table,
            "delete cascades to an audited model, but this executor runs one statement, \
             so the cascaded rows get no audit rows; use `delete_pool` or a `PoolTx`"
        );
    }
}