summaryrefslogtreecommitdiffstats
path: root/src/db/model/state.rs
blob: dcc9b849c8f3b45ed1f3d4b9e6de53673d58c22f (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
use serde::{Deserialize, Serialize};


use crate::db::model::build_state::{BuildState, StepState};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CandidateState {
    PendingReview,
    Approved,
    Rejected,
    Superseded,
    Blocked,
}

impl CandidateState {
    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)
    }

    pub fn is_open(&self) -> bool {
        *self == CandidateState::PendingReview
    }

    fn can_transition(&self, to: CandidateState) -> bool {
        use CandidateState::*;
        if *self == to {
            return true;
        }
        match self {
            PendingReview => matches!(to, Approved | Rejected | Superseded | Blocked),
            Approved | Rejected => to == Superseded,
            Blocked => matches!(to, PendingReview | Approved | Rejected),
            Superseded => false,
        }
    }

    pub(crate) 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 real definition. The module is private, so this `pub`
/// is not a nameable path from outside; the alias below is the
/// only way to reach it, and the alias is what carries the
/// feature-conditional visibility.
mod release_state {
    use super::*;

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum ReleaseState {
        Published,
        Withdrawn,
        FailedUnbuilt,
    }
}

/// The state column of a release row. `ReleaseRow` is public and its `state` field is typed here, so the type stays reachable in a release build only through this alias.
///
/// `pub` only under `test-support`. Production reaches the type
/// through its own module and never names it from outside; the
/// outside reader that needs the name is a test.
#[cfg(feature = "test-support")]
pub use release_state::ReleaseState;

#[cfg(not(feature = "test-support"))]
pub(crate) use release_state::ReleaseState;

impl ReleaseState {
    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)
    }

    /// NOTE: nothing consults this table today — release transitions are
    /// enforced elsewhere. Left `pub` and dead rather than quietly deleted
    /// or quietly wired up; it is a disposition-table decision.
    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())
    }
}

pub(crate) trait StateEnum: Copy + Sized {
    const KIND: &'static str;
    fn parse(text: &str) -> Option<Self>;
}

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

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");

pub mod notice_kind {
    pub const PIN_DRIFT: &str = "pin_drift";
    pub const RECIPE_DRIFT: &str = "recipe_drift";
    pub const INTEGRITY_ALERT: &str = "integrity_alert";
    pub const DELETED: &str = "deleted";
    pub const DOWNGRADE: &str = "downgrade";
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SubscriptionState {
    Active,
    Paused,
    Orphaned,
    Removed,
}

impl SubscriptionState {
    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)
    }

    /// NOTE: dead in the same way as `ReleaseState::can_transition`.
    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())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // The three enums declared here keep their `ALL` private, so the round trip
    // through column text — the property that makes a stored row readable back
    // — is checked here rather than from outside. BuildState and StepState are
    // covered in build_state.rs.

    #[test]
    fn every_state_declared_here_round_trips_through_its_column_text() {
        for s in CandidateState::ALL {
            assert_eq!(CandidateState::parse(s.as_str()), Some(*s), "candidate {s:?}");
        }
        for s in ReleaseState::ALL {
            assert_eq!(ReleaseState::parse(s.as_str()), Some(*s), "release {s:?}");
        }
        for s in SubscriptionState::ALL {
            assert_eq!(SubscriptionState::parse(s.as_str()), Some(*s), "subscription {s:?}");
        }
        assert_eq!(CandidateState::parse("exploded"), None);
        assert_eq!(ReleaseState::parse("exploded"), None);
        assert_eq!(SubscriptionState::parse("exploded"), None);
    }
}