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