summaryrefslogtreecommitdiffstats
path: root/src/db/model.rs
blob: 3fa2840fbc7312ce6c5d191c4d1e1232a27215d2 (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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
//! Row types and small value objects that appear in JSON columns.

use serde::{Deserialize, Serialize};

use crate::hash;

/// One resolved upstream VCS source (DESIGN.md §3, "Three things to pin").
///
/// The commit SHA alone is sufficient: a git commit transitively commits to its
/// tree, and a gitlink in that tree commits to any submodule's commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpstreamPin {
    /// Index into the PKGBUILD `source=()` array.
    pub index: usize,
    pub url: String,
    /// The ref we asked for: `HEAD`, a tag, or an explicit commit.
    pub ref_: String,
    /// Branch the ref resolved to, when known.
    pub branch: Option<String>,
    /// Resolved commit SHA. This is the pin.
    pub commit: String,
}

/// A row of the Stage B cache (§5.2): the version that resolution produced,
/// with the pins it was computed from.
///
/// This lives with the schema because the table lives here — the persistence
/// layer must not name a type from the module that owns VCS probing, which is
/// the dependency pointing the wrong way (§6 M-6). `watch::upstream::StageB`
/// is this plus `cached`, and that extra field is the reason the two are not
/// the same type: "was this answer a cache hit?" is a fact about the resolution
/// that just happened, not a column.
#[derive(Debug, Clone)]
pub struct StageBCacheRow {
    pub epoch: String,
    pub pkgver: String,
    pub pkgrel: String,
    pub pins: Vec<UpstreamPin>,
}

impl StageBCacheRow {
    pub fn version(&self) -> String {
        crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
    }
}

/// A source entry with the digest *we* computed, regardless of what the
/// PKGBUILD declares (§5.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceDigest {
    pub index: usize,
    pub url: String,
    /// `static` | `vcs` | `local`
    pub kind: String,
    /// sha256, or the resolved VCS commit for vcs sources.
    pub digest: String,
    pub size: u64,
    /// True when the PKGBUILD gave us no checksum to trust for this source —
    /// `SKIP`, a malformed digest, or nothing at all.
    ///
    /// It means that and nothing else (m-19). It used to be hardcoded `true` for
    /// VCS entries, where it reads as a warning the recipe never earned: a
    /// `-git` source has no checksum by design because the *pin* is the
    /// integrity. Ask [`SourceDigest::is_vcs`] when you need to know which of
    /// the two mechanisms protects an entry.
    pub skip_declared: bool,
}

impl SourceDigest {
    /// True when this entry's integrity comes from a resolved commit rather than
    /// a content hash.
    pub fn is_vcs(&self) -> bool {
        matches!(self.kind.as_str(), "vcs" | "git" | "svn" | "hg" | "bzr")
    }
}

/// A member of a world snapshot: one of *our* packages the build ran against.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct WorldMember {
    pub pkgbase: String,
    pub version: String,
}

/// The identity tuple of a candidate (§3). Every element is part of the key.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Identity {
    pub aur_commit: String,
    pub epoch: String,
    pub pkgver: String,
    pub pkgrel: String,
    pub upstream_pins: Vec<UpstreamPin>,
    pub source_digests: Vec<SourceDigest>,
}

impl Identity {
    /// The hash that makes I3 a fact: two byte-identical inputs never produce
    /// two candidates, and any change to what becomes a byte in the artifact
    /// produces a new one.
    ///
    /// A digest of the canonical JSON of the identity tuple. This is the value
    /// an approval must echo: two candidates share an `identity_hash` only if
    /// every pin, digest and version in them is identical. A value that cannot
    /// be serialized is an error rather than a digest — a shared fallback digest
    /// would be the one way two identities could collide by accident.
    pub fn hash(&self) -> crate::error::Result<String> {
        Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes())))
    }
}

/// The review state machine (§7.1).
///
/// A candidate is what a human decides on, and the decision is the one thing in
/// this system that must never be overwritten by accident: an approval that
/// silently replaced a rejection, or a superseded review resurrected, would
/// break I2 and I3 without any symptom. So the states are an enum, and
/// [`crate::db::candidates::resolve_in`] refuses a move the machine forbids.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CandidateState {
    /// Open: nobody has decided yet. The only state a reviewer can act on.
    PendingReview,
    Approved,
    Rejected,
    /// Frozen: a newer review of the same pkgbase took its place (§7.1).
    Superseded,
    /// Not approved because something it needs is missing (§10.4).
    Blocked,
}

impl CandidateState {
    pub const ALL: &'static [CandidateState] = &[
        CandidateState::PendingReview,
        CandidateState::Approved,
        CandidateState::Rejected,
        CandidateState::Superseded,
        CandidateState::Blocked,
    ];

    pub fn as_str(&self) -> &'static str {
        match self {
            CandidateState::PendingReview => "pending_review",
            CandidateState::Approved => "approved",
            CandidateState::Rejected => "rejected",
            CandidateState::Superseded => "superseded",
            CandidateState::Blocked => "blocked",
        }
    }

    pub fn parse(s: &str) -> Option<CandidateState> {
        CandidateState::ALL.iter().copied().find(|c| c.as_str() == s)
    }

    /// The state a reviewer can still act on.
    pub fn is_open(&self) -> bool {
        *self == CandidateState::PendingReview
    }

    /// May a candidate in this state be written to `to`? Re-writing the state it
    /// already has is a no-op, not a move.
    pub fn can_transition(&self, to: CandidateState) -> bool {
        use CandidateState::*;
        if *self == to {
            return true;
        }
        match self {
            PendingReview => matches!(to, Approved | Rejected | Superseded | Blocked),
            // A decided review is only ever frozen, never re-decided (§7.1).
            Approved | Rejected => to == Superseded,
            Blocked => matches!(to, PendingReview | Approved | Rejected),
            Superseded => false,
        }
    }

    pub fn predecessors(to: CandidateState) -> Vec<&'static str> {
        CandidateState::ALL
            .iter()
            .filter(|from| from.can_transition(to))
            .map(|from| from.as_str())
            .collect()
    }
}

impl std::fmt::Display for CandidateState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

pub mod candidate_kind {
    pub const NEW_VERSION: &str = "new_version";
    pub const FIRST_INTRODUCTION: &str = "first_introduction";
}

/// The release state machine (§9).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReleaseState {
    /// In the served index.
    Published,
    /// Taken out of the index (§9 withdrawal); the row stays (§15).
    Withdrawn,
    /// Approved, but the build never produced it: the old version still serves.
    FailedUnbuilt,
}

impl ReleaseState {
    pub const ALL: &'static [ReleaseState] = &[
        ReleaseState::Published,
        ReleaseState::Withdrawn,
        ReleaseState::FailedUnbuilt,
    ];

    pub fn as_str(&self) -> &'static str {
        match self {
            ReleaseState::Published => "published",
            ReleaseState::Withdrawn => "withdrawn",
            ReleaseState::FailedUnbuilt => "failed_unbuilt",
        }
    }

    pub fn parse(s: &str) -> Option<ReleaseState> {
        ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s)
    }

    /// Withdrawal is the only move a release makes on its own; a failed-unbuilt
    /// release is a record of an attempt, and a published one is live.
    pub fn can_transition(&self, to: ReleaseState) -> bool {
        use ReleaseState::*;
        if *self == to {
            return true;
        }
        match self {
            Published => matches!(to, Withdrawn | FailedUnbuilt),
            Withdrawn | FailedUnbuilt => false,
        }
    }
}

impl std::fmt::Display for ReleaseState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// What the state enums below have in common: a closed set of column values,
/// parsed where a row is read. `db::state_col` uses this to fail a row whose
/// state the code does not know instead of defaulting it.
pub trait StateEnum: Copy + Sized {
    /// The name of the machine, for the error message.
    const KIND: &'static str;
    fn parse(text: &str) -> Option<Self>;
    fn as_str(&self) -> &'static str;
}

macro_rules! impl_state_enum {
    ($t:ty, $kind:literal) => {
        impl StateEnum for $t {
            const KIND: &'static str = $kind;
            fn parse(text: &str) -> Option<Self> {
                <$t>::parse(text)
            }
            fn as_str(&self) -> &'static str {
                <$t>::as_str(self)
            }
        }
    };
}

impl_state_enum!(BuildState, "build");
impl_state_enum!(CandidateState, "candidate");
impl_state_enum!(StepState, "build step");
impl_state_enum!(ReleaseState, "release");
impl_state_enum!(SubscriptionState, "subscription");

/// The build state machine (§7.1, §8.2).
///
/// This used to be seven `&str` constants and a `set_state(&str)` that wrote any
/// string a caller invented, so the machine existed only as `WHERE state IN
/// (...)` clauses scattered across six modules — nothing could tell you that
/// `succeeded → running` is nonsense. The enum is the machine: a state is one
/// of these seven, it is parsed where a row is read, and `can_transition` is
/// the only way a write happens.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum BuildState {
    /// Approved and waiting for a worker.
    Queued,
    /// Claimed by a worker with a lease (§8.2).
    Leased,
    /// A step is executing.
    Running,
    /// Waiting for packages another build must publish first (§10.4).
    BlockedMissingDep,
    Succeeded,
    Failed,
    Cancelled,
}

impl BuildState {
    pub const ALL: &'static [BuildState] = &[
        BuildState::Queued,
        BuildState::Leased,
        BuildState::Running,
        BuildState::BlockedMissingDep,
        BuildState::Succeeded,
        BuildState::Failed,
        BuildState::Cancelled,
    ];

    /// The text in the `state` column. The spelling is part of the schema: the
    /// reaper, the dispatcher and the UI all speak it.
    pub fn as_str(&self) -> &'static str {
        match self {
            BuildState::Queued => "queued",
            BuildState::Leased => "leased",
            BuildState::Running => "running",
            BuildState::BlockedMissingDep => "blocked_missing_dep",
            BuildState::Succeeded => "succeeded",
            BuildState::Failed => "failed",
            BuildState::Cancelled => "cancelled",
        }
    }

    /// The only way in from the database text. An unrecognised state is `None`,
    /// and the row boundary turns that into an error rather than a silent
    /// fallback: a state we cannot name is a state we must not act on.
    pub fn parse(s: &str) -> Option<BuildState> {
        BuildState::ALL.iter().copied().find(|b| b.as_str() == s)
    }

    /// Nothing happens to a finished build by itself. `Succeeded` is final —
    /// the release is published and the row is history (§15). `Failed` and
    /// `Cancelled` end a worker's involvement, and only an explicit human
    /// requeue or resume moves them again ([`BuildState::can_transition`]).
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled
        )
    }

    /// May a row in this state be written to `to`?
    ///
    /// Writing the state a row already has is always allowed: it is a no-op, not
    /// a move. The step loop re-asserts `Running` at every step boundary (§8.3),
    /// and re-running a finished build must stay harmless rather than turn into
    /// an error.
    ///
    /// Everything else is refused by [`crate::db::builds::set_state`], and the
    /// refusals are the point: nothing revives a `Succeeded` build, and a build
    /// reaped back to `Queued` cannot be completed by the zombie worker that
    /// lost its lease — that refusal is the alarm.
    pub fn can_transition(&self, to: BuildState) -> bool {
        use BuildState::*;
        if *self == to {
            return true;
        }
        match self {
            // The dispatcher claims queued builds; `aur-build run <id>` runs one
            // in the foreground without a lease, so `Running` is legal from here
            // too. A dependency can be discovered before a worker ever starts.
            Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled),
            Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled),
            Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled),
            BlockedMissingDep => matches!(to, Queued | Cancelled),
            // A failed build is resumed on the same row — that is I5 (the step
            // checkpoints say where to continue) and §8.4's human requeue.
            Failed => matches!(to, Queued | Running),
            // §8.4: requeue is a human decision, not a policy.
            Cancelled => to == Queued,
            Succeeded => false,
        }
    }

    /// Every state that may legally move to `to` — the `WHERE state IN (...)`
    /// that makes a state write a compare-and-swap.
    pub fn predecessors(to: BuildState) -> Vec<&'static str> {
        BuildState::ALL
            .iter()
            .filter(|from| from.can_transition(to))
            .map(|from| from.as_str())
            .collect()
    }

    /// The states the queue considers "in flight" for metrics and the index.
    pub fn active() -> &'static [BuildState] {
        &[
            BuildState::Queued,
            BuildState::Running,
            BuildState::Leased,
            BuildState::BlockedMissingDep,
        ]
    }
}

impl std::fmt::Display for BuildState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The step checkpoint state machine (§8.3, I5).
///
/// The checkpoint row is what a resumed build reads to decide what not to redo,
/// so the rule that matters is that a completed checkpoint is frozen: a step
/// recorded `succeeded` or `skipped` is never re-run and never rewritten.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepState {
    Pending,
    Running,
    Succeeded,
    Failed,
    /// Killed mid-step; the reaper writes this so the resume re-runs it (§8.2).
    Interrupted,
    Skipped,
}

impl StepState {
    pub const ALL: &'static [StepState] = &[
        StepState::Pending,
        StepState::Running,
        StepState::Succeeded,
        StepState::Failed,
        StepState::Interrupted,
        StepState::Skipped,
    ];

    pub fn as_str(&self) -> &'static str {
        match self {
            StepState::Pending => "pending",
            StepState::Running => "running",
            StepState::Succeeded => "succeeded",
            StepState::Failed => "failed",
            StepState::Interrupted => "interrupted",
            StepState::Skipped => "skipped",
        }
    }

    pub fn parse(text: &str) -> Option<StepState> {
        StepState::ALL.iter().copied().find(|st| st.as_str() == text)
    }

    /// I5: the resume skips a step in one of these two states, so nothing may
    /// move it again — a checkpoint that can be rewritten is not a checkpoint.
    pub fn is_done(&self) -> bool {
        matches!(self, StepState::Succeeded | StepState::Skipped)
    }

    pub fn can_transition(&self, to: StepState) -> bool {
        use StepState::*;
        if *self == to {
            return true;
        }
        match self {
            Pending => matches!(to, Running | Succeeded | Failed | Interrupted | Skipped),
            // `Running → Pending` is the blocked path: the step did not happen,
            // so the checkpoint goes back to waiting.
            Running => matches!(to, Pending | Succeeded | Failed | Interrupted | Skipped),
            Failed | Interrupted => matches!(to, Pending | Running),
            Succeeded | Skipped => false,
        }
    }

    pub fn predecessors(to: StepState) -> Vec<&'static str> {
        StepState::ALL
            .iter()
            .filter(|from| from.can_transition(to))
            .map(|from| from.as_str())
            .collect()
    }
}

impl std::fmt::Display for StepState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

pub mod notice_kind {
    pub const PIN_DRIFT: &str = "pin_drift";
    pub const RECIPE_DRIFT: &str = "recipe_drift";
    pub const DIGEST_DRIFT: &str = "digest_drift";
    pub const INTEGRITY_ALERT: &str = "integrity_alert";
    pub const UNPINABLE_PKGVER: &str = "unpinable_pkgver";
    pub const ORPHANED: &str = "orphaned";
    pub const DELETED: &str = "deleted";
    pub const RENAMED: &str = "renamed";
    pub const DOWNGRADE: &str = "downgrade";
}

/// Whether a pkgbase is being watched (§4.1, §12).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubscriptionState {
    Active,
    Paused,
    /// The pkgbase left AUR; the watcher stopped looking (§12).
    Orphaned,
    Removed,
}

impl SubscriptionState {
    pub const ALL: &'static [SubscriptionState] = &[
        SubscriptionState::Active,
        SubscriptionState::Paused,
        SubscriptionState::Orphaned,
        SubscriptionState::Removed,
    ];

    pub fn as_str(&self) -> &'static str {
        match self {
            SubscriptionState::Active => "active",
            SubscriptionState::Paused => "paused",
            SubscriptionState::Orphaned => "orphaned",
            SubscriptionState::Removed => "removed",
        }
    }

    pub fn parse(text: &str) -> Option<SubscriptionState> {
        SubscriptionState::ALL.iter().copied().find(|st| st.as_str() == text)
    }

    /// Pause and resume are the only moves the UI makes; orphaned and removed
    /// are facts about the pkgbase, reported once.
    pub fn can_transition(&self, to: SubscriptionState) -> bool {
        use SubscriptionState::*;
        if *self == to {
            return true;
        }
        match self {
            Active => matches!(to, Paused | Orphaned | Removed),
            Paused => matches!(to, Active | Orphaned | Removed),
            Orphaned => matches!(to, Active | Removed),
            Removed => false,
        }
    }
}

impl std::fmt::Display for SubscriptionState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The pipeline steps (§8.1). Order matters: a build resumes at the first step
/// in this list without a `succeeded` row.
pub const BUILD_STEPS: &[&str] = &[
    "materialize",
    "plan",
    "chroot",
    "sources",
    "pkgver",
    "build",
    "collect",
    "verify",
    "ingest",
    "publish",
];

/// A `source=()` entry after parsing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SourceEntry {
    pub index: usize,
    /// The URL as written, minus the filename fragment.
    pub url: String,
    /// Explicit filename (`::name` / `::` prefix handling).
    pub filename: Option<String>,
    /// `#commit=` fragment.
    pub commit: Option<String>,
    /// `#tag=` fragment.
    pub tag: Option<String>,
    /// `#branch=` fragment.
    pub branch: Option<String>,
    /// VCS kind if the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`.
    pub vcs: Option<String>,
    /// True for files shipped inside the AUR repo (no scheme).
    pub local: bool,
}

impl SourceEntry {
    pub fn is_vcs(&self) -> bool {
        self.vcs.is_some()
    }
}

/// A parsed recipe: what `.SRCINFO` / `PKGBUILD` tell us.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recipe {
    pub pkgbase: String,
    pub pkgver: String,
    pub pkgrel: String,
    pub epoch: String,
    pub pkgdesc: String,
    pub url: String,
    pub arch: Vec<String>,
    pub license: Vec<String>,
    pub groups: Vec<String>,
    pub depends: Vec<String>,
    pub makedepends: Vec<String>,
    pub checkdepends: Vec<String>,
    pub optdepends: Vec<String>,
    pub provides: Vec<String>,
    pub conflicts: Vec<String>,
    pub source: Vec<String>,
    pub sha256sums: Vec<String>,
    pub b2sums: Vec<String>,
    pub validpgpkeys: Vec<String>,
    pub options: Vec<String>,
    pub backup: Vec<String>,
    pub install: Option<String>,
    /// Names of the binary packages this pkgbase emits (split pkgbases have N).
    pub pkgnames: Vec<String>,
    /// Per-package depends, for split pkgbases.
    pub pkg_depends: Vec<(String, Vec<String>)>,
    /// Raw PKGBUILD text, for display and diffing.
    pub pkgbuild: String,
    /// Raw .SRCINFO text when it was present.
    pub srcinfo: Option<String>,
    /// True if `--skippgpcheck` appears in the PKGBUILD.
    pub skipgpcheck: bool,
    /// Parsed `source=()` entries. Derived from `source`, so not serialized.
    #[serde(skip, default)]
    pub source_entries: Vec<SourceEntry>,
}

impl Recipe {
    /// `epoch:pkgver-pkgrel` as displayed to consumers.
    pub fn full_version(&self) -> String {
        crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
    }
}

/// A source row as stored on a candidate/release.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseRow {
    pub id: i64,
    pub pkgbase_id: i64,
    pub candidate_id: Option<i64>,
    pub approval_id: Option<i64>,
    pub aur_commit: String,
    pub recipe_hash: String,
    pub upstream_pins_json: String,
    pub source_digests_json: String,
    pub epoch: String,
    pub pkgver: String,
    pub pkgrel: String,
    pub world_snapshot_id: Option<i64>,
    pub state: ReleaseState,
    pub published_at: Option<String>,
}

impl ReleaseRow {
    pub fn version(&self) -> String {
        crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
    }
    pub fn pins(&self) -> Vec<UpstreamPin> {
        serde_json::from_str(&self.upstream_pins_json).unwrap_or_default()
    }
    pub fn digests(&self) -> Vec<SourceDigest> {
        serde_json::from_str(&self.source_digests_json).unwrap_or_default()
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct CandidateRow {
    pub id: i64,
    pub pkgbase_id: i64,
    pub base_release_id: Option<i64>,
    pub kind: String,
    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,
    pub diff_digest: String,
    pub revision: i64,
    pub viewed_at: Option<String>,
    pub risk_level: String,
    pub risk_signals_json: String,
    pub missing_deps_json: String,
    pub state: CandidateState,
    pub detected_at: String,
    pub resolved_at: Option<String>,
    pub pkgbase: String,
}

impl CandidateRow {
    pub fn version(&self) -> String {
        crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
    }
    pub fn pins(&self) -> Vec<UpstreamPin> {
        serde_json::from_str(&self.upstream_pins_json).unwrap_or_default()
    }
    pub fn digests(&self) -> Vec<SourceDigest> {
        serde_json::from_str(&self.source_digests_json).unwrap_or_default()
    }
    pub fn risk_signals(&self) -> Vec<String> {
        serde_json::from_str(&self.risk_signals_json).unwrap_or_default()
    }
    pub fn missing_deps(&self) -> Vec<String> {
        serde_json::from_str(&self.missing_deps_json).unwrap_or_default()
    }
}

/// Parse a JSON column with a fallback, so one bad row never takes down a page.
pub fn json_or<T: serde::de::DeserializeOwned>(s: &str, fallback: T) -> T {
    serde_json::from_str(s).unwrap_or(fallback)
}