summaryrefslogtreecommitdiffstats
path: root/src/db/candidates.rs
blob: 63c089fb1a26b79e780c0b6a36e373ff367d4d60 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! The candidate table: its row shape, its column list, and every statement
//! that touches it (§7.1).
//!
//! The *rules* about candidates — collapse into the open review, supersede once
//! a human has looked, never re-raise a rejection — are domain logic and live
//! in `review::candidates`. What lives here is SQL, so that the schema has one
//! owner (§6 M-1). The `_in` functions take a transaction handle so a caller
//! can compose several of them into one atomic decision; the decision itself
//! stays with the caller.

use rusqlite::{params, OptionalExtension, Row, Transaction};

use crate::db::{CandidateRow, CandidateState, Db};
use crate::error::{Error, Result};
use crate::time;

/// The columns `row_to_candidate` reads, spelled once. Every other table in
/// this module already works this way; the candidate select was simply copied
/// four times for long enough to be noticed (§6 m-3).
const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \
     c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, c.diff_digest, \
     c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, c.missing_deps_json, c.state, \
     c.detected_at, c.resolved_at, b.name";

fn row_to_candidate(r: &Row<'_>) -> rusqlite::Result<CandidateRow> {
    Ok(CandidateRow {
        id: r.get(0)?,
        pkgbase_id: r.get(1)?,
        base_release_id: r.get(2)?,
        kind: r.get(3)?,
        snapshot_id: r.get(4)?,
        epoch: r.get(5)?,
        pkgver: r.get(6)?,
        pkgrel: r.get(7)?,
        upstream_pins_json: r.get(8)?,
        source_digests_json: r.get(9)?,
        identity_hash: r.get(10)?,
        diff_digest: r.get(11)?,
        revision: r.get(12)?,
        viewed_at: r.get(13)?,
        risk_level: r.get(14)?,
        risk_signals_json: r.get(15)?,
        missing_deps_json: r.get(16)?,
        state: crate::db::state_col::<CandidateState>(17, &r.get::<_, String>(17)?)?,
        detected_at: r.get(18)?,
        resolved_at: r.get(19)?,
        pkgbase: r.get(20)?,
    })
}

/// The fields a new candidate row carries, beyond its pkgbase and its base.
#[derive(Debug, Clone)]
pub struct NewCandidate {
    pub snapshot_id: i64,
    pub epoch: String,
    pub pkgver: String,
    pub pkgrel: String,
    pub upstream_pins_json: String,
    pub source_digests_json: String,
    pub identity_hash: String,
}

impl NewCandidate {
    /// The `epoch:pkgver-pkgrel` this candidate would publish.
    pub fn version(&self) -> String {
        crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
    }
}

/// The open review of a pkgbase — as much of it as the collapse rules need.
#[derive(Debug, Clone)]
pub struct OpenReview {
    pub id: i64,
    pub identity_hash: String,
    pub viewed_at: Option<String>,
    pub revision: i64,
}

impl OpenReview {
    /// Has a human opened this review yet? That timestamp is what decides
    /// whether a newer detection collapses or supersedes (§7.1).
    pub fn viewed(&self) -> bool {
        self.viewed_at.is_some()
    }
}

// ------------------------------------------------------------------ in-tx --

/// Everything the approval gate has to look at to decide, read in one statement
/// so the check cannot straddle two snapshots of the database.
#[derive(Debug, Clone)]
pub struct ReviewSubject {
    pub id: i64,
    pub pkgbase_id: i64,
    pub state: CandidateState,
    pub identity_hash: String,
    pub diff_digest: String,
    /// The release this review was opened against (I2).
    pub base_release_id: Option<i64>,
    /// What the pkgbase accepts now — the other half of the I2 check.
    pub current_base_release_id: Option<i64>,
    pub risk_level: String,
    pub pkgbase: String,
}

pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Option<ReviewSubject>> {
    Ok(tx
        .query_row(
            "SELECT c.id, c.pkgbase_id, c.state, c.identity_hash, c.diff_digest, c.base_release_id,
                    p.current_accepted_release_id, c.risk_level, p.name
             FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id
             WHERE c.id = ?1",
            params![candidate_id],
            |r| {
                Ok(ReviewSubject {
                    id: r.get(0)?,
                    pkgbase_id: r.get(1)?,
                    state: crate::db::state_col::<CandidateState>(2, &r.get::<_, String>(2)?)?,
                    identity_hash: r.get(3)?,
                    diff_digest: r.get(4)?,
                    base_release_id: r.get(5)?,
                    current_base_release_id: r.get(6)?,
                    risk_level: r.get(7)?,
                    pkgbase: r.get(8)?,
                })
            },
        )
        .optional()?)
}

/// Take a candidate out of the open state: approved, rejected or superseded.
///
/// The write is a compare-and-swap on [`CandidateState`]: a decided review is
/// never re-decided, so an approval racing a rejection — or a stale worker
/// resolving a review that has since been superseded — fails instead of
/// silently overwriting what a human did.
pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> {
    let froms = CandidateState::predecessors(to);
    let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(",");
    let sql = format!(
        "UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3 AND state IN ({placeholders})"
    );
    let state = to.as_str();
    let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &at, &id];
    for f in &froms {
        args.push(f);
    }
    let n = tx.execute(&sql, rusqlite::params_from_iter(args))?;
    if n == 0 {
        let was: Option<String> = tx
            .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get(0))
            .optional()?;
        return Err(match was {
            Some(w) => Error::conflict(format!("illegal candidate transition {w} → {to} for review {id}")),
            None => Error::not_found(format!("no candidate {id} to resolve")),
        });
    }
    Ok(())
}

/// A candidate's state, read inside a transaction (the reject path needs it
/// before it writes).
pub fn state_in(tx: &Transaction<'_>, id: i64) -> Result<Option<CandidateState>> {
    Ok(tx
        .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| {
            crate::db::state_col::<CandidateState>(0, &r.get::<_, String>(0)?)
        })
        .optional()?)
}

pub fn identity_in(tx: &Transaction<'_>, id: i64) -> Result<Option<String>> {
    Ok(tx
        .query_row("SELECT identity_hash FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0))
        .optional()?)
}

/// The risk level recorded at review time, if the candidate exists.
pub fn risk_level(db: &Db, id: i64) -> Result<Option<String>> {
    db.read(|c| {
        Ok(c.query_row("SELECT risk_level FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0))
            .optional()?)
    })
}

/// The pkgbase's open review, if it has one (I7: at most one).
pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenReview>> {
    Ok(tx
        .query_row(
            "SELECT id, identity_hash, viewed_at, revision FROM candidate
             WHERE pkgbase_id=?1 AND state='pending_review'",
            params![pkgbase_id],
            |r| {
                Ok(OpenReview {
                    id: r.get(0)?,
                    identity_hash: r.get(1)?,
                    viewed_at: r.get(2)?,
                    revision: r.get(3)?,
                })
            },
        )
        .optional()?)
}

/// Write a newer detection into the open review: same row, same base, one more
/// revision, and the stale diff rendering dropped so it cannot be approved.
pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidate) -> Result<i64> {
    let revision = open.revision + 1;
    tx.execute(
        "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4,
            upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7,
            revision=?8, detected_at=?9, diff_digest=''
         WHERE id=?10",
        params![
            nc.snapshot_id,
            nc.epoch,
            nc.pkgver,
            nc.pkgrel,
            nc.upstream_pins_json,
            nc.source_digests_json,
            nc.identity_hash,
            revision,
            time::now(),
            open.id
        ],
    )?;
    Ok(revision)
}

/// Freeze a reviewed candidate as `superseded` so a fresh review can open.
pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> {
    let at = time::now();
    resolve_in(tx, id, CandidateState::Superseded, &at)
}

/// Has this exact identity been rejected before? If so the watcher stays quiet
/// until a human re-opens it (§7.1: "do not nag").
pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> {
    Ok(tx
        .query_row(
            "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected'
             ORDER BY id DESC LIMIT 1",
            params![pkgbase_id, identity_hash],
            |r| r.get::<_, i64>(0),
        )
        .optional()?
        .is_some())
}

/// Has this identity been recorded at all — approved, superseded, anything?
/// Then the detection said nothing new.
pub fn recorded_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> {
    Ok(tx
        .query_row(
            "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2
             ORDER BY id DESC LIMIT 1",
            params![pkgbase_id, identity_hash],
            |r| r.get::<_, i64>(0),
        )
        .optional()?
        .is_some())
}

/// Open a candidate row in `pending_review`.
pub fn insert_in(
    tx: &mut Transaction<'_>,
    pkgbase_id: i64,
    base: Option<i64>,
    kind: &str,
    nc: &NewCandidate,
) -> Result<i64> {
    tx.execute(
        "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel,
                                upstream_pins_json, source_digests_json, identity_hash, state, detected_at)
         VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)",
        params![
            pkgbase_id,
            base,
            kind,
            nc.snapshot_id,
            nc.epoch,
            nc.pkgver,
            nc.pkgrel,
            nc.upstream_pins_json,
            nc.source_digests_json,
            nc.identity_hash,
            time::now()
        ],
    )?;
    Ok(tx.last_insert_rowid())
}

// ------------------------------------------------------------------ reads --

/// Every candidate regardless of state, newest first (`aur-build reviews --all`).
pub fn all(db: &Db) -> Result<Vec<CandidateRow>> {
    let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id ORDER BY c.detected_at DESC LIMIT 500");
    db.read(move |c| {
        let mut stmt = c.prepare(&sql)?;
        let rows = stmt.query_map([], row_to_candidate)?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r?);
        }
        Ok(out)
    })
}

/// The reviews waiting for a decision, riskiest first.
pub fn pending(db: &Db) -> Result<Vec<CandidateRow>> {
    let sql = format!(
        "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \
         WHERE c.state='pending_review' ORDER BY (c.risk_level='high') DESC, c.detected_at"
    );
    db.read(move |c| {
        let mut stmt = c.prepare(&sql)?;
        let rows = stmt.query_map([], row_to_candidate)?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r?);
        }
        Ok(out)
    })
}

pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
    let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1");
    db.read(move |c| {
        Ok(c.query_row(&sql, params![id], row_to_candidate)
            .optional()?)
    })
}

/// Open reviews for a pkgbase (usually zero or one, by I7).
pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> {
    let sql = format!(
        "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \
         WHERE c.pkgbase_id=?1 AND c.state='pending_review'"
    );
    db.read(move |c| {
        let mut stmt = c.prepare(&sql)?;
        let rows = stmt.query_map(params![pkgbase_id], row_to_candidate)?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r?);
        }
        Ok(out)
    })
}

// ---------------------------------------------------------------- writes --

/// Mark a candidate `viewed` the first time a human opens it. That timestamp is
/// what decides whether a later detection collapses or supersedes (§7.1).
pub fn mark_viewed(db: &Db, id: i64) -> Result<()> {
    let at = time::now();
    db.writer.tx(move |tx| {
        tx.execute(
            "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL",
            params![at, id],
        )?;
        Ok(())
    })
}

/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops
/// suppressing the identity, and the next detection opens a fresh review.
pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> {
    let at = time::now();
    db.writer.tx(move |tx| {
        let n = tx.execute(
            "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'",
            params![at, id],
        )?;
        if n == 0 {
            return Err(Error::conflict("candidate is not rejected"));
        }
        Ok(())
    })
}

/// Record the risk assessment computed at review time.
pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> {
    let lvl = level.to_string();
    let sig = serde_json::to_string(signals)?;
    db.writer.tx(move |tx| {
        tx.execute(
            "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3",
            params![lvl, sig, id],
        )?;
        Ok(())
    })
}

pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> {
    let m = serde_json::to_string(missing)?;
    db.writer.tx(move |tx| {
        tx.execute(
            "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2",
            params![m, id],
        )?;
        Ok(())
    })
}

pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> {
    let d = digest.to_string();
    db.writer.tx(move |tx| {
        tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", params![d, id])?;
        Ok(())
    })
}