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
//! Resumable full-history job queue.
//!
//! [`enqueue_versions`] records every source version as a job keyed by
//! `(repo_did, project_slug, version_raw)`, skipping versions that already have
//! an immutable `software.release.version` row. [`process_jobs`] drains a
//! bounded batch: it resolves one artifact per version through an injected
//! [`ArtifactProvider`], reuses existing manifest/version rows, writes only
//! missing immutable records through [`Publisher`], and records the outcome so
//! the next cycle resumes where this one stopped.
//!
//! Job statuses:
//!
//! | status | meaning |
//! |---|---|
//! | `pending` | enqueued, never attempted |
//! | `retry` | transient failure; eligible for the next cycle |
//! | `done` | version record exists (created or reused) |
//! | `skipped` | typed reason in `error`; never retried automatically |
//! | `error` | failed [`MAX_ATTEMPTS`] times; stopped |
//!
//! Every failure increments `attempts` and stores the error text. A job is
//! only run again while `attempts < MAX_ATTEMPTS`; the queue order is
//! `(updated_at, project_slug, version_raw)`, so retries resume deterministically
//! across cycles and processes.
use anyhow::{Result, anyhow, bail};
use async_trait::async_trait;
use serde::Serialize;
use serde_json::Value;
use crate::constants::{MANIFEST_COLLECTION, PROJECT_COLLECTION, VERSION_COLLECTION};
use crate::db::DbHandle;
use crate::db::model::{
ReleaseHistoryJobMark, ReleaseHistoryJobRow, ReleaseManifestMark, ReleaseVersionMark,
};
use crate::links;
use crate::pds::Publisher;
use crate::release::ReleaseCounters;
use crate::release::artifact::Artifact;
use crate::release::records::{manifest_record, manifest_rkey, version_record, version_rkey};
use crate::release::source::VersionInfo;
use crate::runtime::events::{EventTx, ProgressEvent};
/// Statuses `process_jobs` drains, lowest precedence first.
const RUNNABLE_STATUSES: [&str; 2] = ["pending", "retry"];
/// Failures after which a job becomes terminal `error`.
const MAX_ATTEMPTS: i64 = 3;
/// Commit the queue progress every this many jobs.
const COMMIT_EVERY: u64 = 50;
/// One project's full-history ingestion parameters.
#[derive(Debug, Clone)]
pub struct HistoryConfig {
pub repo_did: String,
pub project_slug: String,
pub purl: String,
pub source: String,
/// Maximum jobs processed per call; `0` means no limit.
pub limit: usize,
}
/// Per-call queue counters.
#[derive(Debug, Clone, Default, Serialize)]
pub struct HistoryCounters {
pub enqueued: u64,
pub processed: u64,
pub versions_created: u64,
pub manifests_created: u64,
pub skipped: u64,
pub failed: u64,
pub reused: u64,
}
/// Artifact metadata (and, where the provider verifies it, bytes) for one
/// version. The queue never downloads anything itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedArtifact {
pub file_name: String,
pub url: String,
pub sha256: String,
pub size: u64,
pub mime_type: String,
}
impl ResolvedArtifact {
fn into_artifact(self) -> Artifact {
Artifact {
file_name: self.file_name,
url: self.url,
sha256: self.sha256,
size: self.size,
mime_type: self.mime_type,
}
}
}
/// Artifact resolution seam. Integration adapts the Phase 3 artifact
/// resolver; tests inject a fixture provider.
#[async_trait]
pub trait ArtifactProvider: Send + Sync {
async fn resolve(&self, purl: &str, raw_version: &str) -> Result<ResolvedArtifact>;
}
/// Upsert one job per source version.
///
/// Versions already materialized in `release_versions` are skipped, and an
/// existing job row is never reset: pending/retry jobs keep their attempts and
/// terminal jobs stay terminal, so re-enumerating a source is idempotent and a
/// crash cannot lose resume state.
pub async fn enqueue_versions(
db: &DbHandle,
config: &HistoryConfig,
versions: &[VersionInfo],
) -> Result<HistoryCounters> {
let mut counters = HistoryCounters::default();
for info in versions {
if info.raw.is_empty()
|| info.version.is_empty()
|| db
.get_release_version(&config.repo_did, &config.project_slug, &info.version)
.await?
.is_some()
{
counters.skipped += 1;
continue;
}
if db
.get_release_history_job(&config.repo_did, &config.project_slug, &info.raw)
.await?
.is_some()
{
counters.skipped += 1;
continue;
}
db.mark_release_history_job(ReleaseHistoryJobMark {
repo_did: config.repo_did.clone(),
project_slug: config.project_slug.clone(),
version_raw: info.raw.clone(),
version: Some(info.version.clone()),
source: Some(config.source.clone()),
purl: Some(config.purl.clone()),
status: "pending".to_owned(),
attempts: 0,
error: None,
})
.await?;
counters.enqueued += 1;
}
db.commit().await?;
Ok(counters)
}
/// Drain up to `config.limit` runnable jobs for `config.project_slug`.
///
/// Manifest and version rows are immutable: an existing row is reused as-is
/// and never rewritten. Per-job failures are recorded on the job (and isolated
/// from the rest of the batch); only local DB errors abort the call.
pub async fn process_jobs(
db: &DbHandle,
publisher: &Publisher,
config: &HistoryConfig,
artifacts: &dyn ArtifactProvider,
events: EventTx,
) -> Result<HistoryCounters> {
let _ = events
.send(ProgressEvent::ReleasePhaseStarted {
mode: "history",
limit: config.limit,
recheck_seconds: 0.0,
})
.await;
let mut jobs = Vec::new();
for status in RUNNABLE_STATUSES {
jobs.extend(
db.list_release_history_jobs(&config.repo_did, Some(status), 0)
.await?,
);
}
jobs.retain(|job| job.project_slug == config.project_slug);
jobs.sort_by(|left, right| {
left.updated_at
.cmp(&right.updated_at)
.then_with(|| left.project_slug.cmp(&right.project_slug))
.then_with(|| left.version_raw.cmp(&right.version_raw))
});
if config.limit > 0 {
jobs.truncate(config.limit);
}
let mut counters = HistoryCounters::default();
for job in &jobs {
counters.processed += 1;
match process_job(db, publisher, config, artifacts, job).await? {
JobOutcome::Created {
manifest_created,
reused,
} => {
counters.versions_created += 1;
counters.manifests_created += u64::from(manifest_created);
counters.reused += u64::from(reused);
mark_job(db, job, "done", job.attempts, None).await?;
}
JobOutcome::Reused => {
counters.reused += 1;
mark_job(db, job, "done", job.attempts, None).await?;
}
JobOutcome::Skipped(reason) => {
counters.skipped += 1;
mark_job(db, job, "skipped", job.attempts, Some(reason.to_owned())).await?;
}
JobOutcome::Failed(error) => {
counters.failed += 1;
let attempts = job.attempts + 1;
// Jobs stay runnable until the attempt cap; the attempt count
// and error text are the backoff state available in the queue.
let status = if attempts >= MAX_ATTEMPTS {
"error"
} else {
"retry"
};
mark_job(db, job, status, attempts, Some(error)).await?;
}
}
if counters.processed % COMMIT_EVERY == 0 {
db.commit().await?;
}
}
db.commit().await?;
let _ = events
.send(ProgressEvent::ReleasePhaseCompleted {
stats: ReleaseCounters {
projects_checked: u64::from(counters.processed > 0),
versions_created: counters.versions_created,
skipped: counters.skipped,
failures: counters.failed,
..ReleaseCounters::default()
},
})
.await;
Ok(counters)
}
enum JobOutcome {
Created {
manifest_created: bool,
reused: bool,
},
Reused,
Skipped(&'static str),
Failed(String),
}
async fn process_job(
db: &DbHandle,
publisher: &Publisher,
config: &HistoryConfig,
artifacts: &dyn ArtifactProvider,
job: &ReleaseHistoryJobRow,
) -> Result<JobOutcome> {
let Some(version) = job.version.as_deref().filter(|version| !version.is_empty()) else {
return Ok(JobOutcome::Skipped("unrepresentable_version"));
};
if db
.get_release_version(&config.repo_did, &config.project_slug, version)
.await?
.is_some()
{
return Ok(JobOutcome::Reused);
}
let resolved = match artifacts.resolve(&config.purl, &job.version_raw).await {
Ok(resolved) => resolved,
Err(error) => return Ok(JobOutcome::Failed(error.to_string())),
};
if resolved.sha256.is_empty() || resolved.size == 0 || resolved.url.is_empty() {
return Ok(JobOutcome::Failed(format!(
"missing artifact digest/size: {}",
resolved.url
)));
}
let artifact = resolved.into_artifact();
let manifest_key = manifest_rkey(&config.project_slug, &artifact);
let project_uri = project_uri(db, config).await?;
let existing_manifest = db
.get_release_manifest(&config.repo_did, &config.project_slug, &manifest_key)
.await?;
let (manifest_uri, manifest_cid, manifest_created) = match existing_manifest {
Some(row) if reusable(&row.uri, &row.cid) => (
row.uri.unwrap_or_default(),
row.cid.unwrap_or_default(),
false,
),
_ => {
let record = manifest_record(&project_uri, &artifact);
let (uri, cid) = match write_record(
db,
publisher,
&config.repo_did,
MANIFEST_COLLECTION,
&manifest_key,
&record,
)
.await
{
Ok(written) => written,
Err(error) => return Ok(JobOutcome::Failed(format!("manifest write: {error}"))),
};
db.mark_release_manifest(ReleaseManifestMark {
repo_did: config.repo_did.clone(),
project_slug: config.project_slug.clone(),
manifest_key,
uri: Some(uri.clone()),
cid: Some(cid.clone()),
artifacts_json: Some(serde_json::to_string(
record.get("artifacts").unwrap_or(&Value::Null),
)?),
})
.await?;
(uri, cid, true)
}
};
let version_key = version_rkey(&config.project_slug, version);
let record = version_record(&project_uri, version, &manifest_uri, &manifest_cid);
let (version_uri, version_cid) = match write_record(
db,
publisher,
&config.repo_did,
VERSION_COLLECTION,
&version_key,
&record,
)
.await
{
Ok(written) => written,
Err(error) => return Ok(JobOutcome::Failed(format!("version write: {error}"))),
};
db.mark_release_version(ReleaseVersionMark {
repo_did: config.repo_did.clone(),
project_slug: config.project_slug.clone(),
version: version.to_owned(),
version_raw: job.version_raw.clone(),
rkey: version_key,
uri: version_uri,
cid: version_cid,
manifest_uri,
manifest_cid,
})
.await?;
Ok(JobOutcome::Created {
manifest_created,
reused: !manifest_created,
})
}
fn reusable(uri: &Option<String>, cid: &Option<String>) -> bool {
uri.as_deref().is_some_and(|value| !value.is_empty())
&& cid.as_deref().is_some_and(|value| !value.is_empty())
}
/// The project strongRef target. Latest-mode rows win; otherwise the AT-URI is
/// derived deterministically from the repo DID and canonical slug.
async fn project_uri(db: &DbHandle, config: &HistoryConfig) -> Result<String> {
if let Some(row) = db
.get_release_project(&config.repo_did, &config.project_slug)
.await?
&& let Some(uri) = row.project_uri.filter(|uri| !uri.is_empty())
{
return Ok(uri);
}
Ok(format!(
"at://{}/{PROJECT_COLLECTION}/{}",
config.repo_did, config.project_slug
))
}
async fn write_record(
db: &DbHandle,
publisher: &Publisher,
repo_did: &str,
collection: &str,
rkey: &str,
record: &Value,
) -> Result<(String, String)> {
let outcome = publisher
.put_record(collection, rkey, record.clone())
.await?;
if !outcome.created {
bail!(
"{}",
outcome
.error
.unwrap_or_else(|| "putRecord was not applied".to_owned())
);
}
let uri = outcome
.uri
.ok_or_else(|| anyhow!("putRecord returned no uri"))?;
let cid = outcome
.cid
.ok_or_else(|| anyhow!("putRecord returned no cid"))?;
links::index_or_queue(db, repo_did, &uri, Some(&cid), collection, record).await?;
Ok((uri, cid))
}
async fn mark_job(
db: &DbHandle,
job: &ReleaseHistoryJobRow,
status: &str,
attempts: i64,
error: Option<String>,
) -> Result<()> {
db.mark_release_history_job(ReleaseHistoryJobMark {
repo_did: job.repo_did.clone(),
project_slug: job.project_slug.clone(),
version_raw: job.version_raw.clone(),
version: job.version.clone(),
source: job.source.clone(),
purl: job.purl.clone(),
status: status.to_owned(),
attempts,
error,
})
.await
}