OXYGENHUB
# 1c4ad601ef9d oxygenhub / crates / hub / src / db / repos.rs
14.9 KiB · Rust · last changed Newest run wins: a proposal's new run supersedes its older ones 17 days ago source blame history raw
1
//! The `repositories` and `pushes` tables.
2
3
use super::{now_ms, Pool};
4
use hub_api::Visibility;
5
use sqlx::FromRow;
6
7
#[derive(Clone, Debug, Default, FromRow)]
8
pub struct RepoRow {
9
    pub id: i64,
10
    pub owner: String,
11
    pub name: String,
12
    pub description: String,
13
    pub default_bookmark: String,
14
    pub visibility: String,
15
    pub created_ms: i64,
16
    pub updated_ms: i64,
17
    #[sqlx(default)]
18
    pub git_mirror: bool,
19
    #[sqlx(default)]
20
    pub git_mirror_state: String,
21
    /// The repository this one was forked from (migration 0009).
22
    #[sqlx(default)]
23
    pub forked_from: Option<i64>,
24
    /// Space-separated topics (migration 0010).
25
    #[sqlx(default)]
26
    pub topics: String,
27
    /// OxygenFlow: `on`, `off`, or empty to follow hub.toml (migration 0018).
28
    #[sqlx(default)]
29
    pub flow: String,
30
    /// Its jobs' priority: `low`, `normal`, `high`, or empty to follow its
31
    /// organisation's and the site's (oxygenhub#244, migration 0073).
32
    #[sqlx(default)]
33
    pub flow_priority: String,
34
    /// Diffusion: `off`, `green`, `any`, or empty to follow hub.toml
35
    /// (migration 0058, #148).
36
    #[sqlx(default)]
37
    pub diffusion: String,
38
    /// Diffusion auto-land: `auto`, `propose`, or empty for propose
39
    /// (migration 0061).
40
    #[sqlx(default)]
41
    pub diffusion_land: String,
42
    /// Backups (migration 0062): empty with its owner's, `off`, or its own
43
    /// `hourly` or `daily`.
44
    #[sqlx(default)]
45
    pub backup: String,
46
    /// Read-only, with why (migration 0040, #108).
47
    #[sqlx(default)]
48
    pub archived: bool,
49
    #[sqlx(default)]
50
    pub archived_reason: String,
51
    /// Agents' tokens may approve or reject its approval gates (#258).
52
    #[sqlx(default)]
53
    pub agents_decide_gates: bool,
54
    /// Newest run wins (#267): a superseded run already running finishes;
55
    /// only queued ones are cancelled. Off by default.
56
    #[sqlx(default)]
57
    pub flow_keep_running: bool,
58
    /// Counts for the tabs; filled by `get` only.
59
    #[sqlx(default)]
60
    pub open_issues: i64,
61
    #[sqlx(default)]
62
    pub open_proposals: i64,
63
}
64
65
impl RepoRow {
66
    pub fn visibility(&self) -> Visibility {
67
        Visibility::parse(&self.visibility).unwrap_or(Visibility::Private)
68
    }
69
70
    pub fn topic_list(&self) -> Vec<&str> {
71
        self.topics.split_whitespace().collect()
72
    }
73
74
    pub fn slug(&self) -> String {
75
        format!("{}/{}", self.owner, self.name)
76
    }
77
}
78
79
#[derive(Clone, Debug, FromRow)]
80
pub struct PushRow {
81
    pub id: i64,
82
    pub at_ms: i64,
83
    pub reference: String,
84
    pub ok: bool,
85
    pub reason: String,
86
    pub old_state: String,
87
    pub new_state: String,
88
    pub heads: i64,
89
    pub changes: i64,
90
    pub pusher: String,
91
}
92
93
/// One reference's outcome in a push, as the protocol backend reports it.
94
#[derive(Clone, Debug)]
95
pub struct PushOutcome {
96
    pub reference: String,
97
    pub ok: bool,
98
    pub reason: String,
99
    pub old_state: String,
100
    pub new_state: String,
101
    pub heads: i64,
102
    pub changes: i64,
103
}
104
105
pub async fn list(pool: &Pool) -> sqlx::Result<Vec<RepoRow>> {
106
    sqlx::query_as("SELECT * FROM repositories ORDER BY updated_ms DESC, owner, name").fetch_all(pool).await
107
}
108
109
pub async fn get_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<RepoRow>> {
110
    sqlx::query_as("SELECT * FROM repositories WHERE id = $1").bind(id).fetch_optional(pool).await
111
}
112
113
pub async fn list_by_owner(pool: &Pool, owner: &str) -> sqlx::Result<Vec<RepoRow>> {
114
    sqlx::query_as("SELECT * FROM repositories WHERE owner = $1 ORDER BY updated_ms DESC, name").bind(owner).fetch_all(pool).await
115
}
116
117
/// One repository, with its open issue and proposal counts for the tabs.
118
pub async fn get(pool: &Pool, owner: &str, name: &str) -> sqlx::Result<Option<RepoRow>> {
119
    sqlx::query_as(
120
        "SELECT r.*, \
121
           (SELECT COUNT(*) FROM issues i WHERE i.repo_id = r.id AND i.state = 'open') AS open_issues, \
122
           (SELECT COUNT(*) FROM proposals p WHERE p.repo_id = r.id AND p.state IN ('open', 'draft')) AS open_proposals \
123
         FROM repositories r WHERE r.owner = $1 AND r.name = $2",
124
    )
125
    .bind(owner)
126
    .bind(name)
127
    .fetch_optional(pool)
128
    .await
129
}
130
131
/// Create a repository row. One under an organisation of two or more
132
/// members requires one sealed approval to land a proposal (oxygenhub#64),
133
/// since someone other than the author can then give it; others require none.
134
pub async fn create(pool: &Pool, owner: &str, name: &str, description: &str, visibility: Visibility) -> sqlx::Result<RepoRow> {
135
    let now = now_ms();
136
    sqlx::query_as(
137
        "INSERT INTO repositories (owner, name, description, visibility, created_ms, updated_ms, required_approvals) \
138
         VALUES ($1, $2, $3, $4, $5, $6, (SELECT CASE WHEN COUNT(*) >= 2 THEN 1 ELSE 0 END FROM org_members m JOIN organisations o ON o.id = m.org_id WHERE o.name = $7)) RETURNING *",
139
    )
140
    .bind(owner)
141
    .bind(name)
142
    .bind(description)
143
    .bind(visibility.as_str())
144
    .bind(now)
145
    .bind(now)
146
    .bind(owner)
147
    .fetch_one(pool)
148
    .await
149
}
150
151
/// The repository an old name now points at, after a transfer.
152
pub async fn moved_to(pool: &Pool, owner: &str, name: &str) -> sqlx::Result<Option<RepoRow>> {
153
    let id: Option<i64> = sqlx::query_scalar("SELECT repo_id FROM repo_redirects WHERE old_owner = $1 AND old_name = $2")
154
        .bind(owner)
155
        .bind(name)
156
        .fetch_optional(pool)
157
        .await?;
158
    match id {
159
        Some(id) => get_by_id(pool, id).await,
160
        None => Ok(None),
161
    }
162
}
163
164
/// Move a repository to another owner, keeping its name: the row, and a
165
/// redirect from the old name. A redirect that pointed at the new name
166
/// goes, so names never loop.
167
pub async fn transfer(pool: &Pool, id: i64, old_owner: &str, name: &str, new_owner: &str) -> sqlx::Result<()> {
168
    sqlx::query("UPDATE repositories SET owner = $1, updated_ms = $2 WHERE id = $3")
169
        .bind(new_owner)
170
        .bind(now_ms())
171
        .bind(id)
172
        .execute(pool)
173
        .await?;
174
    sqlx::query("DELETE FROM repo_redirects WHERE old_owner = $1 AND old_name = $2").bind(new_owner).bind(name).execute(pool).await?;
175
    sqlx::query("INSERT OR REPLACE INTO repo_redirects (old_owner, old_name, repo_id, moved_ms) VALUES ($1, $2, $3, $4)")
176
        .bind(old_owner)
177
        .bind(name)
178
        .bind(id)
179
        .bind(now_ms())
180
        .execute(pool)
181
        .await?;
182
    Ok(())
183
}
184
185
/// Archive (read-only) or bring back a repository.
186
pub async fn set_archived(pool: &Pool, id: i64, archived: bool, reason: &str) -> sqlx::Result<()> {
187
    sqlx::query("UPDATE repositories SET archived = $1, archived_reason = $2, updated_ms = $3 WHERE id = $4")
188
        .bind(archived)
189
        .bind(if archived { reason } else { "" })
190
        .bind(now_ms())
191
        .bind(id)
192
        .execute(pool)
193
        .await?;
194
    Ok(())
195
}
196
197
pub async fn delete(pool: &Pool, id: i64) -> sqlx::Result<()> {
198
    sqlx::query("DELETE FROM repositories WHERE id = $1").bind(id).execute(pool).await?;
199
    Ok(())
200
}
201
202
pub async fn set_description(pool: &Pool, id: i64, description: &str) -> sqlx::Result<()> {
203
    sqlx::query("UPDATE repositories SET description = $1 WHERE id = $2").bind(description).bind(id).execute(pool).await?;
204
    Ok(())
205
}
206
207
pub async fn set_default_bookmark(pool: &Pool, id: i64, bookmark: &str) -> sqlx::Result<()> {
208
    sqlx::query("UPDATE repositories SET default_bookmark = $1 WHERE id = $2").bind(bookmark).bind(id).execute(pool).await?;
209
    Ok(())
210
}
211
212
pub async fn set_visibility(pool: &Pool, id: i64, visibility: Visibility) -> sqlx::Result<()> {
213
    sqlx::query("UPDATE repositories SET visibility = $1 WHERE id = $2").bind(visibility.as_str()).bind(id).execute(pool).await?;
214
    Ok(())
215
}
216
217
/// Record a push's per-reference results and bump the repository's activity.
218
pub async fn record_push(pool: &Pool, id: i64, pusher: Option<(i64, &str)>, results: &[PushOutcome]) -> sqlx::Result<()> {
219
    record_push_via(pool, id, pusher, "", results).await
220
}
221
222
/// [`record_push`], naming the agent token the push came through (#217).
223
pub async fn record_push_via(pool: &Pool, id: i64, pusher: Option<(i64, &str)>, via: &str, results: &[PushOutcome]) -> sqlx::Result<()> {
224
    let now = now_ms();
225
    let mut tx = super::begin_write(pool).await?;
226
    for r in results {
227
        sqlx::query("INSERT INTO pushes (repo_id, at_ms, reference, ok, reason, old_state, new_state, heads, changes, account_id, pusher, via) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)")
228
            .bind(id)
229
            .bind(now)
230
            .bind(&r.reference)
231
            .bind(r.ok)
232
            .bind(&r.reason)
233
            .bind(&r.old_state)
234
            .bind(&r.new_state)
235
            .bind(r.heads)
236
            .bind(r.changes)
237
            .bind(pusher.map(|p| p.0).filter(|id| *id > 0))
238
            .bind(pusher.map(|p| p.1).unwrap_or(""))
239
            .bind(via)
240
            .execute(&mut *tx)
241
            .await?;
242
    }
243
    if results.iter().any(|r| r.ok) {
244
        sqlx::query("UPDATE repositories SET updated_ms = $1 WHERE id = $2").bind(now).bind(id).execute(&mut *tx).await?;
245
    }
246
    tx.commit().await
247
}
248
249
pub async fn pushes(pool: &Pool, id: i64, limit: i64) -> sqlx::Result<Vec<PushRow>> {
250
    sqlx::query_as("SELECT id, at_ms, reference, ok, reason, old_state, new_state, heads, changes, pusher FROM pushes WHERE repo_id = $1 ORDER BY at_ms DESC, id DESC LIMIT $2")
251
        .bind(id)
252
        .bind(limit)
253
        .fetch_all(pool)
254
        .await
255
}
256
257
/// Topics from user input: comma or space separated, lower-cased,
258
/// letters, digits and dashes, at most 35 characters each and 20 in all.
259
/// Returns the stored form or what is wrong.
260
pub fn parse_topics(input: &str) -> Result<String, String> {
261
    let mut out: Vec<String> = Vec::new();
262
    for t in input.split([',', ' ', '\n', '\t']).map(|t| t.trim().to_ascii_lowercase()).filter(|t| !t.is_empty()) {
263
        if t.len() > 35 || !t.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') || t.starts_with('-') {
264
            return Err(format!("\"{t}\" is not a topic: use letters, digits and dashes, up to 35 characters"));
265
        }
266
        if !out.contains(&t) {
267
            out.push(t);
268
        }
269
    }
270
    if out.len() > 20 {
271
        return Err("At most 20 topics.".into());
272
    }
273
    Ok(out.join(" "))
274
}
275
276
pub async fn set_topics(pool: &Pool, id: i64, topics: &str) -> sqlx::Result<()> {
277
    sqlx::query("UPDATE repositories SET topics = $1 WHERE id = $2").bind(topics).bind(id).execute(pool).await?;
278
    Ok(())
279
}
280
281
/// Star or unstar; returns whether it is now starred.
282
pub async fn toggle_star(pool: &Pool, account_id: i64, repo_id: i64) -> sqlx::Result<bool> {
283
    let gone = sqlx::query("DELETE FROM stars WHERE account_id = $1 AND repo_id = $2").bind(account_id).bind(repo_id).execute(pool).await?;
284
    if gone.rows_affected() > 0 {
285
        return Ok(false);
286
    }
287
    sqlx::query("INSERT INTO stars (account_id, repo_id, at_ms) VALUES ($1, $2, $3)")
288
        .bind(account_id)
289
        .bind(repo_id)
290
        .bind(now_ms())
291
        .execute(pool)
292
        .await?;
293
    Ok(true)
294
}
295
296
pub async fn starred(pool: &Pool, account_id: i64, repo_id: i64) -> sqlx::Result<bool> {
297
    let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stars WHERE account_id = $1 AND repo_id = $2")
298
        .bind(account_id)
299
        .bind(repo_id)
300
        .fetch_one(pool)
301
        .await?;
302
    Ok(n > 0)
303
}
304
305
/// Stars and watchers of one repository.
306
pub async fn counts(pool: &Pool, repo_id: i64) -> sqlx::Result<(i64, i64)> {
307
    let stars: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM stars WHERE repo_id = $1").bind(repo_id).fetch_one(pool).await?;
308
    let watchers = super::notify::watchers(pool, repo_id).await?.len() as i64;
309
    Ok((stars, watchers))
310
}
311
312
/// Star counts of every starred repository.
313
pub async fn star_counts(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
314
    let rows: Vec<(i64, i64)> = sqlx::query_as("SELECT repo_id, COUNT(*) FROM stars GROUP BY repo_id").fetch_all(pool).await?;
315
    Ok(rows.into_iter().collect())
316
}
317
318
/// Record that `id` is a fork of `from`.
319
pub async fn set_forked_from(pool: &Pool, id: i64, from: i64) -> sqlx::Result<()> {
320
    sqlx::query("UPDATE repositories SET forked_from = $1 WHERE id = $2").bind(from).bind(id).execute(pool).await?;
321
    Ok(())
322
}
323
324
/// The forks of `id`, newest activity first.
325
pub async fn forks_of(pool: &Pool, id: i64) -> sqlx::Result<Vec<RepoRow>> {
326
    sqlx::query_as("SELECT * FROM repositories WHERE forked_from = $1 ORDER BY updated_ms DESC").bind(id).fetch_all(pool).await
327
}
328
329
/// `on`, `off`, or `` (follow hub.toml's `[flow] repos`).
330
pub async fn set_flow(pool: &Pool, id: i64, setting: &str) -> sqlx::Result<()> {
331
    sqlx::query("UPDATE repositories SET flow = $1 WHERE id = $2").bind(setting).bind(id).execute(pool).await?;
332
    Ok(())
333
}
334
335
pub async fn set_flow_priority(pool: &Pool, id: i64, priority: &str) -> sqlx::Result<()> {
336
    sqlx::query("UPDATE repositories SET flow_priority = $1 WHERE id = $2").bind(priority).bind(id).execute(pool).await?;
337
    Ok(())
338
}
339
340
/// Whether agents' tokens may decide the repository's approval gates (#258).
341
pub async fn set_agents_decide_gates(pool: &Pool, id: i64, on: bool) -> sqlx::Result<()> {
342
    sqlx::query("UPDATE repositories SET agents_decide_gates = $1 WHERE id = $2").bind(on).bind(id).execute(pool).await?;
343
    Ok(())
344
}
345
346
/// Whether a new run leaves the older runs it supersedes that are already
347
/// running to finish (#267), cancelling only the queued ones.
348
pub async fn set_flow_keep_running(pool: &Pool, id: i64, on: bool) -> sqlx::Result<()> {
349
    sqlx::query("UPDATE repositories SET flow_keep_running = $1 WHERE id = $2").bind(on).bind(id).execute(pool).await?;
350
    Ok(())
351
}
352
353
pub async fn set_backup(pool: &Pool, id: i64, setting: &str) -> sqlx::Result<()> {
354
    sqlx::query("UPDATE repositories SET backup = $1 WHERE id = $2").bind(setting).bind(id).execute(pool).await?;
355
    Ok(())
356
}
357
358
pub async fn set_diffusion_land(pool: &Pool, id: i64, setting: &str) -> sqlx::Result<()> {
359
    sqlx::query("UPDATE repositories SET diffusion_land = $1 WHERE id = $2").bind(setting).bind(id).execute(pool).await?;
360
    Ok(())
361
}
362
363
pub async fn set_diffusion(pool: &Pool, id: i64, setting: &str) -> sqlx::Result<()> {
364
    sqlx::query("UPDATE repositories SET diffusion = $1 WHERE id = $2").bind(setting).bind(id).execute(pool).await?;
365
    Ok(())
366
}
367
368
pub async fn set_git_mirror(pool: &Pool, id: i64, on: bool) -> sqlx::Result<()> {
369
    sqlx::query("UPDATE repositories SET git_mirror = $1 WHERE id = $2").bind(on).bind(id).execute(pool).await?;
370
    Ok(())
371
}
372
373
pub async fn set_git_mirror_state(pool: &Pool, id: i64, state: &str) -> sqlx::Result<()> {
374
    sqlx::query("UPDATE repositories SET git_mirror_state = $1 WHERE id = $2").bind(state).bind(id).execute(pool).await?;
375
    Ok(())
376
}
377
378
#[cfg(test)]
379
mod topic_tests {
380
    use super::parse_topics;
381
382
    #[test]
383
    fn topics_are_normalised_and_checked() {
384
        assert_eq!(parse_topics("Rust, vcs  retro-computing,rust").unwrap(), "rust vcs retro-computing");
385
        assert_eq!(parse_topics("").unwrap(), "");
386
        assert!(parse_topics("c++").is_err());
387
        assert!(parse_topics("-lead").is_err());
388
        assert!(parse_topics(&"x".repeat(36)).is_err());
389
        assert!(parse_topics(&(0..21).map(|i| format!("t{i}")).collect::<Vec<_>>().join(" ")).is_err());
390
    }
391
}