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