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

johnandersen777.bsky.social/vuln-notif

0
0
main
3859 lines · 136.2 KB Raw History
//! Dedicated-thread SQLite actor.
//!
//! All `rusqlite` work happens on one OS thread. Callers hold a cheap
//! `Clone + Send + Sync` handle and send commands over a bounded Tokio channel;
//! every command carries a `oneshot` reply. Transaction state is tracked here so
//! the commit points match the reference cache exactly.

pub mod model;
pub mod purl2cpe;

use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow};
use chrono::Utc;
use rusqlite::{
    Connection, OptionalExtension, Row, params, params_from_iter, types::Value as SqlValue,
};
use serde_json::Value;
use tokio::sync::{mpsc, oneshot};

use crate::config::Order;
use crate::constants::{RATE_BUDGET_SCHEMA, SCHEMA};
use crate::time::created_at;
use model::{
    Counts, CveRow, IdentityMigrationMark, IdentityMigrationRow, Link, LinkRepairMark,
    LinkRepairRow, LinkRow, ProjectAliasMark, ProjectAliasRow, ProjectChannelMark,
    ProjectChannelRow, PublicationMark, PublishErrorMark, PublishErrorRow, PurlRow, RateBudget,
    ReleaseArtifactMark, ReleaseArtifactRow, ReleaseCandidate, ReleaseChannelMark,
    ReleaseChannelRow, ReleaseCveLinkMark, ReleaseCveLinkRow, ReleaseHistoryJobMark,
    ReleaseHistoryJobRow, ReleaseManifestMark, ReleaseManifestRow, ReleaseOsvMark, ReleaseOsvRow,
    ReleaseProjectMark, ReleaseProjectRow, ReleaseProjectStateMark, ReleaseProjectStateRow,
    ReleaseSourceStateMark, ReleaseSourceStateRow, ReleaseStatusEventMark, ReleaseStatusEventRow,
    ReleaseStatusMark, ReleaseStatusRow, ReleaseVersionMark, ReleaseVersionMetaMark,
    ReleaseVersionMetaRow, ReleaseVersionRow, SoftwareIdentityMark, SoftwareIdentityRow,
    SoftwareMark, SoftwareRow, SourceHostStateMark, SourceHostStateRow, cache_json,
};

const DB_QUEUE: usize = 256;

type Reply<T> = oneshot::Sender<Result<T>>;

#[derive(Clone)]
pub struct DbHandle {
    tx: mpsc::Sender<DbCmd>,
}

enum DbCmd {
    GetCursor(Reply<Option<String>>),
    SetCursor {
        cursor: String,
        reply: Reply<()>,
    },
    UpsertCves {
        repo_did: String,
        cves: Vec<Value>,
        reply: Reply<(i64, i64, i64)>,
    },
    Pending {
        repo_did: String,
        limit: usize,
        order: Order,
        reply: Reply<Vec<CveRow>>,
    },
    MarkPublication {
        mark: PublicationMark,
        reply: Reply<()>,
    },
    GetCveRecord {
        repo_did: String,
        cve_id: String,
        reply: Reply<Option<(String, String)>>,
    },
    GetCveData {
        cve_id: String,
        reply: Reply<Option<Value>>,
    },
    GetSoftware {
        repo_did: String,
        slug: String,
        reply: Reply<Option<SoftwareRow>>,
    },
    MarkSoftware {
        mark: SoftwareMark,
        reply: Reply<()>,
    },
    GetPurl {
        repo_did: String,
        purl: String,
        reply: Reply<Option<PurlRow>>,
    },
    MarkPurl {
        repo_did: String,
        purl: String,
        software_slug: String,
        uri: String,
        cid: String,
        reply: Reply<()>,
    },
    PendingAtproto {
        repo_did: String,
        limit: usize,
        reply: Reply<Vec<String>>,
    },
    MarkCveAtproto {
        repo_did: String,
        cve_id: String,
        uri: String,
        cid: String,
        reply: Reply<()>,
    },
    Counts {
        repo_did: String,
        reply: Reply<Counts>,
    },
    ReplaceLinks {
        repo_did: String,
        src_uri: String,
        src_collection: String,
        src_rkey: String,
        src_cid: Option<String>,
        links: Vec<Link>,
        reply: Reply<()>,
    },
    Backlinks {
        repo_did: String,
        subject_uri: String,
        collection: Option<String>,
        path: Option<String>,
        limit: usize,
        reply: Reply<Vec<LinkRow>>,
    },
    Outgoing {
        repo_did: String,
        src_uri: String,
        reply: Reply<Vec<LinkRow>>,
    },
    ReleaseCandidates {
        repo_did: String,
        limit: usize,
        recheck_seconds: f64,
        after_slug: Option<String>,
        reply: Reply<Vec<ReleaseCandidate>>,
    },
    NormalizePurlSlugs {
        repo_did: String,
        reply: Reply<usize>,
    },
    GetSoftwareIdentity {
        repo_did: String,
        raw_slug: String,
        reply: Reply<Option<SoftwareIdentityRow>>,
    },
    MarkSoftwareIdentity {
        mark: SoftwareIdentityMark,
        reply: Reply<()>,
    },
    ListSoftwareIdentities {
        repo_did: String,
        reply: Reply<Vec<SoftwareIdentityRow>>,
    },
    GetProjectAlias {
        repo_did: String,
        alias_key: String,
        reply: Reply<Option<ProjectAliasRow>>,
    },
    MarkProjectAlias {
        mark: ProjectAliasMark,
        reply: Reply<()>,
    },
    ListProjectAliases {
        repo_did: String,
        reply: Reply<Vec<ProjectAliasRow>>,
    },
    GetProjectChannel {
        repo_did: String,
        project_slug: String,
        channel: String,
        reply: Reply<Option<ProjectChannelRow>>,
    },
    MarkProjectChannel {
        mark: ProjectChannelMark,
        reply: Reply<()>,
    },
    ListProjectChannels {
        repo_did: String,
        project_slug: String,
        reply: Reply<Vec<ProjectChannelRow>>,
    },
    GetReleaseArtifact {
        repo_did: String,
        source: String,
        package: String,
        version: String,
        url: String,
        reply: Reply<Option<ReleaseArtifactRow>>,
    },
    MarkReleaseArtifact {
        mark: ReleaseArtifactMark,
        reply: Reply<()>,
    },
    ListReleaseArtifacts {
        repo_did: String,
        source: String,
        package: String,
        version: String,
        reply: Reply<Vec<ReleaseArtifactRow>>,
    },
    GetReleaseManifest {
        repo_did: String,
        project_slug: String,
        manifest_key: String,
        reply: Reply<Option<ReleaseManifestRow>>,
    },
    MarkReleaseManifest {
        mark: ReleaseManifestMark,
        reply: Reply<()>,
    },
    ListReleaseManifests {
        repo_did: String,
        project_slug: String,
        reply: Reply<Vec<ReleaseManifestRow>>,
    },
    GetReleaseHistoryJob {
        repo_did: String,
        project_slug: String,
        version_raw: String,
        reply: Reply<Option<ReleaseHistoryJobRow>>,
    },
    MarkReleaseHistoryJob {
        mark: ReleaseHistoryJobMark,
        reply: Reply<()>,
    },
    ListReleaseHistoryJobs {
        repo_did: String,
        status: Option<String>,
        limit: usize,
        reply: Reply<Vec<ReleaseHistoryJobRow>>,
    },
    GetReleaseOsv {
        repo_did: String,
        purl: String,
        osv_id: String,
        reply: Reply<Option<ReleaseOsvRow>>,
    },
    MarkReleaseOsv {
        mark: ReleaseOsvMark,
        reply: Reply<()>,
    },
    ListReleaseOsv {
        repo_did: String,
        purl: String,
        reply: Reply<Vec<ReleaseOsvRow>>,
    },
    GetReleaseCveLink {
        repo_did: String,
        cve_id: String,
        project_slug: String,
        reply: Reply<Option<ReleaseCveLinkRow>>,
    },
    MarkReleaseCveLink {
        mark: ReleaseCveLinkMark,
        reply: Reply<()>,
    },
    ListReleaseCveLinks {
        repo_did: String,
        cve_id: String,
        reply: Reply<Vec<ReleaseCveLinkRow>>,
    },
    GetReleaseSourceState {
        repo_did: String,
        source: String,
        reply: Reply<Option<ReleaseSourceStateRow>>,
    },
    MarkReleaseSourceState {
        mark: ReleaseSourceStateMark,
        reply: Reply<()>,
    },
    ListReleaseSourceStates {
        repo_did: String,
        reply: Reply<Vec<ReleaseSourceStateRow>>,
    },
    AppendReleaseStatusEvent {
        mark: ReleaseStatusEventMark,
        reply: Reply<()>,
    },
    ListReleaseStatusEvents {
        repo_did: String,
        subject_uri: String,
        limit: usize,
        reply: Reply<Vec<ReleaseStatusEventRow>>,
    },
    GetReleaseProjectState {
        repo_did: String,
        slug: String,
        reply: Reply<Option<ReleaseProjectStateRow>>,
    },
    MarkReleaseProjectState {
        mark: ReleaseProjectStateMark,
        reply: Reply<()>,
    },
    ListReleaseProjectStates {
        repo_did: String,
        limit: usize,
        reply: Reply<Vec<ReleaseProjectStateRow>>,
    },
    GetReleaseVersionMeta {
        repo_did: String,
        project_slug: String,
        version: String,
        reply: Reply<Option<ReleaseVersionMetaRow>>,
    },
    MarkReleaseVersionMeta {
        mark: ReleaseVersionMetaMark,
        reply: Reply<()>,
    },
    ListReleaseVersionMeta {
        repo_did: String,
        project_slug: String,
        reply: Reply<Vec<ReleaseVersionMetaRow>>,
    },
    GetIdentityMigration {
        repo_did: String,
        phase: String,
        raw_slug: String,
        reply: Reply<Option<IdentityMigrationRow>>,
    },
    MarkIdentityMigration {
        mark: IdentityMigrationMark,
        reply: Reply<()>,
    },
    ListIdentityMigration {
        repo_did: String,
        status: Option<String>,
        limit: usize,
        reply: Reply<Vec<IdentityMigrationRow>>,
    },
    GetLinkRepair {
        repo_did: String,
        src_uri: String,
        reply: Reply<Option<LinkRepairRow>>,
    },
    MarkLinkRepair {
        mark: LinkRepairMark,
        reply: Reply<()>,
    },
    PendingLinkRepairs {
        limit: usize,
        reply: Reply<Vec<LinkRepairRow>>,
    },
    DeleteLinkRepair {
        repo_did: String,
        src_uri: String,
        reply: Reply<()>,
    },
    GetPublishError {
        repo_did: String,
        cve_id: String,
        reply: Reply<Option<PublishErrorRow>>,
    },
    MarkPublishError {
        mark: PublishErrorMark,
        reply: Reply<()>,
    },
    PendingPublishErrors {
        limit: usize,
        reply: Reply<Vec<PublishErrorRow>>,
    },
    DeletePublishError {
        repo_did: String,
        cve_id: String,
        reply: Reply<()>,
    },
    GetSourceHostState {
        host: String,
        reply: Reply<Option<SourceHostStateRow>>,
    },
    MarkSourceHostState {
        mark: SourceHostStateMark,
        reply: Reply<()>,
    },
    ListSourceHostStates {
        reply: Reply<Vec<SourceHostStateRow>>,
    },
    GetReleaseProject {
        repo_did: String,
        slug: String,
        reply: Reply<Option<ReleaseProjectRow>>,
    },
    ListReleaseProjectsForSlugs {
        repo_did: String,
        slugs: Vec<String>,
        reply: Reply<Vec<ReleaseProjectRow>>,
    },
    MarkReleaseProject {
        mark: ReleaseProjectMark,
        reply: Reply<()>,
    },
    GetReleaseVersion {
        repo_did: String,
        project_slug: String,
        version: String,
        reply: Reply<Option<ReleaseVersionRow>>,
    },
    ListReleaseVersionsForProject {
        repo_did: String,
        project_slug: String,
        reply: Reply<Vec<ReleaseVersionRow>>,
    },
    MarkReleaseVersion {
        mark: ReleaseVersionMark,
        reply: Reply<()>,
    },
    GetReleaseChannel {
        repo_did: String,
        project_slug: String,
        name: String,
        reply: Reply<Option<ReleaseChannelRow>>,
    },
    ListReleaseChannelsForProject {
        repo_did: String,
        project_slug: String,
        reply: Reply<Vec<ReleaseChannelRow>>,
    },
    MarkReleaseChannel {
        mark: ReleaseChannelMark,
        reply: Reply<()>,
    },
    GetReleaseStatus {
        repo_did: String,
        subject_uri: String,
        status: String,
        reply: Reply<Option<ReleaseStatusRow>>,
    },
    MarkReleaseStatus {
        mark: ReleaseStatusMark,
        reply: Reply<()>,
    },
    LoadRateBudget {
        repo_did: String,
        reply: Reply<Option<RateBudget>>,
    },
    PersistRateBudget {
        budget: RateBudget,
        reply: Reply<()>,
    },
    Commit(Reply<()>),
    Snapshot {
        path: PathBuf,
        reply: Reply<()>,
    },
    Close(Reply<()>),
}

impl DbHandle {
    pub async fn open(path: impl AsRef<Path>) -> Result<Self> {
        let path = path.as_ref().to_path_buf();
        let (tx, mut rx) = mpsc::channel(DB_QUEUE);
        let (ready_tx, ready_rx) = oneshot::channel();
        std::thread::Builder::new()
            .name("vuln-notif-db".to_owned())
            .spawn(move || match DbState::open(&path) {
                Ok(mut state) => {
                    if ready_tx.send(Ok(())).is_err() {
                        return;
                    }
                    while let Some(command) = rx.blocking_recv() {
                        if state.handle(command) {
                            break;
                        }
                    }
                }
                Err(error) => {
                    let _ = ready_tx.send(Err(error));
                }
            })
            .context("failed to spawn database thread")?;
        ready_rx
            .await
            .map_err(|_| anyhow!("database thread exited during open"))??;
        Ok(Self { tx })
    }

    pub async fn open_in_memory() -> Result<Self> {
        Self::open(":memory:").await
    }

    async fn call<T>(&self, command: impl FnOnce(Reply<T>) -> DbCmd) -> Result<T> {
        let (reply, response) = oneshot::channel();
        self.tx
            .send(command(reply))
            .await
            .map_err(|_| anyhow!("database actor stopped"))?;
        response
            .await
            .map_err(|_| anyhow!("database actor dropped reply"))?
    }

    pub async fn get_cursor(&self) -> Result<Option<String>> {
        self.call(DbCmd::GetCursor).await
    }

    pub async fn set_cursor(&self, cursor: impl Into<String>) -> Result<()> {
        let cursor = cursor.into();
        self.call(|reply| DbCmd::SetCursor { cursor, reply }).await
    }

    pub async fn upsert_cves(&self, repo_did: &str, cves: &[Value]) -> Result<(i64, i64, i64)> {
        let repo_did = repo_did.to_owned();
        let cves = cves.to_vec();
        self.call(|reply| DbCmd::UpsertCves {
            repo_did,
            cves,
            reply,
        })
        .await
    }

    pub async fn pending(&self, repo_did: &str, limit: usize, order: Order) -> Result<Vec<CveRow>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::Pending {
            repo_did,
            limit,
            order,
            reply,
        })
        .await
    }

    pub async fn mark_publication(&self, mark: PublicationMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkPublication { mark, reply })
            .await
    }

    pub async fn get_cve_record(
        &self,
        repo_did: &str,
        cve_id: &str,
    ) -> Result<Option<(String, String)>> {
        let repo_did = repo_did.to_owned();
        let cve_id = cve_id.to_owned();
        self.call(|reply| DbCmd::GetCveRecord {
            repo_did,
            cve_id,
            reply,
        })
        .await
    }

    pub async fn get_cve_data(&self, cve_id: &str) -> Result<Option<Value>> {
        let cve_id = cve_id.to_owned();
        self.call(|reply| DbCmd::GetCveData { cve_id, reply }).await
    }

    pub async fn get_software(&self, repo_did: &str, slug: &str) -> Result<Option<SoftwareRow>> {
        let repo_did = repo_did.to_owned();
        let slug = slug.to_owned();
        self.call(|reply| DbCmd::GetSoftware {
            repo_did,
            slug,
            reply,
        })
        .await
    }

    pub async fn mark_software(&self, mark: SoftwareMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkSoftware { mark, reply }).await
    }

    pub async fn get_purl(&self, repo_did: &str, purl: &str) -> Result<Option<PurlRow>> {
        let repo_did = repo_did.to_owned();
        let purl = purl.to_owned();
        self.call(|reply| DbCmd::GetPurl {
            repo_did,
            purl,
            reply,
        })
        .await
    }

    pub async fn mark_purl(
        &self,
        repo_did: &str,
        purl: &str,
        software_slug: &str,
        uri: &str,
        cid: &str,
    ) -> Result<()> {
        let repo_did = repo_did.to_owned();
        let purl = purl.to_owned();
        let software_slug = software_slug.to_owned();
        let uri = uri.to_owned();
        let cid = cid.to_owned();
        self.call(|reply| DbCmd::MarkPurl {
            repo_did,
            purl,
            software_slug,
            uri,
            cid,
            reply,
        })
        .await
    }

    pub async fn pending_atproto(&self, repo_did: &str, limit: usize) -> Result<Vec<String>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::PendingAtproto {
            repo_did,
            limit,
            reply,
        })
        .await
    }

    pub async fn mark_cve_atproto(
        &self,
        repo_did: &str,
        cve_id: &str,
        uri: &str,
        cid: &str,
    ) -> Result<()> {
        let repo_did = repo_did.to_owned();
        let cve_id = cve_id.to_owned();
        let uri = uri.to_owned();
        let cid = cid.to_owned();
        self.call(|reply| DbCmd::MarkCveAtproto {
            repo_did,
            cve_id,
            uri,
            cid,
            reply,
        })
        .await
    }

    pub async fn counts(&self, repo_did: &str) -> Result<Counts> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::Counts { repo_did, reply }).await
    }

    pub async fn replace_links(
        &self,
        repo_did: &str,
        src_uri: &str,
        src_collection: &str,
        src_rkey: &str,
        src_cid: Option<&str>,
        links: &[Link],
    ) -> Result<()> {
        let repo_did = repo_did.to_owned();
        let src_uri = src_uri.to_owned();
        let src_collection = src_collection.to_owned();
        let src_rkey = src_rkey.to_owned();
        let src_cid = src_cid.map(str::to_owned);
        let links = links.to_vec();
        self.call(|reply| DbCmd::ReplaceLinks {
            repo_did,
            src_uri,
            src_collection,
            src_rkey,
            src_cid,
            links,
            reply,
        })
        .await
    }

    pub async fn backlinks(
        &self,
        repo_did: &str,
        subject_uri: &str,
        collection: Option<&str>,
        path: Option<&str>,
        limit: usize,
    ) -> Result<Vec<LinkRow>> {
        let repo_did = repo_did.to_owned();
        let subject_uri = subject_uri.to_owned();
        let collection = collection.map(str::to_owned);
        let path = path.map(str::to_owned);
        self.call(|reply| DbCmd::Backlinks {
            repo_did,
            subject_uri,
            collection,
            path,
            limit,
            reply,
        })
        .await
    }

    pub async fn outgoing(&self, repo_did: &str, src_uri: &str) -> Result<Vec<LinkRow>> {
        let repo_did = repo_did.to_owned();
        let src_uri = src_uri.to_owned();
        self.call(|reply| DbCmd::Outgoing {
            repo_did,
            src_uri,
            reply,
        })
        .await
    }

    pub async fn release_candidates(
        &self,
        repo_did: &str,
        limit: usize,
        recheck_seconds: f64,
    ) -> Result<Vec<ReleaseCandidate>> {
        self.release_candidates_after(repo_did, limit, recheck_seconds, None)
            .await
    }

    /// Like [`DbHandle::release_candidates`], but resumes after `after_slug`
    /// so equal-timestamp groups rotate instead of starving later projects.
    pub async fn release_candidates_after(
        &self,
        repo_did: &str,
        limit: usize,
        recheck_seconds: f64,
        after_slug: Option<&str>,
    ) -> Result<Vec<ReleaseCandidate>> {
        let repo_did = repo_did.to_owned();
        let after_slug = after_slug.map(str::to_owned);
        self.call(|reply| DbCmd::ReleaseCandidates {
            repo_did,
            limit,
            recheck_seconds,
            after_slug,
            reply,
        })
        .await
    }

    pub async fn normalize_purl_slugs(&self, repo_did: &str) -> Result<usize> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::NormalizePurlSlugs { repo_did, reply })
            .await
    }

    pub async fn get_software_identity(
        &self,
        repo_did: &str,
        raw_slug: &str,
    ) -> Result<Option<SoftwareIdentityRow>> {
        let repo_did = repo_did.to_owned();
        let raw_slug = raw_slug.to_owned();
        self.call(|reply| DbCmd::GetSoftwareIdentity {
            repo_did,
            raw_slug,
            reply,
        })
        .await
    }

    pub async fn mark_software_identity(&self, mark: SoftwareIdentityMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkSoftwareIdentity { mark, reply })
            .await
    }

    pub async fn list_software_identities(
        &self,
        repo_did: &str,
    ) -> Result<Vec<SoftwareIdentityRow>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::ListSoftwareIdentities { repo_did, reply })
            .await
    }

    pub async fn get_project_alias(
        &self,
        repo_did: &str,
        alias_key: &str,
    ) -> Result<Option<ProjectAliasRow>> {
        let repo_did = repo_did.to_owned();
        let alias_key = alias_key.to_owned();
        self.call(|reply| DbCmd::GetProjectAlias {
            repo_did,
            alias_key,
            reply,
        })
        .await
    }

    pub async fn mark_project_alias(&self, mark: ProjectAliasMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkProjectAlias { mark, reply })
            .await
    }

    pub async fn list_project_aliases(&self, repo_did: &str) -> Result<Vec<ProjectAliasRow>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::ListProjectAliases { repo_did, reply })
            .await
    }

    pub async fn get_project_channel(
        &self,
        repo_did: &str,
        project_slug: &str,
        channel: &str,
    ) -> Result<Option<ProjectChannelRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        let channel = channel.to_owned();
        self.call(|reply| DbCmd::GetProjectChannel {
            repo_did,
            project_slug,
            channel,
            reply,
        })
        .await
    }

    pub async fn mark_project_channel(&self, mark: ProjectChannelMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkProjectChannel { mark, reply })
            .await
    }

    pub async fn list_project_channels(
        &self,
        repo_did: &str,
        project_slug: &str,
    ) -> Result<Vec<ProjectChannelRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        self.call(|reply| DbCmd::ListProjectChannels {
            repo_did,
            project_slug,
            reply,
        })
        .await
    }

    pub async fn get_release_artifact(
        &self,
        repo_did: &str,
        source: &str,
        package: &str,
        version: &str,
        url: &str,
    ) -> Result<Option<ReleaseArtifactRow>> {
        let repo_did = repo_did.to_owned();
        let source = source.to_owned();
        let package = package.to_owned();
        let version = version.to_owned();
        let url = url.to_owned();
        self.call(|reply| DbCmd::GetReleaseArtifact {
            repo_did,
            source,
            package,
            version,
            url,
            reply,
        })
        .await
    }

    pub async fn mark_release_artifact(&self, mark: ReleaseArtifactMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseArtifact { mark, reply })
            .await
    }

    pub async fn list_release_artifacts(
        &self,
        repo_did: &str,
        source: &str,
        package: &str,
        version: &str,
    ) -> Result<Vec<ReleaseArtifactRow>> {
        let repo_did = repo_did.to_owned();
        let source = source.to_owned();
        let package = package.to_owned();
        let version = version.to_owned();
        self.call(|reply| DbCmd::ListReleaseArtifacts {
            repo_did,
            source,
            package,
            version,
            reply,
        })
        .await
    }

    pub async fn get_release_manifest(
        &self,
        repo_did: &str,
        project_slug: &str,
        manifest_key: &str,
    ) -> Result<Option<ReleaseManifestRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        let manifest_key = manifest_key.to_owned();
        self.call(|reply| DbCmd::GetReleaseManifest {
            repo_did,
            project_slug,
            manifest_key,
            reply,
        })
        .await
    }

    pub async fn mark_release_manifest(&self, mark: ReleaseManifestMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseManifest { mark, reply })
            .await
    }

    pub async fn list_release_manifests(
        &self,
        repo_did: &str,
        project_slug: &str,
    ) -> Result<Vec<ReleaseManifestRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        self.call(|reply| DbCmd::ListReleaseManifests {
            repo_did,
            project_slug,
            reply,
        })
        .await
    }

    pub async fn get_release_history_job(
        &self,
        repo_did: &str,
        project_slug: &str,
        version_raw: &str,
    ) -> Result<Option<ReleaseHistoryJobRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        let version_raw = version_raw.to_owned();
        self.call(|reply| DbCmd::GetReleaseHistoryJob {
            repo_did,
            project_slug,
            version_raw,
            reply,
        })
        .await
    }

    pub async fn mark_release_history_job(&self, mark: ReleaseHistoryJobMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseHistoryJob { mark, reply })
            .await
    }

    pub async fn list_release_history_jobs(
        &self,
        repo_did: &str,
        status: Option<&str>,
        limit: usize,
    ) -> Result<Vec<ReleaseHistoryJobRow>> {
        let repo_did = repo_did.to_owned();
        let status = status.map(str::to_owned);
        self.call(|reply| DbCmd::ListReleaseHistoryJobs {
            repo_did,
            status,
            limit,
            reply,
        })
        .await
    }

    pub async fn get_release_osv(
        &self,
        repo_did: &str,
        purl: &str,
        osv_id: &str,
    ) -> Result<Option<ReleaseOsvRow>> {
        let repo_did = repo_did.to_owned();
        let purl = purl.to_owned();
        let osv_id = osv_id.to_owned();
        self.call(|reply| DbCmd::GetReleaseOsv {
            repo_did,
            purl,
            osv_id,
            reply,
        })
        .await
    }

    pub async fn mark_release_osv(&self, mark: ReleaseOsvMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseOsv { mark, reply })
            .await
    }

    pub async fn list_release_osv(&self, repo_did: &str, purl: &str) -> Result<Vec<ReleaseOsvRow>> {
        let repo_did = repo_did.to_owned();
        let purl = purl.to_owned();
        self.call(|reply| DbCmd::ListReleaseOsv {
            repo_did,
            purl,
            reply,
        })
        .await
    }

    pub async fn get_release_cve_link(
        &self,
        repo_did: &str,
        cve_id: &str,
        project_slug: &str,
    ) -> Result<Option<ReleaseCveLinkRow>> {
        let repo_did = repo_did.to_owned();
        let cve_id = cve_id.to_owned();
        let project_slug = project_slug.to_owned();
        self.call(|reply| DbCmd::GetReleaseCveLink {
            repo_did,
            cve_id,
            project_slug,
            reply,
        })
        .await
    }

    pub async fn mark_release_cve_link(&self, mark: ReleaseCveLinkMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseCveLink { mark, reply })
            .await
    }

    pub async fn list_release_cve_links(
        &self,
        repo_did: &str,
        cve_id: &str,
    ) -> Result<Vec<ReleaseCveLinkRow>> {
        let repo_did = repo_did.to_owned();
        let cve_id = cve_id.to_owned();
        self.call(|reply| DbCmd::ListReleaseCveLinks {
            repo_did,
            cve_id,
            reply,
        })
        .await
    }

    pub async fn get_release_source_state(
        &self,
        repo_did: &str,
        source: &str,
    ) -> Result<Option<ReleaseSourceStateRow>> {
        let repo_did = repo_did.to_owned();
        let source = source.to_owned();
        self.call(|reply| DbCmd::GetReleaseSourceState {
            repo_did,
            source,
            reply,
        })
        .await
    }

    pub async fn mark_release_source_state(&self, mark: ReleaseSourceStateMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseSourceState { mark, reply })
            .await
    }

    pub async fn list_release_source_states(
        &self,
        repo_did: &str,
    ) -> Result<Vec<ReleaseSourceStateRow>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::ListReleaseSourceStates { repo_did, reply })
            .await
    }

    pub async fn append_release_status_event(&self, mark: ReleaseStatusEventMark) -> Result<()> {
        self.call(|reply| DbCmd::AppendReleaseStatusEvent { mark, reply })
            .await
    }

    pub async fn list_release_status_events(
        &self,
        repo_did: &str,
        subject_uri: &str,
        limit: usize,
    ) -> Result<Vec<ReleaseStatusEventRow>> {
        let repo_did = repo_did.to_owned();
        let subject_uri = subject_uri.to_owned();
        self.call(|reply| DbCmd::ListReleaseStatusEvents {
            repo_did,
            subject_uri,
            limit,
            reply,
        })
        .await
    }

    pub async fn get_release_project_state(
        &self,
        repo_did: &str,
        slug: &str,
    ) -> Result<Option<ReleaseProjectStateRow>> {
        let repo_did = repo_did.to_owned();
        let slug = slug.to_owned();
        self.call(|reply| DbCmd::GetReleaseProjectState {
            repo_did,
            slug,
            reply,
        })
        .await
    }

    pub async fn mark_release_project_state(&self, mark: ReleaseProjectStateMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseProjectState { mark, reply })
            .await
    }

    pub async fn list_release_project_states(
        &self,
        repo_did: &str,
        limit: usize,
    ) -> Result<Vec<ReleaseProjectStateRow>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::ListReleaseProjectStates {
            repo_did,
            limit,
            reply,
        })
        .await
    }

    pub async fn get_release_version_meta(
        &self,
        repo_did: &str,
        project_slug: &str,
        version: &str,
    ) -> Result<Option<ReleaseVersionMetaRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        let version = version.to_owned();
        self.call(|reply| DbCmd::GetReleaseVersionMeta {
            repo_did,
            project_slug,
            version,
            reply,
        })
        .await
    }

    pub async fn mark_release_version_meta(&self, mark: ReleaseVersionMetaMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseVersionMeta { mark, reply })
            .await
    }

    pub async fn list_release_version_meta(
        &self,
        repo_did: &str,
        project_slug: &str,
    ) -> Result<Vec<ReleaseVersionMetaRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        self.call(|reply| DbCmd::ListReleaseVersionMeta {
            repo_did,
            project_slug,
            reply,
        })
        .await
    }

    pub async fn get_identity_migration(
        &self,
        repo_did: &str,
        phase: &str,
        raw_slug: &str,
    ) -> Result<Option<IdentityMigrationRow>> {
        let repo_did = repo_did.to_owned();
        let phase = phase.to_owned();
        let raw_slug = raw_slug.to_owned();
        self.call(|reply| DbCmd::GetIdentityMigration {
            repo_did,
            phase,
            raw_slug,
            reply,
        })
        .await
    }

    pub async fn mark_identity_migration(&self, mark: IdentityMigrationMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkIdentityMigration { mark, reply })
            .await
    }

    pub async fn list_identity_migration(
        &self,
        repo_did: &str,
        status: Option<&str>,
        limit: usize,
    ) -> Result<Vec<IdentityMigrationRow>> {
        let repo_did = repo_did.to_owned();
        let status = status.map(str::to_owned);
        self.call(|reply| DbCmd::ListIdentityMigration {
            repo_did,
            status,
            limit,
            reply,
        })
        .await
    }

    pub async fn get_link_repair(
        &self,
        repo_did: &str,
        src_uri: &str,
    ) -> Result<Option<LinkRepairRow>> {
        let repo_did = repo_did.to_owned();
        let src_uri = src_uri.to_owned();
        self.call(|reply| DbCmd::GetLinkRepair {
            repo_did,
            src_uri,
            reply,
        })
        .await
    }

    pub async fn mark_link_repair(&self, mark: LinkRepairMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkLinkRepair { mark, reply })
            .await
    }

    pub async fn pending_link_repairs(&self, limit: usize) -> Result<Vec<LinkRepairRow>> {
        self.call(|reply| DbCmd::PendingLinkRepairs { limit, reply })
            .await
    }

    pub async fn delete_link_repair(&self, repo_did: &str, src_uri: &str) -> Result<()> {
        let repo_did = repo_did.to_owned();
        let src_uri = src_uri.to_owned();
        self.call(|reply| DbCmd::DeleteLinkRepair {
            repo_did,
            src_uri,
            reply,
        })
        .await
    }

    pub async fn get_publish_error(
        &self,
        repo_did: &str,
        cve_id: &str,
    ) -> Result<Option<PublishErrorRow>> {
        let repo_did = repo_did.to_owned();
        let cve_id = cve_id.to_owned();
        self.call(|reply| DbCmd::GetPublishError {
            repo_did,
            cve_id,
            reply,
        })
        .await
    }

    pub async fn mark_publish_error(&self, mark: PublishErrorMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkPublishError { mark, reply })
            .await
    }

    pub async fn pending_publish_errors(&self, limit: usize) -> Result<Vec<PublishErrorRow>> {
        self.call(|reply| DbCmd::PendingPublishErrors { limit, reply })
            .await
    }

    pub async fn delete_publish_error(&self, repo_did: &str, cve_id: &str) -> Result<()> {
        let repo_did = repo_did.to_owned();
        let cve_id = cve_id.to_owned();
        self.call(|reply| DbCmd::DeletePublishError {
            repo_did,
            cve_id,
            reply,
        })
        .await
    }

    pub async fn get_source_host_state(&self, host: &str) -> Result<Option<SourceHostStateRow>> {
        let host = host.to_owned();
        self.call(|reply| DbCmd::GetSourceHostState { host, reply })
            .await
    }

    pub async fn mark_source_host_state(&self, mark: SourceHostStateMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkSourceHostState { mark, reply })
            .await
    }

    pub async fn list_source_host_states(&self) -> Result<Vec<SourceHostStateRow>> {
        self.call(|reply| DbCmd::ListSourceHostStates { reply })
            .await
    }

    pub async fn get_release_project(
        &self,
        repo_did: &str,
        slug: &str,
    ) -> Result<Option<ReleaseProjectRow>> {
        let repo_did = repo_did.to_owned();
        let slug = slug.to_owned();
        self.call(|reply| DbCmd::GetReleaseProject {
            repo_did,
            slug,
            reply,
        })
        .await
    }

    pub async fn mark_release_project(&self, mark: ReleaseProjectMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseProject { mark, reply })
            .await
    }

    /// Release projects for `slugs` in one query, ordered by slug.
    pub async fn list_release_projects_for_slugs(
        &self,
        repo_did: &str,
        slugs: &[String],
    ) -> Result<Vec<ReleaseProjectRow>> {
        let repo_did = repo_did.to_owned();
        let slugs = slugs.to_vec();
        self.call(|reply| DbCmd::ListReleaseProjectsForSlugs {
            repo_did,
            slugs,
            reply,
        })
        .await
    }

    pub async fn get_release_version(
        &self,
        repo_did: &str,
        project_slug: &str,
        version: &str,
    ) -> Result<Option<ReleaseVersionRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        let version = version.to_owned();
        self.call(|reply| DbCmd::GetReleaseVersion {
            repo_did,
            project_slug,
            version,
            reply,
        })
        .await
    }

    pub async fn mark_release_version(&self, mark: ReleaseVersionMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseVersion { mark, reply })
            .await
    }

    /// Every version row for one canonical project, ordered by version.
    pub async fn list_release_versions_for_project(
        &self,
        repo_did: &str,
        project_slug: &str,
    ) -> Result<Vec<ReleaseVersionRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        self.call(|reply| DbCmd::ListReleaseVersionsForProject {
            repo_did,
            project_slug,
            reply,
        })
        .await
    }

    pub async fn get_release_channel(
        &self,
        repo_did: &str,
        project_slug: &str,
        name: &str,
    ) -> Result<Option<ReleaseChannelRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        let name = name.to_owned();
        self.call(|reply| DbCmd::GetReleaseChannel {
            repo_did,
            project_slug,
            name,
            reply,
        })
        .await
    }

    pub async fn mark_release_channel(&self, mark: ReleaseChannelMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseChannel { mark, reply })
            .await
    }

    /// Every channel row for one canonical project, ordered by name.
    pub async fn list_release_channels_for_project(
        &self,
        repo_did: &str,
        project_slug: &str,
    ) -> Result<Vec<ReleaseChannelRow>> {
        let repo_did = repo_did.to_owned();
        let project_slug = project_slug.to_owned();
        self.call(|reply| DbCmd::ListReleaseChannelsForProject {
            repo_did,
            project_slug,
            reply,
        })
        .await
    }

    pub async fn get_release_status(
        &self,
        repo_did: &str,
        subject_uri: &str,
        status: &str,
    ) -> Result<Option<ReleaseStatusRow>> {
        let repo_did = repo_did.to_owned();
        let subject_uri = subject_uri.to_owned();
        let status = status.to_owned();
        self.call(|reply| DbCmd::GetReleaseStatus {
            repo_did,
            subject_uri,
            status,
            reply,
        })
        .await
    }

    pub async fn mark_release_status(&self, mark: ReleaseStatusMark) -> Result<()> {
        self.call(|reply| DbCmd::MarkReleaseStatus { mark, reply })
            .await
    }

    pub async fn load_rate_budget(&self, repo_did: &str) -> Result<Option<RateBudget>> {
        let repo_did = repo_did.to_owned();
        self.call(|reply| DbCmd::LoadRateBudget { repo_did, reply })
            .await
    }

    pub async fn persist_rate_budget(&self, budget: RateBudget) -> Result<()> {
        self.call(|reply| DbCmd::PersistRateBudget { budget, reply })
            .await
    }

    pub async fn commit(&self) -> Result<()> {
        self.call(DbCmd::Commit).await
    }

    pub async fn snapshot(&self, path: impl Into<PathBuf>) -> Result<()> {
        let path = path.into();
        self.call(|reply| DbCmd::Snapshot { path, reply }).await
    }

    pub async fn close(&self) -> Result<()> {
        self.call(DbCmd::Close).await
    }
}

const UPSERT_CVE_SQL: &str = "INSERT INTO cves(id, last_modified, data, updated_at) \
     VALUES(?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET \
     last_modified=excluded.last_modified, data=excluded.data, \
     updated_at=excluded.updated_at";

const MARK_PUBLICATION_SQL: &str = "INSERT INTO publications(\
     repo_did, cve_id, status, uri, cid, checked_at, published_at, \
     blob_cid, blob_bytes, record_bytes, mode\
     ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) \
     ON CONFLICT(repo_did, cve_id) DO UPDATE SET \
     status=excluded.status, \
     uri=COALESCE(excluded.uri, publications.uri), \
     cid=COALESCE(excluded.cid, publications.cid), \
     checked_at=excluded.checked_at, \
     published_at=CASE WHEN excluded.status='pending' \
     THEN publications.published_at ELSE excluded.published_at END, \
     blob_cid=COALESCE(excluded.blob_cid, publications.blob_cid), \
     blob_bytes=COALESCE(excluded.blob_bytes, publications.blob_bytes), \
     record_bytes=COALESCE(excluded.record_bytes, publications.record_bytes), \
     mode=COALESCE(excluded.mode, publications.mode)";

const MARK_SOFTWARE_SQL: &str = "INSERT INTO software(\
     repo_did, slug, part, vendor, product, project_uri, project_cid, \
     software_uri, software_cid, status, updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,?,'created',?) \
     ON CONFLICT(repo_did, slug) DO UPDATE SET \
     project_uri=excluded.project_uri, project_cid=excluded.project_cid, \
     software_uri=excluded.software_uri, software_cid=excluded.software_cid, \
     status='created', updated_at=excluded.updated_at";

const MARK_PURL_SQL: &str = "INSERT INTO software_purls(\
     repo_did, purl, software_slug, purl_uri, purl_cid, status, updated_at\
     ) VALUES(?,?,?,?,?,'created',?) \
     ON CONFLICT(repo_did, purl) DO UPDATE SET \
     purl_uri=excluded.purl_uri, purl_cid=excluded.purl_cid, \
     status='created', updated_at=excluded.updated_at";

const MARK_CVE_ATPROTO_SQL: &str = "INSERT INTO cve_atproto(\
     repo_did, cve_id, status, uri, cid, updated_at\
     ) VALUES(?,?,'created',?,?,?) \
     ON CONFLICT(repo_did, cve_id) DO UPDATE SET \
     status='created', uri=excluded.uri, cid=excluded.cid, \
     updated_at=excluded.updated_at";

const MARK_RELEASE_PROJECT_SQL: &str = "INSERT INTO release_projects(\
     repo_did, slug, purl, system, latest_version, latest_version_raw, \
     project_uri, project_cid, manifest_uri, manifest_cid, version_uri, \
     version_cid, channel_uri, channel_cid, status, updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,'created',?) \
     ON CONFLICT(repo_did, slug) DO UPDATE SET \
     purl=excluded.purl, system=excluded.system, \
     latest_version=excluded.latest_version, \
     latest_version_raw=excluded.latest_version_raw, \
     project_uri=excluded.project_uri, project_cid=excluded.project_cid, \
     manifest_uri=excluded.manifest_uri, manifest_cid=excluded.manifest_cid, \
     version_uri=excluded.version_uri, version_cid=excluded.version_cid, \
     channel_uri=excluded.channel_uri, channel_cid=excluded.channel_cid, \
     status='created', updated_at=excluded.updated_at";

const MARK_RELEASE_VERSION_SQL: &str = "INSERT INTO release_versions(\
     repo_did, project_slug, version, version_raw, rkey, uri, cid, \
     manifest_uri, manifest_cid, status, updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,?,'created',?) \
     ON CONFLICT(repo_did, project_slug, version) DO UPDATE SET \
     version_raw=excluded.version_raw, rkey=excluded.rkey, \
     uri=excluded.uri, cid=excluded.cid, \
     manifest_uri=excluded.manifest_uri, manifest_cid=excluded.manifest_cid, \
     status='created', updated_at=excluded.updated_at";

const MARK_RELEASE_CHANNEL_SQL: &str = "INSERT INTO release_channels(\
     repo_did, project_slug, name, rkey, uri, cid, version_uri, \
     version_cid, status, updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,'created',?) \
     ON CONFLICT(repo_did, project_slug, name) DO UPDATE SET \
     rkey=excluded.rkey, uri=excluded.uri, cid=excluded.cid, \
     version_uri=excluded.version_uri, version_cid=excluded.version_cid, \
     status='created', updated_at=excluded.updated_at";

const MARK_RELEASE_STATUS_SQL: &str = "INSERT INTO release_status(\
     repo_did, subject_uri, status, rkey, uri, cid, updated_at\
     ) VALUES(?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, subject_uri, status) DO UPDATE SET \
     rkey=excluded.rkey, uri=excluded.uri, cid=excluded.cid, \
     updated_at=excluded.updated_at";

const MARK_SOFTWARE_IDENTITY_SQL: &str = "INSERT INTO software_identity(\
     repo_did, raw_slug, canonical_slug, identity_key, source, confidence, updated_at\
     ) VALUES(?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, raw_slug) DO UPDATE SET \
     canonical_slug=excluded.canonical_slug, identity_key=excluded.identity_key, \
     source=excluded.source, confidence=excluded.confidence, \
     updated_at=excluded.updated_at";

const MARK_PROJECT_ALIAS_SQL: &str = "INSERT INTO project_aliases(\
     repo_did, alias_key, canonical_slug, source, updated_at\
     ) VALUES(?,?,?,?,?) \
     ON CONFLICT(repo_did, alias_key) DO UPDATE SET \
     canonical_slug=excluded.canonical_slug, source=excluded.source, \
     updated_at=excluded.updated_at";

const MARK_PROJECT_CHANNEL_SQL: &str = "INSERT INTO project_channels(\
     repo_did, project_slug, channel, latest_version, eol_at, status, updated_at\
     ) VALUES(?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, project_slug, channel) DO UPDATE SET \
     latest_version=excluded.latest_version, eol_at=excluded.eol_at, \
     status=excluded.status, updated_at=excluded.updated_at";

const MARK_RELEASE_ARTIFACT_SQL: &str = "INSERT INTO release_artifacts(\
     repo_did, source, package, version, file_name, url, sha256, cid, size, \
     mime_type, metadata_json, fetched_at\
     ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, source, package, version, url) DO UPDATE SET \
     file_name=excluded.file_name, sha256=excluded.sha256, cid=excluded.cid, \
     size=excluded.size, mime_type=excluded.mime_type, \
     metadata_json=excluded.metadata_json, fetched_at=excluded.fetched_at";

const MARK_RELEASE_MANIFEST_SQL: &str = "INSERT INTO release_manifests(\
     repo_did, project_slug, manifest_key, uri, cid, artifacts_json, created_at\
     ) VALUES(?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, project_slug, manifest_key) DO UPDATE SET \
     uri=excluded.uri, cid=excluded.cid, artifacts_json=excluded.artifacts_json";

const MARK_RELEASE_HISTORY_JOB_SQL: &str = "INSERT INTO release_history_jobs(\
     repo_did, project_slug, version_raw, version, source, purl, status, \
     attempts, error, updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, project_slug, version_raw) DO UPDATE SET \
     version=excluded.version, source=excluded.source, purl=excluded.purl, \
     status=excluded.status, attempts=excluded.attempts, error=excluded.error, \
     updated_at=excluded.updated_at";

const MARK_RELEASE_OSV_SQL: &str = "INSERT INTO release_osv(\
     repo_did, purl, osv_id, aliases_json, affected_json, modified, fetched_at\
     ) VALUES(?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, purl, osv_id) DO UPDATE SET \
     aliases_json=excluded.aliases_json, affected_json=excluded.affected_json, \
     modified=excluded.modified, fetched_at=excluded.fetched_at";

const MARK_RELEASE_CVE_LINK_SQL: &str = "INSERT INTO release_cve_links(\
     repo_did, cve_id, project_slug, version_uri, version_cid, channel_uri, \
     channel_cid, manifest_uri, manifest_cid, version_label, affected_ranges, \
     updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, cve_id, project_slug) DO UPDATE SET \
     version_uri=excluded.version_uri, version_cid=excluded.version_cid, \
     channel_uri=excluded.channel_uri, channel_cid=excluded.channel_cid, \
     manifest_uri=excluded.manifest_uri, manifest_cid=excluded.manifest_cid, \
     version_label=excluded.version_label, affected_ranges=excluded.affected_ranges, \
     updated_at=excluded.updated_at";

const MARK_RELEASE_SOURCE_STATE_SQL: &str = "INSERT INTO release_source_state(\
     repo_did, source, cursor, etag, updated_at\
     ) VALUES(?,?,?,?,?) \
     ON CONFLICT(repo_did, source) DO UPDATE SET \
     cursor=excluded.cursor, etag=excluded.etag, updated_at=excluded.updated_at";

const APPEND_RELEASE_STATUS_EVENT_SQL: &str = "INSERT OR IGNORE INTO release_status_events(\
     repo_did, subject_uri, rkey, status, kind, reason, cid, created_at\
     ) VALUES(?,?,?,?,?,?,?,?)";

const MARK_RELEASE_PROJECT_STATE_SQL: &str = "INSERT INTO release_project_state(\
     repo_did, slug, canonical_purl, source, raw_versions_json, checked_at, \
     unsupported_reason\
     ) VALUES(?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, slug) DO UPDATE SET \
     canonical_purl=excluded.canonical_purl, source=excluded.source, \
     raw_versions_json=excluded.raw_versions_json, checked_at=excluded.checked_at, \
     unsupported_reason=excluded.unsupported_reason";

const MARK_RELEASE_VERSION_META_SQL: &str = "INSERT INTO release_version_meta(\
     repo_did, project_slug, version, source, published_at, raw_version, \
     artifact_cid, artifact_size\
     ) VALUES(?,?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, project_slug, version) DO UPDATE SET \
     source=excluded.source, published_at=excluded.published_at, \
     raw_version=excluded.raw_version, artifact_cid=excluded.artifact_cid, \
     artifact_size=excluded.artifact_size";

const MARK_IDENTITY_MIGRATION_SQL: &str = "INSERT INTO identity_migration(\
     repo_did, phase, raw_slug, canonical_slug, action, status, attempts, \
     error, updated_at\
     ) VALUES(?,?,?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, phase, raw_slug) DO UPDATE SET \
     canonical_slug=excluded.canonical_slug, action=excluded.action, \
     status=excluded.status, attempts=excluded.attempts, error=excluded.error, \
     updated_at=excluded.updated_at";

const MARK_LINK_REPAIR_SQL: &str = "INSERT INTO link_repairs(\
     repo_did, src_uri, src_cid, collection, record_json, attempts, last_error, \
     next_retry_at\
     ) VALUES(?,?,?,?,?,?,?,?) \
     ON CONFLICT(repo_did, src_uri) DO UPDATE SET \
     src_cid=excluded.src_cid, collection=excluded.collection, \
     record_json=excluded.record_json, attempts=excluded.attempts, \
     last_error=excluded.last_error, next_retry_at=excluded.next_retry_at";

const MARK_PUBLISH_ERROR_SQL: &str = "INSERT INTO publish_errors(\
     repo_did, cve_id, attempts, last_error, next_retry_at\
     ) VALUES(?,?,?,?,?) \
     ON CONFLICT(repo_did, cve_id) DO UPDATE SET \
     attempts=excluded.attempts, last_error=excluded.last_error, \
     next_retry_at=excluded.next_retry_at";

const MARK_SOURCE_HOST_STATE_SQL: &str = "INSERT INTO source_host_state(\
     host, window_start, requests, blocked_until\
     ) VALUES(?,?,?,?) \
     ON CONFLICT(host) DO UPDATE SET \
     window_start=excluded.window_start, requests=excluded.requests, \
     blocked_until=excluded.blocked_until";

const NORMALIZE_PURL_SLUGS_SQL: &str = "UPDATE software_purls SET \
     software_slug=substr(software_slug, \
     length(rtrim(software_slug, replace(software_slug, '/', ''))) + 1), \
     updated_at=? \
     WHERE repo_did=? AND instr(software_slug, 'at://') = 1";

struct DbState {
    conn: Connection,
    in_tx: bool,
}

impl DbState {
    fn open(path: &Path) -> Result<Self> {
        let conn = if path == Path::new(":memory:") {
            Connection::open_in_memory().context("open in-memory cache")?
        } else {
            if let Some(parent) = path.parent()
                && !parent.as_os_str().is_empty()
            {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("create cache directory {}", parent.display()))?;
            }
            Connection::open(path).with_context(|| format!("open cache {}", path.display()))?
        };
        conn.execute_batch("PRAGMA journal_mode=DELETE; PRAGMA synchronous=FULL;")
            .context("configure cache pragmas")?;
        conn.execute_batch(SCHEMA)
            .context("initialize cache schema")?;
        conn.execute_batch(RATE_BUDGET_SCHEMA)
            .context("initialize rate budget schema")?;
        Ok(Self { conn, in_tx: false })
    }

    fn begin(&mut self) -> Result<()> {
        if !self.in_tx {
            self.conn.execute_batch("BEGIN IMMEDIATE")?;
            self.in_tx = true;
        }
        Ok(())
    }

    fn rollback(&mut self) {
        if self.in_tx {
            let _ = self.conn.execute_batch("ROLLBACK");
            self.in_tx = false;
        }
    }

    fn commit_checked(&mut self) -> Result<()> {
        if self.in_tx {
            if let Err(error) = self.conn.execute_batch("COMMIT") {
                self.rollback();
                return Err(error.into());
            }
            self.in_tx = false;
        }
        Ok(())
    }

    fn guarded<T>(&mut self, operation: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
        match operation(self) {
            Ok(value) => Ok(value),
            Err(error) => {
                self.rollback();
                Err(error)
            }
        }
    }

    fn handle(&mut self, command: DbCmd) -> bool {
        match command {
            DbCmd::GetCursor(reply) => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT value FROM meta WHERE key='last_mod_end'",
                        [],
                        |row| row.get(0),
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::SetCursor { cursor, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        "INSERT INTO meta(key, value) VALUES('last_mod_end', ?) \
                         ON CONFLICT(key) DO UPDATE SET value=excluded.value",
                        params![cursor],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::UpsertCves {
                repo_did,
                cves,
                reply,
            } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    let now = created_at(Utc::now());
                    let mut new = 0i64;
                    let mut updated = 0i64;
                    let mut already_done = 0i64;
                    for cve in &cves {
                        let Some(cve_id) = cve.get("id").and_then(Value::as_str) else {
                            continue;
                        };
                        let exists = state
                            .conn
                            .query_row("SELECT 1 FROM cves WHERE id=?", params![cve_id], |_| Ok(()))
                            .optional()?
                            .is_some();
                        let publication: Option<String> = state
                            .conn
                            .query_row(
                                "SELECT status FROM publications WHERE repo_did=? AND cve_id=?",
                                params![repo_did, cve_id],
                                |row| row.get(0),
                            )
                            .optional()?;
                        if !exists {
                            new += 1;
                        } else if publication.as_deref().is_none()
                            || publication.as_deref() == Some("pending")
                        {
                            updated += 1;
                        } else {
                            already_done += 1;
                        }
                        let last_modified = cve.get("lastModified").and_then(Value::as_str);
                        state.conn.execute(
                            UPSERT_CVE_SQL,
                            params![cve_id, last_modified, cache_json(cve), now],
                        )?;
                    }
                    Ok((new, updated, already_done))
                });
                let _ = reply.send(result);
            }
            DbCmd::Pending {
                repo_did,
                limit,
                order,
                reply,
            } => {
                let mut sql = format!(
                    "SELECT c.id, c.data FROM cves c \
                     LEFT JOIN publications p ON p.repo_did=? AND p.cve_id=c.id \
                     WHERE p.status IS NULL OR p.status='pending' \
                     ORDER BY {}",
                    order.as_sql()
                );
                if limit > 0 {
                    sql.push_str(" LIMIT ?");
                }
                let result = (|| -> Result<Vec<CveRow>> {
                    let mut statement = self.conn.prepare(&sql)?;
                    let map_row = |row: &Row<'_>| -> rusqlite::Result<CveRow> {
                        Ok(CveRow {
                            id: row.get(0)?,
                            data: row.get(1)?,
                        })
                    };
                    let rows = if limit > 0 {
                        statement
                            .query_map(params![repo_did, limit as i64], map_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    } else {
                        statement
                            .query_map(params![repo_did], map_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    };
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::MarkPublication { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    let now = created_at(Utc::now());
                    state.conn.execute(
                        MARK_PUBLICATION_SQL,
                        params![
                            mark.repo_did,
                            mark.cve_id,
                            mark.status,
                            mark.uri,
                            mark.cid,
                            now,
                            now,
                            mark.blob_cid,
                            mark.blob_bytes,
                            mark.record_bytes,
                            mark.mode,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetCveRecord {
                repo_did,
                cve_id,
                reply,
            } => {
                let result = (|| -> Result<Option<(String, String)>> {
                    let row: Option<(Option<String>, Option<String>)> = self
                        .conn
                        .query_row(
                            "SELECT uri, cid FROM publications WHERE repo_did=? AND cve_id=? \
                             AND status IN ('created','present')",
                            params![repo_did, cve_id],
                            |row| Ok((row.get(0)?, row.get(1)?)),
                        )
                        .optional()?;
                    Ok(row.and_then(|(uri, cid)| match (uri, cid) {
                        (Some(uri), Some(cid)) if !uri.is_empty() && !cid.is_empty() => {
                            Some((uri, cid))
                        }
                        _ => None,
                    }))
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetCveData { cve_id, reply } => {
                let result = (|| -> Result<Option<Value>> {
                    let data: Option<String> = self
                        .conn
                        .query_row("SELECT data FROM cves WHERE id=?", params![cve_id], |row| {
                            row.get(0)
                        })
                        .optional()?;
                    match data {
                        Some(data) => Ok(Some(serde_json::from_str(&data)?)),
                        None => Ok(None),
                    }
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetSoftware {
                repo_did,
                slug,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, slug, part, vendor, product, project_uri, \
                         project_cid, software_uri, software_cid, status, updated_at \
                         FROM software WHERE repo_did=? AND slug=?",
                        params![repo_did, slug],
                        software_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkSoftware { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_SOFTWARE_SQL,
                        params![
                            mark.repo_did,
                            mark.slug,
                            mark.part,
                            mark.vendor,
                            mark.product,
                            mark.project_uri,
                            mark.project_cid,
                            mark.software_uri,
                            mark.software_cid,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetPurl {
                repo_did,
                purl,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, purl, software_slug, purl_uri, purl_cid, \
                         status, updated_at FROM software_purls \
                         WHERE repo_did=? AND purl=?",
                        params![repo_did, purl],
                        purl_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkPurl {
                repo_did,
                purl,
                software_slug,
                uri,
                cid,
                reply,
            } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_PURL_SQL,
                        params![
                            repo_did,
                            purl,
                            software_slug,
                            uri,
                            cid,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::PendingAtproto {
                repo_did,
                limit,
                reply,
            } => {
                let result = (|| -> Result<Vec<String>> {
                    let mut sql = String::from(
                        "SELECT c.id FROM cves c \
                         JOIN publications p ON p.repo_did=? AND p.cve_id=c.id \
                         LEFT JOIN cve_atproto a ON a.repo_did=? AND a.cve_id=c.id \
                         WHERE p.status IN ('created','present') \
                         AND (a.status IS NULL OR a.status='pending') \
                         ORDER BY c.last_modified DESC, c.id DESC",
                    );
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = if limit > 0 {
                        statement
                            .query_map(params![repo_did, repo_did, limit as i64], |row| row.get(0))?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    } else {
                        statement
                            .query_map(params![repo_did, repo_did], |row| row.get(0))?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    };
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::MarkCveAtproto {
                repo_did,
                cve_id,
                uri,
                cid,
                reply,
            } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_CVE_ATPROTO_SQL,
                        params![repo_did, cve_id, uri, cid, created_at(Utc::now()),],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::Counts { repo_did, reply } => {
                let result = self.counts(&repo_did);
                let _ = reply.send(result);
            }
            DbCmd::ReplaceLinks {
                repo_did,
                src_uri,
                src_collection,
                src_rkey,
                src_cid,
                links,
                reply,
            } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    let now = created_at(Utc::now());
                    state
                        .conn
                        .execute("DELETE FROM links WHERE src_uri=?", params![src_uri])?;
                    let mut statement = state.conn.prepare(
                        "INSERT OR REPLACE INTO links(\
                         repo_did, src_uri, src_collection, src_rkey, src_cid, path, \
                         subject_uri, subject_cid, indexed_at\
                         ) VALUES(?,?,?,?,?,?,?,?,?)",
                    )?;
                    for link in &links {
                        statement.execute(params![
                            repo_did,
                            src_uri,
                            src_collection,
                            src_rkey,
                            src_cid,
                            link.path,
                            link.subject_uri,
                            link.subject_cid,
                            now,
                        ])?;
                    }
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::Backlinks {
                repo_did,
                subject_uri,
                collection,
                path,
                limit,
                reply,
            } => {
                let result = (|| -> Result<Vec<LinkRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, src_uri, src_collection, src_rkey, src_cid, \
                         path, subject_uri, subject_cid, indexed_at \
                         FROM links WHERE repo_did=? AND subject_uri=?",
                    );
                    let mut values: Vec<SqlValue> = vec![repo_did.into(), subject_uri.into()];
                    if let Some(collection) = collection {
                        sql.push_str(" AND src_collection=?");
                        values.push(collection.into());
                    }
                    if let Some(path) = path {
                        sql.push_str(" AND path=?");
                        values.push(path.into());
                    }
                    sql.push_str(" ORDER BY indexed_at DESC, src_uri LIMIT ?");
                    values.push((limit as i64).into());
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = statement
                        .query_map(params_from_iter(values), link_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::Outgoing {
                repo_did,
                src_uri,
                reply,
            } => {
                let result = (|| -> Result<Vec<LinkRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, src_uri, src_collection, src_rkey, src_cid, \
                         path, subject_uri, subject_cid, indexed_at \
                         FROM links WHERE repo_did=? AND src_uri=? \
                         ORDER BY path, subject_uri",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, src_uri], link_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::ReleaseCandidates {
                repo_did,
                limit,
                recheck_seconds,
                after_slug,
                reply,
            } => {
                let result = self.release_candidates(
                    &repo_did,
                    limit,
                    recheck_seconds,
                    after_slug.as_deref(),
                );
                let _ = reply.send(result);
            }
            DbCmd::NormalizePurlSlugs { repo_did, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    let updated = state.conn.execute(
                        NORMALIZE_PURL_SLUGS_SQL,
                        params![created_at(Utc::now()), repo_did],
                    )?;
                    Ok(updated)
                });
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseProject {
                repo_did,
                slug,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, slug, purl, system, latest_version, \
                         latest_version_raw, project_uri, project_cid, manifest_uri, \
                         manifest_cid, version_uri, version_cid, channel_uri, \
                         channel_cid, status, updated_at \
                         FROM release_projects WHERE repo_did=? AND slug=?",
                        params![repo_did, slug],
                        release_project_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::ListReleaseProjectsForSlugs {
                repo_did,
                slugs,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseProjectRow>> {
                    if slugs.is_empty() {
                        return Ok(Vec::new());
                    }
                    let placeholders = vec!["?"; slugs.len()].join(", ");
                    let sql = format!(
                        "SELECT repo_did, slug, purl, system, latest_version, \
                         latest_version_raw, project_uri, project_cid, manifest_uri, \
                         manifest_cid, version_uri, version_cid, channel_uri, \
                         channel_cid, status, updated_at \
                         FROM release_projects WHERE repo_did=? AND slug IN ({placeholders}) \
                         ORDER BY slug"
                    );
                    let mut statement = self.conn.prepare(&sql)?;
                    let params = std::iter::once(SqlValue::Text(repo_did))
                        .chain(slugs.into_iter().map(SqlValue::Text));
                    let rows = statement
                        .query_map(params_from_iter(params), release_project_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::MarkReleaseProject { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_PROJECT_SQL,
                        params![
                            mark.repo_did,
                            mark.slug,
                            mark.purl,
                            mark.system,
                            mark.latest_version,
                            mark.latest_version_raw,
                            mark.project_uri,
                            mark.project_cid,
                            mark.manifest_uri,
                            mark.manifest_cid,
                            mark.version_uri,
                            mark.version_cid,
                            mark.channel_uri,
                            mark.channel_cid,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseVersion {
                repo_did,
                project_slug,
                version,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, project_slug, version, version_raw, rkey, \
                         uri, cid, manifest_uri, manifest_cid, status, updated_at \
                         FROM release_versions \
                         WHERE repo_did=? AND project_slug=? AND version=?",
                        params![repo_did, project_slug, version],
                        release_version_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::ListReleaseVersionsForProject {
                repo_did,
                project_slug,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseVersionRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, project_slug, version, version_raw, rkey, \
                         uri, cid, manifest_uri, manifest_cid, status, updated_at \
                         FROM release_versions \
                         WHERE repo_did=? AND project_slug=? ORDER BY version",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, project_slug], release_version_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::MarkReleaseVersion { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_VERSION_SQL,
                        params![
                            mark.repo_did,
                            mark.project_slug,
                            mark.version,
                            mark.version_raw,
                            mark.rkey,
                            mark.uri,
                            mark.cid,
                            mark.manifest_uri,
                            mark.manifest_cid,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseChannel {
                repo_did,
                project_slug,
                name,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, project_slug, name, rkey, uri, cid, \
                         version_uri, version_cid, status, updated_at \
                         FROM release_channels \
                         WHERE repo_did=? AND project_slug=? AND name=?",
                        params![repo_did, project_slug, name],
                        release_channel_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::ListReleaseChannelsForProject {
                repo_did,
                project_slug,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseChannelRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, project_slug, name, rkey, uri, cid, \
                         version_uri, version_cid, status, updated_at \
                         FROM release_channels \
                         WHERE repo_did=? AND project_slug=? ORDER BY name",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, project_slug], release_channel_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::MarkReleaseChannel { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_CHANNEL_SQL,
                        params![
                            mark.repo_did,
                            mark.project_slug,
                            mark.name,
                            mark.rkey,
                            mark.uri,
                            mark.cid,
                            mark.version_uri,
                            mark.version_cid,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseStatus {
                repo_did,
                subject_uri,
                status,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, subject_uri, status, rkey, uri, cid, updated_at \
                         FROM release_status \
                         WHERE repo_did=? AND subject_uri=? AND status=?",
                        params![repo_did, subject_uri, status],
                        release_status_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseStatus { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_STATUS_SQL,
                        params![
                            mark.repo_did,
                            mark.subject_uri,
                            mark.status,
                            mark.rkey,
                            mark.uri,
                            mark.cid,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetSoftwareIdentity {
                repo_did,
                raw_slug,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, raw_slug, canonical_slug, identity_key, source, \
                         confidence, updated_at FROM software_identity \
                         WHERE repo_did=? AND raw_slug=?",
                        params![repo_did, raw_slug],
                        software_identity_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkSoftwareIdentity { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_SOFTWARE_IDENTITY_SQL,
                        params![
                            mark.repo_did,
                            mark.raw_slug,
                            mark.canonical_slug,
                            mark.identity_key,
                            mark.source,
                            mark.confidence,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListSoftwareIdentities { repo_did, reply } => {
                let result = (|| -> Result<Vec<SoftwareIdentityRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, raw_slug, canonical_slug, identity_key, source, \
                         confidence, updated_at FROM software_identity \
                         WHERE repo_did=? ORDER BY canonical_slug, raw_slug",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did], software_identity_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetProjectAlias {
                repo_did,
                alias_key,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, alias_key, canonical_slug, source, updated_at \
                         FROM project_aliases WHERE repo_did=? AND alias_key=?",
                        params![repo_did, alias_key],
                        project_alias_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkProjectAlias { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_PROJECT_ALIAS_SQL,
                        params![
                            mark.repo_did,
                            mark.alias_key,
                            mark.canonical_slug,
                            mark.source,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListProjectAliases { repo_did, reply } => {
                let result = (|| -> Result<Vec<ProjectAliasRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, alias_key, canonical_slug, source, updated_at \
                         FROM project_aliases WHERE repo_did=? ORDER BY alias_key",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did], project_alias_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetProjectChannel {
                repo_did,
                project_slug,
                channel,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, project_slug, channel, latest_version, eol_at, \
                         status, updated_at FROM project_channels \
                         WHERE repo_did=? AND project_slug=? AND channel=?",
                        params![repo_did, project_slug, channel],
                        project_channel_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkProjectChannel { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_PROJECT_CHANNEL_SQL,
                        params![
                            mark.repo_did,
                            mark.project_slug,
                            mark.channel,
                            mark.latest_version,
                            mark.eol_at,
                            mark.status,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListProjectChannels {
                repo_did,
                project_slug,
                reply,
            } => {
                let result = (|| -> Result<Vec<ProjectChannelRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, project_slug, channel, latest_version, eol_at, \
                         status, updated_at FROM project_channels \
                         WHERE repo_did=? AND project_slug=? ORDER BY channel",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, project_slug], project_channel_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseArtifact {
                repo_did,
                source,
                package,
                version,
                url,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, source, package, version, file_name, url, sha256, \
                         cid, size, mime_type, metadata_json, fetched_at \
                         FROM release_artifacts \
                         WHERE repo_did=? AND source=? AND package=? AND version=? AND url=?",
                        params![repo_did, source, package, version, url],
                        release_artifact_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseArtifact { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_ARTIFACT_SQL,
                        params![
                            mark.repo_did,
                            mark.source,
                            mark.package,
                            mark.version,
                            mark.file_name,
                            mark.url,
                            mark.sha256,
                            mark.cid,
                            mark.size,
                            mark.mime_type,
                            mark.metadata_json,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseArtifacts {
                repo_did,
                source,
                package,
                version,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseArtifactRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, source, package, version, file_name, url, sha256, \
                         cid, size, mime_type, metadata_json, fetched_at \
                         FROM release_artifacts \
                         WHERE repo_did=? AND source=? AND package=? AND version=? \
                         ORDER BY file_name, url",
                    )?;
                    let rows = statement
                        .query_map(
                            params![repo_did, source, package, version],
                            release_artifact_from_row,
                        )?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseManifest {
                repo_did,
                project_slug,
                manifest_key,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, project_slug, manifest_key, uri, cid, \
                         artifacts_json, created_at FROM release_manifests \
                         WHERE repo_did=? AND project_slug=? AND manifest_key=?",
                        params![repo_did, project_slug, manifest_key],
                        release_manifest_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseManifest { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_MANIFEST_SQL,
                        params![
                            mark.repo_did,
                            mark.project_slug,
                            mark.manifest_key,
                            mark.uri,
                            mark.cid,
                            mark.artifacts_json,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseManifests {
                repo_did,
                project_slug,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseManifestRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, project_slug, manifest_key, uri, cid, \
                         artifacts_json, created_at FROM release_manifests \
                         WHERE repo_did=? AND project_slug=? ORDER BY manifest_key",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, project_slug], release_manifest_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseHistoryJob {
                repo_did,
                project_slug,
                version_raw,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, project_slug, version_raw, version, source, purl, \
                         status, attempts, error, updated_at FROM release_history_jobs \
                         WHERE repo_did=? AND project_slug=? AND version_raw=?",
                        params![repo_did, project_slug, version_raw],
                        release_history_job_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseHistoryJob { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_HISTORY_JOB_SQL,
                        params![
                            mark.repo_did,
                            mark.project_slug,
                            mark.version_raw,
                            mark.version,
                            mark.source,
                            mark.purl,
                            mark.status,
                            mark.attempts,
                            mark.error,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseHistoryJobs {
                repo_did,
                status,
                limit,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseHistoryJobRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, project_slug, version_raw, version, source, purl, \
                         status, attempts, error, updated_at FROM release_history_jobs \
                         WHERE repo_did=?",
                    );
                    let mut values: Vec<SqlValue> = vec![repo_did.into()];
                    if let Some(status) = status {
                        sql.push_str(" AND status=?");
                        values.push(status.into());
                    }
                    sql.push_str(" ORDER BY updated_at, project_slug, version_raw");
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                        values.push((limit as i64).into());
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = statement
                        .query_map(params_from_iter(values), release_history_job_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseOsv {
                repo_did,
                purl,
                osv_id,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, purl, osv_id, aliases_json, affected_json, \
                         modified, fetched_at FROM release_osv \
                         WHERE repo_did=? AND purl=? AND osv_id=?",
                        params![repo_did, purl, osv_id],
                        release_osv_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseOsv { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_OSV_SQL,
                        params![
                            mark.repo_did,
                            mark.purl,
                            mark.osv_id,
                            mark.aliases_json,
                            mark.affected_json,
                            mark.modified,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseOsv {
                repo_did,
                purl,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseOsvRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, purl, osv_id, aliases_json, affected_json, \
                         modified, fetched_at FROM release_osv \
                         WHERE repo_did=? AND purl=? ORDER BY osv_id",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, purl], release_osv_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseCveLink {
                repo_did,
                cve_id,
                project_slug,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, cve_id, project_slug, version_uri, version_cid, \
                         channel_uri, channel_cid, manifest_uri, manifest_cid, \
                         version_label, affected_ranges, updated_at FROM release_cve_links \
                         WHERE repo_did=? AND cve_id=? AND project_slug=?",
                        params![repo_did, cve_id, project_slug],
                        release_cve_link_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseCveLink { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_CVE_LINK_SQL,
                        params![
                            mark.repo_did,
                            mark.cve_id,
                            mark.project_slug,
                            mark.version_uri,
                            mark.version_cid,
                            mark.channel_uri,
                            mark.channel_cid,
                            mark.manifest_uri,
                            mark.manifest_cid,
                            mark.version_label,
                            mark.affected_ranges,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseCveLinks {
                repo_did,
                cve_id,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseCveLinkRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, cve_id, project_slug, version_uri, version_cid, \
                         channel_uri, channel_cid, manifest_uri, manifest_cid, \
                         version_label, affected_ranges, updated_at FROM release_cve_links \
                         WHERE repo_did=? AND cve_id=? ORDER BY project_slug",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did, cve_id], release_cve_link_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseSourceState {
                repo_did,
                source,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, source, cursor, etag, updated_at \
                         FROM release_source_state WHERE repo_did=? AND source=?",
                        params![repo_did, source],
                        release_source_state_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseSourceState { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_SOURCE_STATE_SQL,
                        params![
                            mark.repo_did,
                            mark.source,
                            mark.cursor,
                            mark.etag,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseSourceStates { repo_did, reply } => {
                let result = (|| -> Result<Vec<ReleaseSourceStateRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, source, cursor, etag, updated_at \
                         FROM release_source_state WHERE repo_did=? ORDER BY source",
                    )?;
                    let rows = statement
                        .query_map(params![repo_did], release_source_state_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::AppendReleaseStatusEvent { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    let created_at = mark.created_at.unwrap_or_else(|| created_at(Utc::now()));
                    state.conn.execute(
                        APPEND_RELEASE_STATUS_EVENT_SQL,
                        params![
                            mark.repo_did,
                            mark.subject_uri,
                            mark.rkey,
                            mark.status,
                            mark.kind,
                            mark.reason,
                            mark.cid,
                            created_at,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseStatusEvents {
                repo_did,
                subject_uri,
                limit,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseStatusEventRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, subject_uri, rkey, status, kind, reason, cid, \
                         created_at FROM release_status_events \
                         WHERE repo_did=? AND subject_uri=? ORDER BY created_at, rkey",
                    );
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = if limit > 0 {
                        statement
                            .query_map(
                                params![repo_did, subject_uri, limit as i64],
                                release_status_event_from_row,
                            )?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    } else {
                        statement
                            .query_map(
                                params![repo_did, subject_uri],
                                release_status_event_from_row,
                            )?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    };
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseProjectState {
                repo_did,
                slug,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, slug, canonical_purl, source, raw_versions_json, \
                         checked_at, unsupported_reason FROM release_project_state \
                         WHERE repo_did=? AND slug=?",
                        params![repo_did, slug],
                        release_project_state_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseProjectState { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_PROJECT_STATE_SQL,
                        params![
                            mark.repo_did,
                            mark.slug,
                            mark.canonical_purl,
                            mark.source,
                            mark.raw_versions_json,
                            mark.checked_at,
                            mark.unsupported_reason,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseProjectStates {
                repo_did,
                limit,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseProjectStateRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, slug, canonical_purl, source, raw_versions_json, \
                         checked_at, unsupported_reason FROM release_project_state \
                         WHERE repo_did=? ORDER BY checked_at IS NOT NULL, checked_at, slug",
                    );
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = if limit > 0 {
                        statement
                            .query_map(
                                params![repo_did, limit as i64],
                                release_project_state_from_row,
                            )?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    } else {
                        statement
                            .query_map(params![repo_did], release_project_state_from_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    };
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetReleaseVersionMeta {
                repo_did,
                project_slug,
                version,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, project_slug, version, source, published_at, \
                         raw_version, artifact_cid, artifact_size FROM release_version_meta \
                         WHERE repo_did=? AND project_slug=? AND version=?",
                        params![repo_did, project_slug, version],
                        release_version_meta_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkReleaseVersionMeta { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_RELEASE_VERSION_META_SQL,
                        params![
                            mark.repo_did,
                            mark.project_slug,
                            mark.version,
                            mark.source,
                            mark.published_at,
                            mark.raw_version,
                            mark.artifact_cid,
                            mark.artifact_size,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListReleaseVersionMeta {
                repo_did,
                project_slug,
                reply,
            } => {
                let result = (|| -> Result<Vec<ReleaseVersionMetaRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT repo_did, project_slug, version, source, published_at, \
                         raw_version, artifact_cid, artifact_size FROM release_version_meta \
                         WHERE repo_did=? AND project_slug=? ORDER BY version",
                    )?;
                    let rows = statement
                        .query_map(
                            params![repo_did, project_slug],
                            release_version_meta_from_row,
                        )?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetIdentityMigration {
                repo_did,
                phase,
                raw_slug,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, phase, raw_slug, canonical_slug, action, status, \
                         attempts, error, updated_at FROM identity_migration \
                         WHERE repo_did=? AND phase=? AND raw_slug=?",
                        params![repo_did, phase, raw_slug],
                        identity_migration_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkIdentityMigration { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_IDENTITY_MIGRATION_SQL,
                        params![
                            mark.repo_did,
                            mark.phase,
                            mark.raw_slug,
                            mark.canonical_slug,
                            mark.action,
                            mark.status,
                            mark.attempts,
                            mark.error,
                            created_at(Utc::now()),
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListIdentityMigration {
                repo_did,
                status,
                limit,
                reply,
            } => {
                let result = (|| -> Result<Vec<IdentityMigrationRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, phase, raw_slug, canonical_slug, action, status, \
                         attempts, error, updated_at FROM identity_migration \
                         WHERE repo_did=?",
                    );
                    let mut values: Vec<SqlValue> = vec![repo_did.into()];
                    if let Some(status) = status {
                        sql.push_str(" AND status=?");
                        values.push(status.into());
                    }
                    sql.push_str(" ORDER BY phase, raw_slug");
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                        values.push((limit as i64).into());
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = statement
                        .query_map(params_from_iter(values), identity_migration_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::GetLinkRepair {
                repo_did,
                src_uri,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, src_uri, src_cid, collection, record_json, attempts, \
                         last_error, next_retry_at FROM link_repairs \
                         WHERE repo_did=? AND src_uri=?",
                        params![repo_did, src_uri],
                        link_repair_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkLinkRepair { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_LINK_REPAIR_SQL,
                        params![
                            mark.repo_did,
                            mark.src_uri,
                            mark.src_cid,
                            mark.collection,
                            mark.record_json,
                            mark.attempts,
                            mark.last_error,
                            mark.next_retry_at,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::PendingLinkRepairs { limit, reply } => {
                let result = (|| -> Result<Vec<LinkRepairRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, src_uri, src_cid, collection, record_json, attempts, \
                         last_error, next_retry_at FROM link_repairs \
                         ORDER BY next_retry_at IS NOT NULL, next_retry_at, src_uri",
                    );
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = if limit > 0 {
                        statement
                            .query_map(params![limit as i64], link_repair_from_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    } else {
                        statement
                            .query_map([], link_repair_from_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    };
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::DeleteLinkRepair {
                repo_did,
                src_uri,
                reply,
            } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        "DELETE FROM link_repairs WHERE repo_did=? AND src_uri=?",
                        params![repo_did, src_uri],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetPublishError {
                repo_did,
                cve_id,
                reply,
            } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, cve_id, attempts, last_error, next_retry_at \
                         FROM publish_errors WHERE repo_did=? AND cve_id=?",
                        params![repo_did, cve_id],
                        publish_error_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkPublishError { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_PUBLISH_ERROR_SQL,
                        params![
                            mark.repo_did,
                            mark.cve_id,
                            mark.attempts,
                            mark.last_error,
                            mark.next_retry_at,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::PendingPublishErrors { limit, reply } => {
                let result = (|| -> Result<Vec<PublishErrorRow>> {
                    let mut sql = String::from(
                        "SELECT repo_did, cve_id, attempts, last_error, next_retry_at \
                         FROM publish_errors \
                         ORDER BY next_retry_at IS NOT NULL, next_retry_at, cve_id",
                    );
                    if limit > 0 {
                        sql.push_str(" LIMIT ?");
                    }
                    let mut statement = self.conn.prepare(&sql)?;
                    let rows = if limit > 0 {
                        statement
                            .query_map(params![limit as i64], publish_error_from_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    } else {
                        statement
                            .query_map([], publish_error_from_row)?
                            .collect::<rusqlite::Result<Vec<_>>>()?
                    };
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::DeletePublishError {
                repo_did,
                cve_id,
                reply,
            } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        "DELETE FROM publish_errors WHERE repo_did=? AND cve_id=?",
                        params![repo_did, cve_id],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::GetSourceHostState { host, reply } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT host, window_start, requests, blocked_until \
                         FROM source_host_state WHERE host=?",
                        params![host],
                        source_host_state_from_row,
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::MarkSourceHostState { mark, reply } => {
                let result = self.guarded(|state| {
                    state.begin()?;
                    state.conn.execute(
                        MARK_SOURCE_HOST_STATE_SQL,
                        params![
                            mark.host,
                            mark.window_start,
                            mark.requests,
                            mark.blocked_until,
                        ],
                    )?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::ListSourceHostStates { reply } => {
                let result = (|| -> Result<Vec<SourceHostStateRow>> {
                    let mut statement = self.conn.prepare(
                        "SELECT host, window_start, requests, blocked_until \
                         FROM source_host_state ORDER BY host",
                    )?;
                    let rows = statement
                        .query_map([], source_host_state_from_row)?
                        .collect::<rusqlite::Result<Vec<_>>>()?;
                    Ok(rows)
                })();
                let _ = reply.send(result);
            }
            DbCmd::LoadRateBudget { repo_did, reply } => {
                let result = self
                    .conn
                    .query_row(
                        "SELECT repo_did, hour_start, hour_points, day_start, \
                         day_points, updated_at FROM rate_budget WHERE repo_did=?",
                        params![repo_did],
                        |row| {
                            Ok(RateBudget {
                                repo_did: row.get(0)?,
                                hour_start: row.get(1)?,
                                hour_points: row.get(2)?,
                                day_start: row.get(3)?,
                                day_points: row.get(4)?,
                                updated_at: row.get(5)?,
                            })
                        },
                    )
                    .optional();
                let _ = reply.send(result.map_err(Into::into));
            }
            DbCmd::PersistRateBudget { budget, reply } => {
                let result = self
                    .guarded(|state| {
                        state.begin()?;
                        state.conn.execute(
                            "INSERT INTO rate_budget(\
                         repo_did, hour_start, hour_points, day_start, day_points, updated_at\
                         ) VALUES(?,?,?,?,?,?) ON CONFLICT(repo_did) DO UPDATE SET \
                         hour_start=excluded.hour_start, hour_points=excluded.hour_points, \
                         day_start=excluded.day_start, day_points=excluded.day_points, \
                         updated_at=excluded.updated_at",
                            params![
                                budget.repo_did,
                                budget.hour_start,
                                budget.hour_points,
                                budget.day_start,
                                budget.day_points,
                                budget.updated_at,
                            ],
                        )?;
                        Ok(())
                    })
                    .and_then(|()| self.commit_checked());
                let _ = reply.send(result);
            }
            DbCmd::Commit(reply) => {
                let result = self.commit_checked();
                let _ = reply.send(result);
            }
            DbCmd::Snapshot { path, reply } => {
                let result = self.commit_checked().and_then(|()| {
                    if path.exists() {
                        std::fs::remove_file(&path)
                            .with_context(|| format!("remove snapshot {}", path.display()))?;
                    }
                    let path = path.to_string_lossy().to_string();
                    self.conn.execute("VACUUM INTO ?1", params![path])?;
                    Ok(())
                });
                let _ = reply.send(result);
            }
            DbCmd::Close(reply) => {
                let result = self.commit_checked();
                let _ = reply.send(result);
                return true;
            }
        }
        false
    }

    fn counts(&mut self, repo_did: &str) -> Result<Counts> {
        let total: i64 = self
            .conn
            .query_row("SELECT COUNT(*) FROM cves", [], |row| row.get(0))?;
        let mut counts = Counts {
            total,
            ..Counts::default()
        };
        let mut statement = self.conn.prepare(
            "SELECT status, COUNT(*) AS n FROM publications WHERE repo_did=? GROUP BY status",
        )?;
        let rows = statement.query_map(params![repo_did], |row| {
            Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)?))
        })?;
        for row in rows {
            let (status, value) = row?;
            match status.as_str() {
                "pending" => counts.pending = value,
                "present" => counts.present = value,
                "created" => counts.created = value,
                "skipped" => counts.skipped = value,
                _ => {}
            }
        }
        let done = counts.present + counts.created + counts.skipped;
        counts.pending = total - done;
        Ok(counts)
    }

    fn release_candidates(
        &mut self,
        repo_did: &str,
        limit: usize,
        recheck_seconds: f64,
        after_slug: Option<&str>,
    ) -> Result<Vec<ReleaseCandidate>> {
        // Old caches store a full AT-URI in `software_purls.software_slug`; take
        // the rkey tail so the canonical join works before the one-time
        // normalization migration runs.
        let canonical = "COALESCE(i.canonical_slug, s.slug)";
        let purl_slug = "CASE WHEN instr(p.software_slug, 'at://') = 1 \
             THEN substr(p.software_slug, \
             length(rtrim(p.software_slug, replace(p.software_slug, '/', ''))) + 1) \
             ELSE p.software_slug END";
        let checked = "COALESCE(ps.checked_at, r.updated_at)";
        let mut sql = format!(
            "SELECT {canonical} AS canonical_slug, MIN(s.vendor), MIN(s.product), \
             MIN(s.project_uri), MIN(s.project_cid), GROUP_CONCAT(p.purl, '|'), \
             r.latest_version, r.updated_at, {checked} AS last_checked \
             FROM software s \
             LEFT JOIN software_identity i ON i.repo_did=s.repo_did \
             AND i.raw_slug=s.slug \
             LEFT JOIN software_purls p ON p.repo_did=s.repo_did \
             AND {purl_slug}={canonical} \
             LEFT JOIN release_projects r ON r.repo_did=s.repo_did \
             AND r.slug={canonical} \
             LEFT JOIN release_project_state ps ON ps.repo_did=s.repo_did \
             AND ps.slug={canonical} \
             WHERE s.repo_did=? AND s.status='created' "
        );
        let mut values: Vec<SqlValue> = vec![repo_did.to_owned().into()];
        if recheck_seconds > 0.0 {
            let cutoff = created_at(
                Utc::now() - chrono::Duration::microseconds((recheck_seconds * 1_000_000.0) as i64),
            );
            sql.push_str(&format!("AND ({checked} IS NULL OR {checked} < ?) "));
            values.push(cutoff.into());
        }
        sql.push_str(&format!("GROUP BY {canonical} "));
        if let Some(after_slug) = after_slug {
            sql.push_str(&format!(
                "ORDER BY last_checked IS NOT NULL, last_checked, \
                 {canonical} > ? DESC, {canonical} ASC "
            ));
            values.push(after_slug.to_owned().into());
        } else {
            sql.push_str(&format!(
                "ORDER BY last_checked IS NOT NULL, last_checked, {canonical} ASC "
            ));
        }
        if limit > 0 {
            sql.push_str("LIMIT ?");
            values.push((limit as i64).into());
        }
        let mut statement = self.conn.prepare(&sql)?;
        let rows = statement
            .query_map(params_from_iter(values), |row| {
                let purls: Option<String> = row.get(5)?;
                let mut purls: Vec<String> = purls
                    .map(|raw| {
                        raw.split('|')
                            .filter(|purl| !purl.is_empty())
                            .map(str::to_owned)
                            .collect()
                    })
                    .unwrap_or_default();
                purls.sort();
                purls.dedup();
                Ok(ReleaseCandidate {
                    slug: row.get(0)?,
                    vendor: row.get(1)?,
                    product: row.get(2)?,
                    project_uri: row.get(3)?,
                    project_cid: row.get(4)?,
                    purls,
                    latest_version: row.get(6)?,
                    release_updated_at: row.get(7)?,
                })
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        Ok(rows)
    }
}

fn software_identity_from_row(row: &Row<'_>) -> rusqlite::Result<SoftwareIdentityRow> {
    Ok(SoftwareIdentityRow {
        repo_did: row.get(0)?,
        raw_slug: row.get(1)?,
        canonical_slug: row.get(2)?,
        identity_key: row.get(3)?,
        source: row.get(4)?,
        confidence: row.get(5)?,
        updated_at: row.get(6)?,
    })
}

fn project_alias_from_row(row: &Row<'_>) -> rusqlite::Result<ProjectAliasRow> {
    Ok(ProjectAliasRow {
        repo_did: row.get(0)?,
        alias_key: row.get(1)?,
        canonical_slug: row.get(2)?,
        source: row.get(3)?,
        updated_at: row.get(4)?,
    })
}

fn project_channel_from_row(row: &Row<'_>) -> rusqlite::Result<ProjectChannelRow> {
    Ok(ProjectChannelRow {
        repo_did: row.get(0)?,
        project_slug: row.get(1)?,
        channel: row.get(2)?,
        latest_version: row.get(3)?,
        eol_at: row.get(4)?,
        status: row.get(5)?,
        updated_at: row.get(6)?,
    })
}

fn release_artifact_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseArtifactRow> {
    Ok(ReleaseArtifactRow {
        repo_did: row.get(0)?,
        source: row.get(1)?,
        package: row.get(2)?,
        version: row.get(3)?,
        file_name: row.get(4)?,
        url: row.get(5)?,
        sha256: row.get(6)?,
        cid: row.get(7)?,
        size: row.get(8)?,
        mime_type: row.get(9)?,
        metadata_json: row.get(10)?,
        fetched_at: row.get(11)?,
    })
}

fn release_manifest_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseManifestRow> {
    Ok(ReleaseManifestRow {
        repo_did: row.get(0)?,
        project_slug: row.get(1)?,
        manifest_key: row.get(2)?,
        uri: row.get(3)?,
        cid: row.get(4)?,
        artifacts_json: row.get(5)?,
        created_at: row.get(6)?,
    })
}

fn release_history_job_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseHistoryJobRow> {
    Ok(ReleaseHistoryJobRow {
        repo_did: row.get(0)?,
        project_slug: row.get(1)?,
        version_raw: row.get(2)?,
        version: row.get(3)?,
        source: row.get(4)?,
        purl: row.get(5)?,
        status: row.get(6)?,
        attempts: row.get(7)?,
        error: row.get(8)?,
        updated_at: row.get(9)?,
    })
}

fn release_osv_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseOsvRow> {
    Ok(ReleaseOsvRow {
        repo_did: row.get(0)?,
        purl: row.get(1)?,
        osv_id: row.get(2)?,
        aliases_json: row.get(3)?,
        affected_json: row.get(4)?,
        modified: row.get(5)?,
        fetched_at: row.get(6)?,
    })
}

fn release_cve_link_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseCveLinkRow> {
    Ok(ReleaseCveLinkRow {
        repo_did: row.get(0)?,
        cve_id: row.get(1)?,
        project_slug: row.get(2)?,
        version_uri: row.get(3)?,
        version_cid: row.get(4)?,
        channel_uri: row.get(5)?,
        channel_cid: row.get(6)?,
        manifest_uri: row.get(7)?,
        manifest_cid: row.get(8)?,
        version_label: row.get(9)?,
        affected_ranges: row.get(10)?,
        updated_at: row.get(11)?,
    })
}

fn release_source_state_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseSourceStateRow> {
    Ok(ReleaseSourceStateRow {
        repo_did: row.get(0)?,
        source: row.get(1)?,
        cursor: row.get(2)?,
        etag: row.get(3)?,
        updated_at: row.get(4)?,
    })
}

fn release_status_event_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseStatusEventRow> {
    Ok(ReleaseStatusEventRow {
        repo_did: row.get(0)?,
        subject_uri: row.get(1)?,
        rkey: row.get(2)?,
        status: row.get(3)?,
        kind: row.get(4)?,
        reason: row.get(5)?,
        cid: row.get(6)?,
        created_at: row.get(7)?,
    })
}

fn release_project_state_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseProjectStateRow> {
    Ok(ReleaseProjectStateRow {
        repo_did: row.get(0)?,
        slug: row.get(1)?,
        canonical_purl: row.get(2)?,
        source: row.get(3)?,
        raw_versions_json: row.get(4)?,
        checked_at: row.get(5)?,
        unsupported_reason: row.get(6)?,
    })
}

fn release_version_meta_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseVersionMetaRow> {
    Ok(ReleaseVersionMetaRow {
        repo_did: row.get(0)?,
        project_slug: row.get(1)?,
        version: row.get(2)?,
        source: row.get(3)?,
        published_at: row.get(4)?,
        raw_version: row.get(5)?,
        artifact_cid: row.get(6)?,
        artifact_size: row.get(7)?,
    })
}

fn identity_migration_from_row(row: &Row<'_>) -> rusqlite::Result<IdentityMigrationRow> {
    Ok(IdentityMigrationRow {
        repo_did: row.get(0)?,
        phase: row.get(1)?,
        raw_slug: row.get(2)?,
        canonical_slug: row.get(3)?,
        action: row.get(4)?,
        status: row.get(5)?,
        attempts: row.get(6)?,
        error: row.get(7)?,
        updated_at: row.get(8)?,
    })
}

fn link_repair_from_row(row: &Row<'_>) -> rusqlite::Result<LinkRepairRow> {
    Ok(LinkRepairRow {
        repo_did: row.get(0)?,
        src_uri: row.get(1)?,
        src_cid: row.get(2)?,
        collection: row.get(3)?,
        record_json: row.get(4)?,
        attempts: row.get(5)?,
        last_error: row.get(6)?,
        next_retry_at: row.get(7)?,
    })
}

fn publish_error_from_row(row: &Row<'_>) -> rusqlite::Result<PublishErrorRow> {
    Ok(PublishErrorRow {
        repo_did: row.get(0)?,
        cve_id: row.get(1)?,
        attempts: row.get(2)?,
        last_error: row.get(3)?,
        next_retry_at: row.get(4)?,
    })
}

fn source_host_state_from_row(row: &Row<'_>) -> rusqlite::Result<SourceHostStateRow> {
    Ok(SourceHostStateRow {
        host: row.get(0)?,
        window_start: row.get(1)?,
        requests: row.get(2)?,
        blocked_until: row.get(3)?,
    })
}

fn software_from_row(row: &Row<'_>) -> rusqlite::Result<SoftwareRow> {
    Ok(SoftwareRow {
        repo_did: row.get(0)?,
        slug: row.get(1)?,
        part: row.get(2)?,
        vendor: row.get(3)?,
        product: row.get(4)?,
        project_uri: row.get(5)?,
        project_cid: row.get(6)?,
        software_uri: row.get(7)?,
        software_cid: row.get(8)?,
        status: row.get(9)?,
        updated_at: row.get(10)?,
    })
}

fn purl_from_row(row: &Row<'_>) -> rusqlite::Result<PurlRow> {
    Ok(PurlRow {
        repo_did: row.get(0)?,
        purl: row.get(1)?,
        software_slug: row.get(2)?,
        purl_uri: row.get(3)?,
        purl_cid: row.get(4)?,
        status: row.get(5)?,
        updated_at: row.get(6)?,
    })
}

fn link_from_row(row: &Row<'_>) -> rusqlite::Result<LinkRow> {
    Ok(LinkRow {
        repo_did: row.get(0)?,
        src_uri: row.get(1)?,
        src_collection: row.get(2)?,
        src_rkey: row.get(3)?,
        src_cid: row.get(4)?,
        path: row.get(5)?,
        subject_uri: row.get(6)?,
        subject_cid: row.get(7)?,
        indexed_at: row.get(8)?,
    })
}

fn release_project_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseProjectRow> {
    Ok(ReleaseProjectRow {
        repo_did: row.get(0)?,
        slug: row.get(1)?,
        purl: row.get(2)?,
        system: row.get(3)?,
        latest_version: row.get(4)?,
        latest_version_raw: row.get(5)?,
        project_uri: row.get(6)?,
        project_cid: row.get(7)?,
        manifest_uri: row.get(8)?,
        manifest_cid: row.get(9)?,
        version_uri: row.get(10)?,
        version_cid: row.get(11)?,
        channel_uri: row.get(12)?,
        channel_cid: row.get(13)?,
        status: row.get(14)?,
        updated_at: row.get(15)?,
    })
}

fn release_version_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseVersionRow> {
    Ok(ReleaseVersionRow {
        repo_did: row.get(0)?,
        project_slug: row.get(1)?,
        version: row.get(2)?,
        version_raw: row.get(3)?,
        rkey: row.get(4)?,
        uri: row.get(5)?,
        cid: row.get(6)?,
        manifest_uri: row.get(7)?,
        manifest_cid: row.get(8)?,
        status: row.get(9)?,
        updated_at: row.get(10)?,
    })
}

fn release_channel_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseChannelRow> {
    Ok(ReleaseChannelRow {
        repo_did: row.get(0)?,
        project_slug: row.get(1)?,
        name: row.get(2)?,
        rkey: row.get(3)?,
        uri: row.get(4)?,
        cid: row.get(5)?,
        version_uri: row.get(6)?,
        version_cid: row.get(7)?,
        status: row.get(8)?,
        updated_at: row.get(9)?,
    })
}

fn release_status_from_row(row: &Row<'_>) -> rusqlite::Result<ReleaseStatusRow> {
    Ok(ReleaseStatusRow {
        repo_did: row.get(0)?,
        subject_uri: row.get(1)?,
        status: row.get(2)?,
        rkey: row.get(3)?,
        uri: row.get(4)?,
        cid: row.get(5)?,
        updated_at: row.get(6)?,
    })
}

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

    #[tokio::test]
    async fn cache_actor_roundtrip() {
        let db = DbHandle::open_in_memory().await.expect("open db");
        assert_eq!(db.get_cursor().await.expect("get cursor"), None);

        db.set_cursor("2024-01-01T00:00:00.000").await.expect("set");
        db.commit().await.expect("commit");
        assert_eq!(
            db.get_cursor().await.expect("cursor"),
            Some("2024-01-01T00:00:00.000".to_owned())
        );

        let cves = vec![
            json!({"id": "CVE-1", "lastModified": "2024-01-01T00:00:00.000", "x": "é"}),
            json!({"id": "CVE-2"}),
        ];
        assert_eq!(
            db.upsert_cves("did:plc:test", &cves).await.expect("upsert"),
            (2, 0, 0)
        );
        let counts = db.counts("did:plc:test").await.expect("counts");
        assert_eq!((counts.pending, counts.total), (2, 2));

        let rows = db
            .pending("did:plc:test", 0, Order::Cache)
            .await
            .expect("pending");
        assert_eq!(rows.len(), 2);
        assert!(rows[0].data.contains("\\u00e9"));

        let mut mark = PublicationMark::new("did:plc:test", "CVE-1", "present");
        mark.uri = Some("at://did:plc:test/com.nahdig.cve.nvdV2/CVE-1".to_owned());
        mark.cid = Some("bafytest".to_owned());
        db.mark_publication(mark).await.expect("mark");
        let counts = db.counts("did:plc:test").await.expect("counts");
        assert_eq!((counts.present, counts.pending), (1, 1));

        db.close().await.expect("close");
    }
}