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

johnandersen777.bsky.social/vuln-notif

0
0
main
445 lines · 13.6 KB Raw History
//! Typed events: phases/progress -> inner runtime -> outer orchestrator.

use serde_json::{Value, json};
use tokio::sync::mpsc;

use crate::links::LinkRepairCounters;
use crate::metrics::CycleStats;
use crate::publish::PublishStats;
use crate::release::{
    AffectedCounters, ExtrasCounters, HistoryJobCounters, HistoryModeCounters, ReleaseCounters,
};
use crate::software::SoftwareCounters;

/// Progress reported by lane functions through the bounded phase channel.
#[derive(Debug, Clone)]
pub enum ProgressEvent {
    PublishPhaseStarted {
        limit: usize,
    },
    PublishPhaseCompleted {
        stats: PublishStats,
        error: Option<String>,
    },
    PublishBatchStarted {
        offset: usize,
        size: usize,
    },
    PublishBatchCompleted {
        offset: usize,
        size: usize,
        missing: usize,
        created: u64,
        present: u64,
        failed: u64,
    },
    SoftwarePhaseStarted {
        limit: usize,
    },
    SoftwarePhaseCompleted {
        stats: SoftwareCounters,
    },
    ReleasePhaseStarted {
        /// `latest` or `affected`.
        mode: &'static str,
        limit: usize,
        recheck_seconds: f64,
    },
    ReleasePhaseCompleted {
        stats: ReleaseCounters,
    },
    ReleaseAffectedCompleted {
        stats: AffectedCounters,
    },
    ReleaseHistoryStarted {
        limit: usize,
        concurrency: usize,
    },
    ReleaseHistoryProject {
        project: String,
        counters: HistoryJobCounters,
    },
    ReleaseHistorySkipped {
        project: String,
        reason: String,
    },
    ReleaseHistoryCompleted {
        stats: HistoryModeCounters,
    },
    ReleaseExtrasStarted {
        limit: usize,
    },
    ReleaseExtrasProject {
        project: String,
        version: String,
    },
    ReleaseExtrasSkipped {
        project: String,
        reason: String,
    },
    ReleaseExtrasCompleted {
        stats: ExtrasCounters,
    },
}

/// Channel handed to lane phase functions for progress reporting.
pub type EventTx = mpsc::Sender<ProgressEvent>;

/// Runtime lifecycle events forwarded to the orchestrator for stdout/logs.
#[derive(Debug, Clone)]
pub enum RuntimeEvent {
    PrepareStarted,
    S3Downloaded {
        bucket: String,
        path: String,
        bytes: u64,
        seconds: f64,
    },
    PdsResolved {
        handle: String,
        pds: String,
        seconds: f64,
    },
    PdsLoggedIn {
        repo: String,
        seconds: f64,
    },
    CycleStarted {
        cycle: u64,
        cursor: Option<String>,
    },
    NvdPhaseStarted {
        cursor: Option<String>,
    },
    NvdPhaseCompleted {
        cves: u64,
        requests: u64,
        retries: u64,
        seconds: f64,
        cursor: Option<String>,
        error: Option<String>,
    },
    CvesCached {
        new: u64,
        updated_pending: u64,
        already_done: u64,
    },
    PublishPhaseStarted {
        limit: usize,
    },
    PublishPhaseCompleted {
        stats: PublishStats,
        error: Option<String>,
    },
    PublishBatchStarted {
        offset: usize,
        size: usize,
    },
    PublishBatchCompleted {
        offset: usize,
        size: usize,
        missing: usize,
        created: u64,
        present: u64,
        failed: u64,
    },
    SoftwarePhaseStarted {
        limit: usize,
    },
    SoftwarePhaseCompleted {
        stats: SoftwareCounters,
        error: Option<String>,
    },
    ReleasePhaseStarted {
        mode: String,
        limit: usize,
        recheck_seconds: f64,
    },
    ReleasePhaseCompleted {
        stats: ReleaseCounters,
        error: Option<String>,
    },
    ReleaseAffectedCompleted {
        stats: AffectedCounters,
        error: Option<String>,
    },
    ReleaseHistoryStarted {
        limit: usize,
        concurrency: usize,
    },
    ReleaseHistoryProject {
        project: String,
        counters: HistoryJobCounters,
    },
    ReleaseHistorySkipped {
        project: String,
        reason: String,
    },
    ReleaseHistoryCompleted {
        stats: HistoryModeCounters,
        error: Option<String>,
    },
    ReleaseExtrasStarted {
        limit: usize,
    },
    ReleaseExtrasProject {
        project: String,
        version: String,
    },
    ReleaseExtrasSkipped {
        project: String,
        reason: String,
    },
    ReleaseExtrasCompleted {
        stats: ExtrasCounters,
        error: Option<String>,
    },
    LinkRepairCompleted {
        phase: &'static str,
        counters: LinkRepairCounters,
        error: Option<String>,
    },
    S3Uploaded {
        bucket: String,
        path: String,
        bytes: u64,
        seconds: f64,
    },
    S3UploadFailed {
        bucket: String,
        path: String,
        bytes: u64,
        error: String,
    },
    CycleCompleted {
        cycle: u64,
        duration: f64,
        stats: Box<CycleStats>,
    },
    CycleFailed {
        cycle: u64,
        error: String,
    },
    ShutdownRequested,
    Fatal {
        error: String,
    },
    Done,
}

impl RuntimeEvent {
    pub fn name(&self) -> &'static str {
        match self {
            Self::PrepareStarted => "prepare_started",
            Self::S3Downloaded { .. } => "s3_downloaded",
            Self::PdsResolved { .. } => "pds_resolved",
            Self::PdsLoggedIn { .. } => "pds_logged_in",
            Self::CycleStarted { .. } => "cycle_started",
            Self::NvdPhaseStarted { .. } => "nvd_phase_started",
            Self::NvdPhaseCompleted { .. } => "nvd_phase_completed",
            Self::CvesCached { .. } => "cves_cached",
            Self::PublishPhaseStarted { .. } => "publish_phase_started",
            Self::PublishPhaseCompleted { .. } => "publish_phase_completed",
            Self::PublishBatchStarted { .. } => "publish_batch_started",
            Self::PublishBatchCompleted { .. } => "publish_batch_completed",
            Self::SoftwarePhaseStarted { .. } => "software_phase_started",
            Self::SoftwarePhaseCompleted { .. } => "software_phase_completed",
            Self::ReleasePhaseStarted { .. } => "release_phase_started",
            Self::ReleasePhaseCompleted { .. } => "release_phase_completed",
            Self::ReleaseAffectedCompleted { .. } => "release_affected_completed",
            Self::ReleaseHistoryStarted { .. } => "release_history_started",
            Self::ReleaseHistoryProject { .. } => "release_history_project",
            Self::ReleaseHistorySkipped { .. } => "release_history_skipped",
            Self::ReleaseHistoryCompleted { .. } => "release_history_completed",
            Self::ReleaseExtrasStarted { .. } => "release_extras_started",
            Self::ReleaseExtrasProject { .. } => "release_extras_project",
            Self::ReleaseExtrasSkipped { .. } => "release_extras_skipped",
            Self::ReleaseExtrasCompleted { .. } => "release_extras_completed",
            Self::LinkRepairCompleted { .. } => "link_repair_completed",
            Self::S3Uploaded { .. } => "s3_uploaded",
            Self::S3UploadFailed { .. } => "s3_upload_failed",
            Self::CycleCompleted { .. } => "cycle_completed",
            Self::CycleFailed { .. } => "cycle_failed",
            Self::ShutdownRequested => "shutdown_requested",
            Self::Fatal { .. } => "fatal",
            Self::Done => "done",
        }
    }

    /// Payload fields (everything except the `event` key).
    pub fn payload(&self) -> Value {
        match self {
            Self::PrepareStarted | Self::ShutdownRequested | Self::Done => json!({}),
            Self::S3Downloaded {
                bucket,
                path,
                bytes,
                seconds,
            } => json!({
                "bucket": bucket,
                "path": path,
                "bytes": bytes,
                "seconds": seconds,
            }),
            Self::PdsResolved {
                handle,
                pds,
                seconds,
            } => json!({ "handle": handle, "pds": pds, "seconds": seconds }),
            Self::PdsLoggedIn { repo, seconds } => {
                json!({ "repo": repo, "seconds": seconds })
            }
            Self::CycleStarted { cycle, cursor } => {
                json!({ "cycle": cycle, "cursor": cursor })
            }
            Self::NvdPhaseStarted { cursor } => json!({ "cursor": cursor }),
            Self::NvdPhaseCompleted {
                cves,
                requests,
                retries,
                seconds,
                cursor,
                error,
            } => json!({
                "cves": cves,
                "requests": requests,
                "retries": retries,
                "seconds": seconds,
                "cursor": cursor,
                "error": error,
            }),
            Self::CvesCached {
                new,
                updated_pending,
                already_done,
            } => json!({
                "new": new,
                "updated_pending": updated_pending,
                "already_done": already_done,
            }),
            Self::PublishPhaseStarted { limit } => json!({ "limit": limit }),
            Self::PublishPhaseCompleted { stats, error } => stats_payload(stats, error),
            Self::PublishBatchStarted { offset, size } => {
                json!({ "offset": offset, "size": size })
            }
            Self::PublishBatchCompleted {
                offset,
                size,
                missing,
                created,
                present,
                failed,
            } => json!({
                "offset": offset,
                "size": size,
                "missing": missing,
                "created": created,
                "present": present,
                "failed": failed,
            }),
            Self::SoftwarePhaseStarted { limit } => json!({ "limit": limit }),
            Self::SoftwarePhaseCompleted { stats, error } => stats_payload(stats, error),
            Self::ReleasePhaseStarted {
                mode,
                limit,
                recheck_seconds,
            } => json!({
                "mode": mode,
                "limit": limit,
                "recheck_seconds": recheck_seconds,
            }),
            Self::ReleasePhaseCompleted { stats, error } => stats_payload(stats, error),
            Self::ReleaseAffectedCompleted { stats, error } => stats_payload(stats, error),
            Self::ReleaseHistoryStarted { limit, concurrency } => {
                json!({ "limit": limit, "concurrency": concurrency })
            }
            Self::ReleaseHistoryProject { project, counters } => {
                let mut payload = flatten(serde_json::to_value(counters).unwrap_or(Value::Null));
                if let Value::Object(fields) = &mut payload {
                    fields.insert("project".to_owned(), json!(project));
                }
                payload
            }
            Self::ReleaseHistorySkipped { project, reason } => {
                json!({ "project": project, "reason": reason })
            }
            Self::ReleaseHistoryCompleted { stats, error } => stats_payload(stats, error),
            Self::ReleaseExtrasStarted { limit } => json!({ "limit": limit }),
            Self::ReleaseExtrasProject { project, version } => {
                json!({ "project": project, "version": version })
            }
            Self::ReleaseExtrasSkipped { project, reason } => {
                json!({ "project": project, "reason": reason })
            }
            Self::ReleaseExtrasCompleted { stats, error } => stats_payload(stats, error),
            Self::LinkRepairCompleted {
                phase,
                counters,
                error,
            } => {
                let mut payload = stats_payload(counters, error);
                if let Value::Object(fields) = &mut payload {
                    fields.insert("phase".to_owned(), json!(phase));
                }
                payload
            }
            Self::S3Uploaded {
                bucket,
                path,
                bytes,
                seconds,
            } => json!({
                "bucket": bucket,
                "path": path,
                "bytes": bytes,
                "seconds": seconds,
            }),
            Self::S3UploadFailed {
                bucket,
                path,
                bytes,
                error,
            } => json!({
                "bucket": bucket,
                "path": path,
                "bytes": bytes,
                "error": error,
            }),
            Self::CycleCompleted {
                cycle,
                duration,
                stats,
            } => cycle_completed_payload(stats, *cycle, *duration),
            Self::CycleFailed { cycle, error } => {
                json!({ "cycle": cycle, "error": error })
            }
            Self::Fatal { error } => json!({ "error": error }),
        }
    }
}

/// Full cycle stats plus the event-level cycle/duration fields.
pub fn cycle_completed_payload(stats: &CycleStats, cycle: u64, duration: f64) -> Value {
    let mut payload = stats.to_value();
    if let Value::Object(fields) = &mut payload {
        fields.insert("cycle".to_owned(), json!(cycle));
        fields.insert("duration".to_owned(), json!(duration));
    }
    payload
}

fn flatten(value: Value) -> Value {
    match value {
        Value::Object(_) => value,
        other => json!({ "data": other }),
    }
}

/// Serialized phase stats plus the optional error field.
fn stats_payload(stats: &impl serde::Serialize, error: &Option<String>) -> Value {
    let mut payload = flatten(serde_json::to_value(stats).unwrap_or(Value::Null));
    if let Value::Object(fields) = &mut payload {
        fields.insert("error".to_owned(), json!(error));
    }
    payload
}