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