~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
429 lines · 13.8 KB Raw History
//! 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
}