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
//! Append-only release status transitions.
//!
//! Registry signals (npm/PyPI/crates/RubyGems/NuGet/Go deprecations, yanks,
//! archives, retractions) become immutable `software.release.status` records
//! plus local `release_status_events` rows. Re-observing an identical event is
//! a no-op; a status or reason change appends, never rewrites.
//!
//! CVE presence never changes a status: only an explicit registry
//! [`StatusInfo`] signal can, and `kind: security` is only propagated when the
//! signal itself carries it. A CVE ID inside a reason is never used to infer a
//! kind.
use std::collections::{BTreeMap, BTreeSet};
use anyhow::Result;
use chrono::Utc;
use serde::Serialize;
use serde_json::{Value, json};
use crate::constants::STATUS_COLLECTION;
use crate::db::DbHandle;
use crate::db::model::{
ReleaseStatusEventMark, ReleaseStatusEventRow, ReleaseStatusMark, ReleaseStatusRow,
};
use crate::links;
use crate::pds::Publisher;
use crate::records::digest_rkey;
use crate::release::source::StatusInfo;
use crate::time::created_at;
/// Lifecycle states the `software.release.status` lexicon recognizes.
pub const STATUSES: &[&str] = &["active", "deprecated", "yanked", "archived", "retracted"];
/// Provenance label for transitions planned from registry signals.
pub const REGISTRY_SOURCE: &str = "registry";
const REASON_MAX_CHARS: usize = 3000;
/// One append-only lifecycle event to append for a subject.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusTransition {
pub subject_uri: String,
pub status: String,
pub kind: Option<String>,
pub reason: String,
pub source: String,
}
/// Outcome of [`apply_transitions`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct StatusCounters {
pub planned: u64,
pub created: u64,
pub unchanged: u64,
pub failures: u64,
}
/// Plan the events that are not already present for `subject_uri`.
///
/// `observed` are registry signals for one subject; `current` are the current
/// `release_status` rows (used only to recognize legacy rows written before
/// events were appended). Identical latest events are no-ops, so callers can
/// run this every cycle.
pub async fn plan_transitions(
db: &DbHandle,
repo_did: &str,
subject_uri: &str,
observed: &[StatusInfo],
current: &[ReleaseStatusRow],
) -> Result<Vec<StatusTransition>> {
let existing = db
.list_release_status_events(repo_did, subject_uri, 0)
.await?;
let latest = latest_events(&existing);
let legacy_current: Vec<&str> = current.iter().map(|row| row.status.as_str()).collect();
let mut seen: BTreeSet<(String, Option<String>, String)> = BTreeSet::new();
let mut transitions = Vec::new();
for signal in observed {
let Some(status) = normalized_status(&signal.status) else {
continue;
};
let kind = signal_kind(signal);
let reason = normalized_reason(&signal.reason);
if !seen.insert((status.clone(), kind.clone(), reason.clone())) {
continue;
}
match latest.get(status.as_str()) {
Some(event)
if event.kind == kind && event.reason.as_deref().unwrap_or("") == reason =>
{
continue;
}
None if existing.is_empty()
&& legacy_current.len() == 1
&& legacy_current[0] == status
&& kind.is_none()
&& reason.is_empty() =>
{
continue;
}
_ => {}
}
transitions.push(StatusTransition {
subject_uri: subject_uri.to_owned(),
status,
kind,
reason,
source: REGISTRY_SOURCE.to_owned(),
});
}
Ok(transitions)
}
/// Write each transition as a `software.release.status` record, index its
/// `subject` link, and append the matching local event.
///
/// `events` are the subject's existing event rows; they keep the apply step
/// idempotent even when a caller re-applies stale transitions. The local event
/// is appended only after the PDS write and link index succeed.
pub async fn apply_transitions(
publisher: &Publisher,
db: &DbHandle,
repo_did: &str,
transitions: &[StatusTransition],
events: &[ReleaseStatusEventRow],
) -> StatusCounters {
let mut counters = StatusCounters {
planned: transitions.len() as u64,
..StatusCounters::default()
};
let latest = latest_events(events);
let observed_at = created_at(Utc::now());
for transition in transitions {
if let Some(event) = latest.get(transition.status.as_str())
&& event.kind == transition.kind
&& event.reason.as_deref().unwrap_or("") == transition.reason
{
counters.unchanged += 1;
continue;
}
let rkey = digest_rkey(&[
"status",
&transition.subject_uri,
&transition.status,
transition.kind.as_deref().unwrap_or(""),
&transition.reason,
&observed_at,
]);
let record = status_record(transition);
let outcome = match publisher
.put_record(STATUS_COLLECTION, &rkey, record.clone())
.await
{
Ok(outcome) if outcome.created => outcome,
_ => {
counters.failures += 1;
continue;
}
};
let (Some(uri), Some(cid)) = (outcome.uri, outcome.cid) else {
counters.failures += 1;
continue;
};
if links::index_record(db, repo_did, &uri, Some(&cid), STATUS_COLLECTION, &record)
.await
.is_err()
{
counters.failures += 1;
continue;
}
let event = ReleaseStatusEventMark {
repo_did: repo_did.to_owned(),
subject_uri: transition.subject_uri.clone(),
rkey: rkey.clone(),
status: transition.status.clone(),
kind: transition.kind.clone(),
reason: (!transition.reason.is_empty()).then(|| transition.reason.clone()),
cid: Some(cid.clone()),
created_at: Some(observed_at.clone()),
};
if db.append_release_status_event(event).await.is_err() {
counters.failures += 1;
continue;
}
let mark = ReleaseStatusMark {
repo_did: repo_did.to_owned(),
subject_uri: transition.subject_uri.clone(),
status: transition.status.clone(),
rkey,
uri,
cid,
};
if db.mark_release_status(mark).await.is_err() {
counters.failures += 1;
continue;
}
counters.created += 1;
}
counters
}
fn latest_events(events: &[ReleaseStatusEventRow]) -> BTreeMap<&str, &ReleaseStatusEventRow> {
let mut latest = BTreeMap::new();
for event in events {
latest.insert(event.status.as_str(), event);
}
latest
}
fn normalized_status(raw: &str) -> Option<String> {
let status = raw.trim().to_ascii_lowercase();
STATUSES.contains(&status.as_str()).then_some(status)
}
/// Accept only kinds the signal itself carries. `security` is never inferred
/// from `reason`, so a CVE ID alone cannot promote an event.
fn signal_kind(signal: &StatusInfo) -> Option<String> {
let kind = signal.kind.as_deref()?.trim().to_ascii_lowercase();
matches!(kind.as_str(), "security" | "broken" | "superseded").then_some(kind)
}
fn normalized_reason(raw: &str) -> String {
raw.trim().chars().take(REASON_MAX_CHARS).collect()
}
fn status_record(transition: &StatusTransition) -> Value {
let mut record = json!({
"$type": STATUS_COLLECTION,
"subject": transition.subject_uri,
"status": transition.status,
});
if let Some(kind) = &transition.kind {
record["kind"] = json!(kind);
}
if !transition.reason.is_empty() {
record["reason"] = json!(transition.reason);
}
record
}