summaryrefslogtreecommitdiffstats
path: root/src/review/candidates.rs
blob: 566434b34a9b3562e2749aff86714ae0780212ae (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
//! Candidate creation and the collapse-in-place rule (§7.1).
//!
//! One review object per pkgbase at a time. A newer detection **collapses into**
//! the open review rather than queueing beside it, and the review's `base` is
//! fixed at creation to the pkgbase's `current_accepted_release` — that is what
//! makes "diff against the last accepted version, never the last seen one" (I2)
//! true no matter how many detections arrive while nobody is looking.

use rusqlite::OptionalExtension;

use crate::db::{self, *};
use crate::error::Result;
use crate::time;

#[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,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Upsert {
    /// A new review row was opened.
    Created { id: i64, kind: String },
    /// The open review was updated in place; no new row, `base` untouched (I7).
    Collapsed { id: i64, revision: i64 },
    /// A human had already seen the old diff, so it was frozen as `superseded`
    /// and a fresh review opened (decision 8).
    Superseded { old: i64, new: i64 },
    /// This exact identity was rejected before; do not nag (§7.1).
    PreviouslyRejected,
    /// Nothing changed relative to what is already recorded.
    Unchanged,
}

/// Insert-or-collapse a candidate for `pb`.
///
/// `accepted` is the pkgbase's current accepted release, or `None` when this is
/// a first introduction (§7.1b).
pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> {
    let kind = if accepted.is_some() { candidate_kind::NEW_VERSION } else { candidate_kind::FIRST_INTRODUCTION };
    let base = accepted.map(|a| a.id);
    let pkgbase_id = pb.id;
    let nc = nc.clone();

    db.writer.tx(move |tx| {
        let existing: Option<(i64, String, Option<String>, i64)> = tx
            .query_row(
                "SELECT id, identity_hash, viewed_at, revision FROM candidate
                 WHERE pkgbase_id=?1 AND state='pending_review'",
                rusqlite::params![pkgbase_id],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
            )
            .optional()?;

        if let Some((id, identity, viewed, revision)) = existing {
            if identity == nc.identity_hash {
                return Ok(Upsert::Unchanged);
            }
            if viewed.is_none() {
                // Collapse in place: same base, no new row, revision bumped.
                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",
                    rusqlite::params![
                        nc.snapshot_id, nc.epoch, nc.pkgver, nc.pkgrel,
                        nc.upstream_pins_json, nc.source_digests_json, nc.identity_hash,
                        revision + 1, time::now(), id
                    ],
                )?;
                return Ok(Upsert::Collapsed { id, revision: revision + 1 });
            }
            // A human saw the old diff: freeze it for the audit trail and open a
            // fresh review against the same base.
            tx.execute(
                "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2",
                rusqlite::params![time::now(), id],
            )?;
            let new_id = insert(tx, pkgbase_id, base, kind, &nc)?;
            return Ok(Upsert::Superseded { old: id, new: new_id });
        }

        // No open review. A previously rejected identity must not be re-raised.
        let rejected: Option<i64> = tx
            .query_row(
                "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected'
                 ORDER BY id DESC LIMIT 1",
                rusqlite::params![pkgbase_id, nc.identity_hash],
                |r| r.get(0),
            )
            .optional()?;
        if rejected.is_some() {
            return Ok(Upsert::PreviouslyRejected);
        }
        // Same identity already approved/recorded: nothing to do.
        let same: Option<i64> = tx
            .query_row(
                "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2
                 ORDER BY id DESC LIMIT 1",
                rusqlite::params![pkgbase_id, nc.identity_hash],
                |r| r.get(0),
            )
            .optional()?;
        if same.is_some() {
            return Ok(Upsert::Unchanged);
        }
        let id = insert(tx, pkgbase_id, base, kind, &nc)?;
        Ok(Upsert::Created { id, kind: kind.to_string() })
    })
}

fn insert(
    tx: &mut rusqlite::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)",
        rusqlite::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())
}

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)
    }
}

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

/// 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",
            rusqlite::params![at, id],
        )?;
        Ok(())
    })
}

pub fn pending_candidates(db: &Db) -> Result<Vec<CandidateRow>> {
    db.read(|c| {
        let mut stmt = c.prepare(
            "SELECT 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
             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",
        )?;
        let rows = stmt.query_map([], row_to_candidate)?;
        let mut out = Vec::new();
        for r in rows {
            out.push(r?);
        }
        Ok(out)
    })
}

pub fn candidate_by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> {
    db.read(|c| {
        Ok(c.query_row(
            "SELECT 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
             FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1",
            rusqlite::params![id],
            row_to_candidate,
        )
        .optional()?)
    })
}

fn row_to_candidate(r: &rusqlite::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: r.get(17)?,
        detected_at: r.get(18)?,
        resolved_at: r.get(19)?,
        pkgbase: r.get(20)?,
    })
}

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

/// §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'",
            rusqlite::params![at, id],
        )?;
        if n == 0 {
            return Err(crate::error::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",
            rusqlite::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",
            rusqlite::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", rusqlite::params![d, id])?;
        Ok(())
    })
}

/// Convenience used by the watcher: the accepted release of a pkgbase row.
pub fn accepted_for(db: &Db, pb: &Pkgbase) -> Result<Option<ReleaseRow>> {
    match pb.current_accepted_release_id {
        Some(id) => db::release_by_id(db, id),
        None => Ok(None),
    }
}