rustango 0.57.7

Django-shaped 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
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
//! Where a provisioning run lives while it happens, and after.
//!
//! Slices [#1318] and [#1320] produce a stream of events. Holding them
//! only in memory fails two ways that matter:
//!
//! **Replay.** [`crate::sse::EventBus`] is a `tokio::sync::broadcast`
//! wrapper, so a subscriber sees only what is sent *after* it connects.
//! Provisioning starts on a POST and the browser connects on the *next*
//! request — the opening steps are gone before anyone is listening, and
//! a mid-run reload loses the rest.
//!
//! **Two pods.** Behind a load balancer the operator watching the
//! stream may not be on the pod doing the work. In-process state means
//! they watch an empty page while provisioning runs fine elsewhere.
//! This is the same problem the resolver solved with a registry
//! fingerprint rather than a shared cache: put it in the database both
//! pods already have.
//!
//! [#1318]: https://github.com/ujeenet/rustango/issues/1318
//! [#1320]: https://github.com/ujeenet/rustango/issues/1320
//!
//! ## Credentials are never stored
//!
//! A run records the URL it was asked to provision, and a connection
//! URL has a password in it. [`crate::sql::connect_diagnosis::redact`]
//! is applied on the way in — not on the way out, so there is no
//! reading path that can forget it. The same goes for event messages,
//! which carry connection diagnoses.

use serde::Serialize;

use crate::core::Column as _;
use crate::sql::{Auto, FetcherPool, Pool, UpdaterPool};

use super::error::TenancyError;

/// Where a provisioning run has got to.
///
/// Stored as a short string rather than an enum column so a state can
/// be added without a migration, and so a human reading the table with
/// `psql` can see what it says.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunState {
    /// Accepted, not started. The state a webhook returns on.
    Pending,
    Running,
    Succeeded,
    /// Stopped at some step. `ProvisioningRun::error` says which.
    Failed,
}

impl RunState {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::Running => "running",
            Self::Succeeded => "succeeded",
            Self::Failed => "failed",
        }
    }

    /// Parse a stored value. Unknown strings read as `Failed` rather
    /// than panicking: a row written by a newer build should not take
    /// down an older one, and "something went wrong" is the safe
    /// reading of a state this binary does not know.
    #[must_use]
    pub fn parse(raw: &str) -> Self {
        match raw {
            "pending" => Self::Pending,
            "running" => Self::Running,
            "succeeded" => Self::Succeeded,
            _ => Self::Failed,
        }
    }

    /// Nothing more will happen to this run.
    #[must_use]
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Succeeded | Self::Failed)
    }
}

/// One attempt to stand up a tenant.
/// What a run was for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunKind {
    Provision,
    Migrate,
}

impl RunKind {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Provision => "provision",
            Self::Migrate => "migrate",
        }
    }

    /// Unknown values read as `Provision`: every row written before the
    /// column existed was one.
    #[must_use]
    pub fn parse(raw: &str) -> Self {
        match raw {
            "migrate" => Self::Migrate,
            _ => Self::Provision,
        }
    }
}

#[derive(crate::Model, Debug, Clone, Serialize)]
#[rustango(
    table = "rustango_provisioning_runs",
    scope = "registry",
    display = "slug",
    admin(
        list_display = "slug, state, started_at, finished_at",
        ordering = "-started_at",
    )
)]
pub struct ProvisioningRun {
    #[rustango(primary_key)]
    pub id: crate::sql::Auto<i64>,

    /// What the run was: standing a tenant up, or migrating one.
    ///
    /// Both produce the same stream of steps and both are worth keeping,
    /// so they share a table; without this a migrate run reads as a
    /// provisioning run that skipped most of its steps.
    #[rustango(max_length = 16, index, default = "'provision'")]
    pub kind: String,

    /// The tenant this run is for. Not a foreign key: the row is
    /// written *before* the `Org` exists, and must survive the tenant
    /// later being purged — a run is a record of what happened, and an
    /// `ON DELETE CASCADE` would erase exactly the history someone
    /// comes looking for.
    #[rustango(max_length = 100, index)]
    pub slug: String,

    /// Set once the `Org` row lands. `None` while a run is still before
    /// that step, or if it failed before reaching it.
    pub org_id: Option<i64>,

    /// `pending` / `running` / `succeeded` / `failed`. See [`RunState`].
    #[rustango(max_length = 16, index)]
    pub state: String,

    #[rustango(max_length = 16)]
    pub storage_mode: String,

    #[rustango(max_length = 16)]
    pub backend_kind: String,

    /// **Redacted.** The password is replaced before this is stored;
    /// see the module docs.
    #[rustango(max_length = 500)]
    pub database_url: Option<String>,

    /// Who asked for this run — an operator username, a webhook's
    /// caller id, or `cli`. Free text on purpose: the sources are not
    /// one namespace.
    #[rustango(max_length = 150)]
    pub requested_by: Option<String>,

    /// The caller-supplied key that makes a retried request return this
    /// run instead of creating a second tenant. Unique so the database,
    /// not the handler, is what wins a race between two simultaneous
    /// deliveries of one event.
    #[rustango(max_length = 200, unique)]
    pub idempotency_key: Option<String>,

    /// Why it failed, if it did. Already rendered for display.
    pub error: Option<String>,

    #[rustango(auto_now_add)]
    pub started_at: crate::sql::Auto<chrono::DateTime<chrono::Utc>>,

    pub finished_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// One thing that happened during a run.
///
/// The stream a console replays. Deliberately append-only: an event is
/// a fact about the past, and the value of the log is that it is what
/// actually happened rather than a summary someone kept up to date.
#[derive(crate::Model, Debug, Clone, Serialize)]
#[rustango(
    table = "rustango_provisioning_events",
    scope = "registry",
    display = "message",
    admin(list_display = "run_id, seq, step, status", ordering = "run_id, seq")
)]
pub struct ProvisioningEvent {
    #[rustango(primary_key)]
    pub id: crate::sql::Auto<i64>,

    #[rustango(fk = "rustango_provisioning_runs", on = "id", index)]
    pub run_id: i64,

    /// Monotonic within a run, from 1. **This is what `Last-Event-ID`
    /// resumes from**, so it has to be dense and ordered — an
    /// autoincrement `id` would be globally ordered but not per-run,
    /// and a reconnecting client would have nothing to count from.
    pub seq: i64,

    /// Which provisioning step, or `migration` for a forwarded
    /// migration event.
    #[rustango(max_length = 32)]
    pub step: String,

    /// `started` / `ok` / `skipped` / `failed` / `info`.
    #[rustango(max_length = 16)]
    pub status: String,

    /// Human-readable detail. Empty for a bare transition.
    pub message: String,

    #[rustango(auto_now_add)]
    pub at: crate::sql::Auto<chrono::DateTime<chrono::Utc>>,
}

/// Open a run, before any work starts.
///
/// `database_url` is redacted here rather than by the caller: this is
/// the only way into the table, so redacting on the way in means there
/// is no path that can forget.
///
/// # Errors
/// A registry write failure — or a unique-constraint violation on
/// `idempotency_key`, which is the intended way two simultaneous
/// deliveries of one event resolve to one run.
pub async fn open_run(
    registry: &Pool,
    slug: &str,
    storage_mode: &str,
    backend_kind: &str,
    database_url: Option<&str>,
    requested_by: Option<&str>,
    idempotency_key: Option<&str>,
) -> Result<ProvisioningRun, TenancyError> {
    let mut run = ProvisioningRun {
        id: Auto::default(),
        kind: RunKind::Provision.as_str().to_owned(),
        slug: slug.to_owned(),
        org_id: None,
        state: RunState::Running.as_str().to_owned(),
        storage_mode: storage_mode.to_owned(),
        backend_kind: backend_kind.to_owned(),
        database_url: database_url.map(crate::sql::connect_diagnosis::redact),
        requested_by: requested_by.map(ToOwned::to_owned),
        idempotency_key: idempotency_key.map(ToOwned::to_owned),
        error: None,
        started_at: Auto::default(),
        finished_at: None,
    };
    run.insert_pool(registry).await?;
    Ok(run)
}

/// Append an event to a run.
///
/// `seq` is supplied by the caller rather than computed here: the
/// caller is emitting a known sequence and a `SELECT MAX(seq)` per
/// event would be a round-trip per line of a progress stream, plus a
/// race between two writers.
///
/// # Errors
/// A registry write failure.
pub async fn append_event(
    registry: &Pool,
    run_id: i64,
    seq: i64,
    step: &str,
    status: &str,
    message: &str,
) -> Result<(), TenancyError> {
    let mut event = ProvisioningEvent {
        id: Auto::default(),
        run_id,
        seq,
        step: step.to_owned(),
        status: status.to_owned(),
        message: message.to_owned(),
        at: Auto::default(),
    };
    event.insert_pool(registry).await?;
    Ok(())
}

/// Record that the `Org` row now exists, so a run that fails later
/// still says which tenant it half-made.
///
/// # Errors
/// A registry write failure.
pub async fn attach_org(registry: &Pool, run_id: i64, org_id: i64) -> Result<(), TenancyError> {
    ProvisioningRun::objects()
        .where_(ProvisioningRun::id.eq(run_id))
        .update()
        .set("org_id", org_id)
        .execute_pool(registry)
        .await?;
    Ok(())
}

/// Close a run.
///
/// # Errors
/// A registry write failure.
pub async fn finish_run(
    registry: &Pool,
    run_id: i64,
    state: RunState,
    error: Option<&str>,
) -> Result<(), TenancyError> {
    ProvisioningRun::objects()
        .where_(ProvisioningRun::id.eq(run_id))
        .update()
        .set("state", state.as_str())
        .set("error", error)
        .set("finished_at", chrono::Utc::now())
        .execute_pool(registry)
        .await?;
    Ok(())
}

/// Read a run by id.
///
/// # Errors
/// A registry read failure.
pub async fn run_by_id(
    registry: &Pool,
    run_id: i64,
) -> Result<Option<ProvisioningRun>, TenancyError> {
    Ok(ProvisioningRun::objects()
        .where_(ProvisioningRun::id.eq(run_id))
        .fetch(registry)
        .await?
        .into_iter()
        .next())
}

/// Find the run a caller's idempotency key already opened.
///
/// # Errors
/// A registry read failure.
pub async fn run_by_idempotency_key(
    registry: &Pool,
    key: &str,
) -> Result<Option<ProvisioningRun>, TenancyError> {
    Ok(ProvisioningRun::objects()
        .where_(ProvisioningRun::idempotency_key.eq(Some(key.to_owned())))
        .fetch(registry)
        .await?
        .into_iter()
        .next())
}

/// Replay a run's events, in order, from `after_seq` exclusive.
///
/// `after_seq` of 0 is the whole log — what a fresh subscriber wants.
/// A reconnecting one passes the last `seq` it saw (its
/// `Last-Event-ID`) and gets only what it missed.
///
/// # Errors
/// A registry read failure.
pub async fn events_since(
    registry: &Pool,
    run_id: i64,
    after_seq: i64,
) -> Result<Vec<ProvisioningEvent>, TenancyError> {
    Ok(ProvisioningEvent::objects()
        .where_(ProvisioningEvent::run_id.eq(run_id))
        .where_(ProvisioningEvent::seq.gt(after_seq))
        // Ascending — the bool is `desc`. A replay handed back newest
        // first is not a replay.
        .order_by(&[("seq", false)])
        .fetch(registry)
        .await?)
}

/// Open a run for a migration.
///
/// `slug` names one tenant, or `None` for every active tenant — a batch
/// stores an empty slug, and the events name each tenant as they go.
/// The storage/backend columns stay empty for the same reason: a batch
/// spans tenants that do not agree on either.
///
/// # Errors
/// Driver / insert failures.
pub async fn open_migrate_run(
    registry: &Pool,
    slug: Option<&str>,
    requested_by: Option<&str>,
) -> Result<ProvisioningRun, TenancyError> {
    let mut run = ProvisioningRun {
        id: Auto::default(),
        kind: RunKind::Migrate.as_str().to_owned(),
        slug: slug.unwrap_or_default().to_owned(),
        org_id: None,
        state: RunState::Running.as_str().to_owned(),
        storage_mode: String::new(),
        backend_kind: String::new(),
        database_url: None,
        requested_by: requested_by.map(ToOwned::to_owned),
        idempotency_key: None,
        error: None,
        started_at: Auto::default(),
        finished_at: None,
    };
    run.insert_pool(registry).await?;
    Ok(run)
}

/// The most recent runs, newest first.
///
/// A run is reachable by id and nothing enumerated them, so a console
/// could show a run only while its redirect was still in the address
/// bar — navigate away and the record survived in the table but not in
/// anybody's reach. That is the opposite of why the table is persisted.
///
/// `limit` is a page size rather than a promise to return everything:
/// the table grows with provisioning activity and a console asking for
/// "recent" wants a screenful.
///
/// # Errors
/// Driver / query failures.
pub async fn recent_runs(
    registry: &Pool,
    limit: i64,
    offset: i64,
) -> Result<Vec<ProvisioningRun>, TenancyError> {
    recent_runs_filtered(registry, None, None, limit, offset).await
}

/// As [`recent_runs`], narrowed to one `kind` and/or `state`.
///
/// The filter belongs in the query, not in a `.filter()` on the result:
/// filtering a page of the newest N reports "none" whenever the newest N
/// happen to be a different kind, which is exactly the answer nobody wants
/// while looking for the migration run that failed last week.
///
/// # Errors
/// Driver / query failures.
pub async fn recent_runs_filtered(
    registry: &Pool,
    kind: Option<&str>,
    state: Option<&str>,
    limit: i64,
    offset: i64,
) -> Result<Vec<ProvisioningRun>, TenancyError> {
    let mut q = ProvisioningRun::objects();
    if let Some(k) = kind {
        q = q.where_(ProvisioningRun::kind.eq(k.to_owned()));
    }
    if let Some(s) = state {
        q = q.where_(ProvisioningRun::state.eq(s.to_owned()));
    }
    Ok(q
        // Descending — the bool is `desc`, and "recent" means the run
        // somebody just started is the one at the top.
        .order_by(&[("id", true)])
        .limit(limit)
        .offset(offset)
        .fetch(registry)
        .await?)
}

/// Delete finished runs older than `cutoff`, and their events.
///
/// Runs are append-only and one per tenant creation, so the table grows
/// with provisioning activity and nothing removes it. Unfinished runs
/// are never pruned regardless of age — one stuck in `running` is
/// evidence of a pod that died mid-provision, which is exactly what
/// someone will come looking for.
///
/// Returns how many runs were removed.
///
/// # Errors
/// A registry write failure.
pub async fn prune_runs(
    registry: &Pool,
    cutoff: chrono::DateTime<chrono::Utc>,
) -> Result<usize, TenancyError> {
    let stale: Vec<ProvisioningRun> = ProvisioningRun::objects()
        .where_(ProvisioningRun::finished_at.lt(Some(cutoff)))
        .fetch(registry)
        .await?;

    let mut removed = 0;
    for run in stale {
        let Some(id) = run.id.get().copied() else {
            continue;
        };
        // Children first: the FK points this way, and a database with
        // it enforced would refuse the parent delete otherwise.
        //
        // Row at a time because the ORM has no queryset-level delete
        // through a `Pool`. Acceptable here — this is a maintenance
        // verb over a couple of dozen events per run, not a request
        // path — but it is why `prune_runs` is not something to call
        // in a loop.
        let events: Vec<ProvisioningEvent> = ProvisioningEvent::objects()
            .where_(ProvisioningEvent::run_id.eq(id))
            .fetch(registry)
            .await?;
        for event in events {
            event.delete_pool(registry).await?;
        }
        run.delete_pool(registry).await?;
        removed += 1;
    }
    Ok(removed)
}