OXYGENHUB
# b6dfcb61cf5e oxygenhub / crates / hub / src / db / mod.rs
7.0 KiB · Rust · last changed Runner updates: policy, test groups and the offer 10 days ago source blame history raw
1
//! SQLite through `sqlx` (hub spec §3.1, §17.2): WAL, foreign keys on,
2
//! migrations embedded and applied at start; or PostgreSQL, built with the
3
//! `postgres` feature (#211). One module per table group.
4
5
pub mod accounts;
6
pub mod activity;
7
pub mod flow;
8
pub mod hooks;
9
pub mod issues;
10
pub mod notify;
11
pub mod projects;
12
pub mod proposals;
13
pub mod push_protection;
14
pub mod queue;
15
pub mod releases;
16
pub mod repos;
17
pub mod runner_updates;
18
pub mod runners;
19
pub mod sessions;
20
pub mod terraform;
21
pub mod tlog;
22
23
#[cfg(not(feature = "postgres"))]
24
pub use sqlite::{begin_write, open, Db};
25
26
#[cfg(feature = "postgres")]
27
pub use postgres::{begin_write, open, Db};
28
29
pub type Pool = sqlx::Pool<Db>;
30
31
#[cfg(not(feature = "postgres"))]
32
mod sqlite {
33
    use super::Pool;
34
    use crate::config::Config;
35
    use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous};
36
37
    pub type Db = sqlx::Sqlite;
38
39
    /// How long a statement waits for SQLite's write lock. Most writers are
40
    /// background clients (runners appending logs, webhook deliveries), and a
41
    /// commit can stall for seconds while a build saturates the host's disk, so
42
    /// waiting beats failing.
43
    const BUSY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
44
45
    /// Open (creating if needed) and migrate `<data>/hub.db`.
46
    pub async fn open(config: &Config) -> anyhow::Result<Pool> {
47
        let options = SqliteConnectOptions::new()
48
            .filename(config.db_path())
49
            .create_if_missing(true)
50
            .journal_mode(SqliteJournalMode::Wal)
51
            .synchronous(SqliteSynchronous::Normal)
52
            .foreign_keys(true)
53
            .busy_timeout(BUSY_TIMEOUT);
54
        migrate(options.clone()).await?;
55
        let pool = SqlitePoolOptions::new().max_connections(8).connect_with(options).await?;
56
        Ok(pool)
57
    }
58
59
    /// Apply the migrations on a connection of their own with foreign keys
60
    /// off, as SQLite's way to change a table (rebuild it, drop the old one,
61
    /// rename) needs: with them on, dropping a table its children reference
62
    /// deletes the children too. Every reference must hold afterwards.
63
    async fn migrate(options: SqliteConnectOptions) -> anyhow::Result<()> {
64
        use sqlx::Connection;
65
        let mut conn = sqlx::SqliteConnection::connect_with(&options.foreign_keys(false)).await?;
66
        sqlx::migrate!("./migrations").run(&mut conn).await?;
67
        let broken: Vec<(String,)> = sqlx::query_as("SELECT \"table\" FROM pragma_foreign_key_check").fetch_all(&mut conn).await?;
68
        if let Some((table,)) = broken.first() {
69
            anyhow::bail!("after the migrations, {} rows break a foreign key (the first in {table})", broken.len());
70
        }
71
        conn.close().await?;
72
        Ok(())
73
    }
74
75
    /// A write transaction that takes SQLite's write lock at `BEGIN`
76
    /// (`BEGIN IMMEDIATE`). A deferred transaction that reads and then writes
77
    /// fails at once with "database is locked" when another writer holds the
78
    /// lock, whatever the busy timeout; an immediate one waits its turn.
79
    pub async fn begin_write(pool: &Pool) -> sqlx::Result<sqlx::Transaction<'static, Db>> {
80
        pool.begin_with("BEGIN IMMEDIATE").await
81
    }
82
}
83
84
/// PostgreSQL (#211), for a hub on more than one host or a managed database.
85
/// The same queries as SQLite's; the schema is `migrations-pg`, which starts
86
/// as SQLite's 0001-0072 in one and takes each later change written for it.
87
#[cfg(feature = "postgres")]
88
mod postgres {
89
    use super::Pool;
90
    use crate::config::Config;
91
    use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
92
    use sqlx::Executor;
93
94
    pub type Db = sqlx::Postgres;
95
96
    /// Connect to `[database] url`, use its schema, and migrate.
97
    pub async fn open(config: &Config) -> anyhow::Result<Pool> {
98
        if config.database.url.is_empty() {
99
            anyhow::bail!("this hub is built for PostgreSQL: set [database] url (or OXYHUB_DATABASE_URL)");
100
        }
101
        let options: PgConnectOptions = config.database.url.parse()?;
102
        let schema = schema_name(config);
103
        if let Some(schema) = &schema {
104
            let pool = PgPoolOptions::new().max_connections(1).connect_with(options.clone()).await?;
105
            pool.execute(format!("CREATE SCHEMA IF NOT EXISTS \"{schema}\"").as_str()).await?;
106
            pool.close().await;
107
        }
108
        let path = match &schema {
109
            // Plain (letters, digits, `_`), so it needs no quoting here.
110
            Some(s) => format!("{s},public"),
111
            None => "public".to_string(),
112
        };
113
        let options = options.options([("search_path", path.as_str())]);
114
        let pool = PgPoolOptions::new().max_connections(16).connect_with(options).await?;
115
        extension(&pool).await?;
116
        sqlx::migrate!("./migrations-pg").run(&pool).await?;
117
        Ok(pool)
118
    }
119
120
    /// `citext`, for names compared without case, made once in `public` so
121
    /// every schema sees it. Two hubs starting at once may race to make it.
122
    async fn extension(pool: &Pool) -> anyhow::Result<()> {
123
        let made = pool.execute("CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public").await;
124
        if let Err(e) = made {
125
            let there: bool =
126
                sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'citext')").fetch_one(pool).await?;
127
            if !there {
128
                return Err(e.into());
129
            }
130
        }
131
        Ok(())
132
    }
133
134
    /// The schema to use: none for `public`; `*` names it after the data
135
    /// directory, so hubs (and tests) can share one database.
136
    fn schema_name(config: &Config) -> Option<String> {
137
        let s = match config.database.schema.as_str() {
138
            "" | "public" => return None,
139
            "*" => {
140
                let dir = config.data.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
141
                format!("hub_{dir}")
142
            }
143
            s => s.to_string(),
144
        };
145
        Some(s.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '_' }).collect())
146
    }
147
148
    /// One writer at a time, as SQLite's `BEGIN IMMEDIATE` gives: callers
149
    /// read and then write (the next number, a check before an insert) and
150
    /// rely on nothing changing between. A transaction-scoped advisory lock.
151
    pub async fn begin_write(pool: &Pool) -> sqlx::Result<sqlx::Transaction<'static, Db>> {
152
        let mut tx = pool.begin().await?;
153
        sqlx::query("SELECT pg_advisory_xact_lock(7300211)").execute(&mut *tx).await?;
154
        Ok(tx)
155
    }
156
}
157
158
/// SQL for the text at `key` of the JSON object in column `col` (null when
159
/// the column is empty or has no such key).
160
pub fn json_text(col: &str, key: &str) -> String {
161
    if cfg!(feature = "postgres") {
162
        format!("(CAST(NULLIF({col}, '') AS json) ->> '{key}')")
163
    } else {
164
        format!("json_extract({col}, '$.{key}')")
165
    }
166
}
167
168
/// Milliseconds since the epoch, the hub's timestamp unit (as `oxy`'s).
169
pub fn now_ms() -> i64 {
170
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0)
171
}