Skip to main content

awa_model/
storage.rs

1use crate::admin;
2use crate::error::AwaError;
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use sqlx::{FromRow, PgExecutor, PgPool};
6use std::collections::BTreeMap;
7
8#[derive(Debug, Clone, Serialize, Deserialize, FromRow, PartialEq)]
9pub struct StorageStatus {
10    pub current_engine: String,
11    pub active_engine: String,
12    pub prepared_engine: Option<String>,
13    pub state: String,
14    pub transition_epoch: i64,
15    pub details: serde_json::Value,
16    pub entered_at: DateTime<Utc>,
17    pub updated_at: DateTime<Utc>,
18    pub finalized_at: Option<DateTime<Utc>>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
22pub struct StorageStatusReport {
23    #[serde(flatten)]
24    pub status: StorageStatus,
25    pub canonical_live_backlog: i64,
26    pub prepared_queue_storage_schema: Option<String>,
27    pub prepared_schema_ready: bool,
28    pub live_runtime_capability_counts: BTreeMap<String, usize>,
29    pub can_enter_mixed_transition: bool,
30    pub enter_mixed_transition_blockers: Vec<String>,
31    pub can_finalize: bool,
32    pub finalize_blockers: Vec<String>,
33    /// Historical samples of `canonical_live_backlog` anchored to the
34    /// current `transition_epoch`. Only populated when the caller passes
35    /// `?history=true` on `/api/storage`. The 0.6 server returns an empty
36    /// slice because samples are accumulated client-side (no audit table
37    /// — see issue #180); this field is kept additive so future versions
38    /// that introduce server-side accumulation stay wire-compatible.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub history: Option<Vec<BacklogSample>>,
41}
42
43/// One sample of `canonical_live_backlog`, timestamped server-side. The UI
44/// uses these to render an epoch-anchored sparkline showing the full
45/// timeline of the current cutover (rather than a sliding window).
46#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47pub struct BacklogSample {
48    pub at: DateTime<Utc>,
49    pub canonical_live_backlog: i64,
50}
51
52pub async fn status<'e, E>(executor: E) -> Result<StorageStatus, AwaError>
53where
54    E: PgExecutor<'e>,
55{
56    sqlx::query_as::<_, StorageStatus>("SELECT * FROM awa.storage_status()")
57        .fetch_one(executor)
58        .await
59        .map_err(AwaError::from)
60}
61
62pub async fn prepare<'e, E>(
63    executor: E,
64    engine: &str,
65    details: serde_json::Value,
66) -> Result<StorageStatus, AwaError>
67where
68    E: PgExecutor<'e>,
69{
70    sqlx::query_as::<_, StorageStatus>("SELECT * FROM awa.storage_prepare($1, $2)")
71        .bind(engine)
72        .bind(details)
73        .fetch_one(executor)
74        .await
75        .map_err(AwaError::from)
76}
77
78pub async fn abort<'e, E>(executor: E) -> Result<StorageStatus, AwaError>
79where
80    E: PgExecutor<'e>,
81{
82    sqlx::query_as::<_, StorageStatus>("SELECT * FROM awa.storage_abort()")
83        .fetch_one(executor)
84        .await
85        .map_err(AwaError::from)
86}
87
88pub async fn enter_mixed_transition<'e, E>(executor: E) -> Result<StorageStatus, AwaError>
89where
90    E: PgExecutor<'e>,
91{
92    sqlx::query_as::<_, StorageStatus>("SELECT * FROM awa.storage_enter_mixed_transition()")
93        .fetch_one(executor)
94        .await
95        .map_err(AwaError::from)
96}
97
98pub async fn finalize<'e, E>(executor: E) -> Result<StorageStatus, AwaError>
99where
100    E: PgExecutor<'e>,
101{
102    sqlx::query_as::<_, StorageStatus>("SELECT * FROM awa.storage_finalize()")
103        .fetch_one(executor)
104        .await
105        .map_err(AwaError::from)
106}
107
108fn queue_storage_schema_from_status(status: &StorageStatus) -> Option<String> {
109    let queue_storage_involved = status.prepared_engine.as_deref() == Some("queue_storage")
110        || status.active_engine == "queue_storage";
111    if !queue_storage_involved {
112        return None;
113    }
114    Some(
115        status
116            .details
117            .get("schema")
118            .and_then(serde_json::Value::as_str)
119            .unwrap_or("awa")
120            .to_string(),
121    )
122}
123
124/// Returns true only when every queue-storage substrate object the
125/// runtime depends on is present. Workers and producers should treat
126/// `false` as "schema not installed yet" and either wait or trigger
127/// `QueueStorage::prepare_schema`.
128///
129/// The required objects (tables, the job-id sequence, the claim
130/// function and its exact signature) originate from the v023 SQL helper,
131/// called either by `awa migrate` for the default schema or by
132/// [`QueueStorage::prepare_schema`](crate::QueueStorage::prepare_schema)
133/// for custom schemas. If you change a required substrate object or the
134/// `claim_ready_runtime` signature there, update this check at the same
135/// time.
136pub async fn queue_storage_schema_ready(pool: &PgPool, schema: &str) -> Result<bool, AwaError> {
137    sqlx::query_scalar::<_, bool>(
138        r#"
139        SELECT
140            to_regclass(format('%I.%I', $1, 'job_id_seq')) IS NOT NULL
141            AND to_regclass(format('%I.%I', $1, 'queue_ring_state')) IS NOT NULL
142            AND to_regclass(format('%I.%I', $1, 'ready_entries')) IS NOT NULL
143            AND to_regclass(format('%I.%I', $1, 'ready_tombstones')) IS NOT NULL
144            AND to_regclass(format('%I.%I', $1, 'done_entries')) IS NOT NULL
145            AND to_regclass(format('%I.%I', $1, 'queue_terminal_count_deltas')) IS NOT NULL
146            AND to_regclass(format('%I.%I', $1, 'leases')) IS NOT NULL
147            AND to_regclass(format('%I.%I', $1, 'deferred_jobs')) IS NOT NULL
148            AND to_regclass(format('%I.%I', $1, 'lease_claims')) IS NOT NULL
149            AND to_regclass(format('%I.%I', $1, 'lease_claim_closures')) IS NOT NULL
150            AND to_regprocedure(
151                format('%I.%I(text,bigint,double precision,double precision)', $1, 'claim_ready_runtime')
152            ) IS NOT NULL
153        "#,
154    )
155    .bind(schema)
156    .fetch_one(pool)
157    .await
158    .map_err(AwaError::from)
159}
160
161async fn canonical_live_backlog(pool: &PgPool) -> Result<i64, AwaError> {
162    sqlx::query_scalar::<_, i64>(
163        r#"
164        SELECT
165            COALESCE((
166                SELECT count(*)::bigint
167                FROM awa.jobs_hot
168                WHERE state NOT IN ('completed', 'failed', 'cancelled')
169            ), 0)
170            +
171            COALESCE((
172                SELECT count(*)::bigint
173                FROM awa.scheduled_jobs
174            ), 0)
175        "#,
176    )
177    .fetch_one(pool)
178    .await
179    .map_err(AwaError::from)
180}
181
182pub async fn status_report(pool: &PgPool) -> Result<StorageStatusReport, AwaError> {
183    let status = status(pool).await?;
184    let canonical_live_backlog = canonical_live_backlog(pool).await?;
185    let prepared_queue_storage_schema = queue_storage_schema_from_status(&status);
186    let prepared_schema_ready = match prepared_queue_storage_schema.as_deref() {
187        Some(schema) => queue_storage_schema_ready(pool, schema).await?,
188        None => false,
189    };
190
191    let instances = admin::list_runtime_instances(pool).await?;
192    let mut live_runtime_capability_counts = BTreeMap::new();
193    let mut live_queue_storage_targets = 0usize;
194    for instance in instances.into_iter().filter(|instance| !instance.stale) {
195        *live_runtime_capability_counts
196            .entry(instance.storage_capability.as_str().to_string())
197            .or_insert(0) += 1;
198        if instance.transition_role == admin::TransitionRole::QueueStorageTarget
199            && instance.storage_capability == admin::StorageCapability::QueueStorage
200        {
201            live_queue_storage_targets += 1;
202        }
203    }
204
205    let live_canonical = *live_runtime_capability_counts
206        .get("canonical")
207        .unwrap_or(&0);
208    let live_drain = *live_runtime_capability_counts
209        .get("canonical_drain_only")
210        .unwrap_or(&0);
211
212    let mut enter_mixed_transition_blockers = Vec::new();
213    if status.state != "prepared" {
214        enter_mixed_transition_blockers
215            .push(format!("state is '{}' (expected 'prepared')", status.state));
216    }
217    if status.prepared_engine.as_deref() != Some("queue_storage") {
218        enter_mixed_transition_blockers.push(format!(
219            "prepared_engine is {:?} (expected Some(\"queue_storage\"))",
220            status.prepared_engine
221        ));
222    }
223    if prepared_queue_storage_schema.is_some() && !prepared_schema_ready {
224        enter_mixed_transition_blockers
225            .push("prepared queue-storage schema is missing required tables".to_string());
226    }
227    if live_canonical > 0 {
228        enter_mixed_transition_blockers.push(format!(
229            "{live_canonical} canonical-only runtime(s) are still live"
230        ));
231    }
232    if live_queue_storage_targets == 0 {
233        enter_mixed_transition_blockers.push(
234            "no live runtimes with transition_role=queue_storage_target are reporting; \
235             auto-role runtimes downgrade to drain-only after the routing flip"
236                .to_string(),
237        );
238    }
239
240    let mut finalize_blockers = Vec::new();
241    if status.state != "mixed_transition" {
242        finalize_blockers.push(format!(
243            "state is '{}' (expected 'mixed_transition')",
244            status.state
245        ));
246    }
247    if status.prepared_engine.as_deref() != Some("queue_storage") {
248        finalize_blockers.push(format!(
249            "prepared_engine is {:?} (expected Some(\"queue_storage\"))",
250            status.prepared_engine
251        ));
252    }
253    if canonical_live_backlog > 0 {
254        finalize_blockers.push(format!(
255            "canonical live backlog is {canonical_live_backlog}"
256        ));
257    }
258    if live_canonical + live_drain > 0 {
259        finalize_blockers.push(format!(
260            "{} canonical or drain-only runtime(s) are still live",
261            live_canonical + live_drain
262        ));
263    }
264
265    Ok(StorageStatusReport {
266        status,
267        canonical_live_backlog,
268        prepared_queue_storage_schema,
269        prepared_schema_ready,
270        live_runtime_capability_counts,
271        can_enter_mixed_transition: enter_mixed_transition_blockers.is_empty(),
272        enter_mixed_transition_blockers,
273        can_finalize: finalize_blockers.is_empty(),
274        finalize_blockers,
275        history: None,
276    })
277}