Skip to main content

orch/store/
jobs.rs

1/// The SQL behind each replicated job and channel write
2pub(crate) mod apply;
3
4use super::TaskStore;
5use crate::store::Command;
6use serde::{Deserialize, Serialize};
7use sqlx::SqliteConnection;
8#[cfg(test)]
9use std::sync::atomic::Ordering;
10
11/// Explicit column list for `SELECT` queries on the `job_state` table.
12///
13/// Using `SELECT *` with `sqlx-sqlite`'s prepared statement cache can cause OOB
14/// panics when the schema changes (new migration columns) because the cached
15/// column metadata may not match the current table structure. Explicit columns
16/// prevent this mismatch.
17const JOB_STATE_COLS: &str = "repo, job_id, last_run, last_task_status, active_task_id";
18
19/// Runtime state for a scheduled job, stored in SQLite (not in .orch.yml).
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, sqlx::FromRow)]
21pub struct JobState {
22    pub repo: String,
23    pub job_id: String,
24    pub last_run: Option<String>,
25    pub last_task_status: Option<String>,
26    pub active_task_id: Option<String>,
27}
28
29impl JobState {
30    /// State for a job that has never run.
31    pub fn new(repo: &str, job_id: &str) -> Self {
32        Self {
33            repo: repo.to_string(),
34            job_id: job_id.to_string(),
35            last_run: None,
36            last_task_status: None,
37            active_task_id: None,
38        }
39    }
40}
41
42impl TaskStore {
43    pub async fn get_job_state(
44        &self,
45        repo: &str,
46        job_id: &str,
47    ) -> anyhow::Result<Option<JobState>> {
48        let sql = format!("SELECT {JOB_STATE_COLS} FROM job_state WHERE repo = ? AND job_id = ?");
49        let row: Option<JobState> = sqlx::query_as(sqlx::AssertSqlSafe(sql.as_str()))
50            .bind(repo)
51            .bind(job_id)
52            .fetch_optional(&self.pool)
53            .await?;
54        Ok(row)
55    }
56
57    #[cfg(test)]
58    pub fn fail_next_job_state_writes(&self, n: u32) {
59        self.fail_job_state_writes.store(n, Ordering::SeqCst);
60    }
61
62    /// Upsert runtime state for a job.
63    pub async fn upsert_job_state(&self, state: &JobState) -> anyhow::Result<()> {
64        #[cfg(test)]
65        if state.active_task_id.is_some() {
66            let n = self.fail_job_state_writes.load(Ordering::SeqCst);
67            if n > 0 {
68                self.fail_job_state_writes.store(n - 1, Ordering::SeqCst);
69                anyhow::bail!("injected job state write failure");
70            }
71        }
72        self.write(Command::JobStateUpsert(state.clone()))
73            .await
74            .map(|_| ())
75    }
76
77    /// List all job states for a repo.
78    pub async fn list_job_states(&self, repo: &str) -> anyhow::Result<Vec<JobState>> {
79        let sql = format!("SELECT {JOB_STATE_COLS} FROM job_state WHERE repo = ?");
80        let rows: Vec<JobState> = sqlx::query_as(sqlx::AssertSqlSafe(sql.as_str()))
81            .bind(repo)
82            .fetch_all(&self.pool)
83            .await?;
84        Ok(rows)
85    }
86
87    // ---------------------------------------------------------------
88    // Channel Subscriptions
89    // ---------------------------------------------------------------
90
91    /// Subscribe a channel/thread to notifications for a project.
92    pub async fn subscribe_channel(
93        &self,
94        channel: &str,
95        thread_id: &str,
96        repo: &str,
97        topic_id: Option<&str>,
98    ) -> anyhow::Result<()> {
99        let cmd = Command::ChannelSubscribe {
100            channel: channel.to_string(),
101            thread_id: thread_id.to_string(),
102            repo: repo.to_string(),
103            topic_id: topic_id.unwrap_or("").to_string(),
104        };
105        self.write(cmd).await.map(|_| ())
106    }
107
108    /// Unsubscribe a channel/thread from a project's notifications.
109    pub async fn unsubscribe_channel(
110        &self,
111        channel: &str,
112        thread_id: &str,
113        repo: &str,
114    ) -> anyhow::Result<()> {
115        let cmd = Command::ChannelUnsubscribe {
116            channel: channel.to_string(),
117            thread_id: thread_id.to_string(),
118            repo: repo.to_string(),
119        };
120        self.write(cmd).await.map(|_| ())
121    }
122
123    /// List repos that a channel/thread is subscribed to.
124    #[cfg(test)]
125    pub async fn list_channel_subscriptions(
126        &self,
127        channel: &str,
128        thread_id: &str,
129    ) -> anyhow::Result<Vec<String>> {
130        let rows: Vec<(String,)> = sqlx::query_as(
131            "SELECT repo FROM channel_subscriptions WHERE channel = ? AND thread_id = ?",
132        )
133        .bind(channel)
134        .bind(thread_id)
135        .fetch_all(&self.pool)
136        .await?;
137        Ok(rows.into_iter().map(|r| r.0).collect())
138    }
139
140    /// List all subscriptions (channel, thread_id, topic_id) for a repo.
141    pub async fn list_subscribers_for_repo(
142        &self,
143        repo: &str,
144    ) -> anyhow::Result<Vec<(String, String, String)>> {
145        let rows: Vec<(String, String, String)> = sqlx::query_as(
146            "SELECT channel, thread_id, topic_id FROM channel_subscriptions WHERE repo = ?",
147        )
148        .bind(repo)
149        .fetch_all(&self.pool)
150        .await?;
151        Ok(rows)
152    }
153}