|
| 1 | +use anyhow::{anyhow, bail}; |
| 2 | +use bytes::BytesMut; |
| 3 | +use futures_util::stream::TryStreamExt; |
| 4 | +use futures_util::{StreamExt, stream}; |
| 5 | +use sea_orm::{ |
| 6 | + ConnectionTrait, DatabaseTransaction, DbErr, EntityTrait, ModelTrait, TransactionTrait, |
| 7 | +}; |
| 8 | +use sea_orm_migration::SchemaManager; |
| 9 | +use trustify_common::id::Id; |
| 10 | +use trustify_entity::{sbom, source_document}; |
| 11 | +use trustify_module_storage::service::{StorageBackend, StorageKey, dispatch::DispatchBackend}; |
| 12 | + |
| 13 | +#[allow(clippy::large_enum_variant)] |
| 14 | +pub enum Sbom { |
| 15 | + CycloneDx(serde_cyclonedx::cyclonedx::v_1_6::CycloneDx), |
| 16 | + Spdx(spdx_rs::models::SPDX), |
| 17 | +} |
| 18 | + |
| 19 | +pub trait Document: Sized + Send + Sync { |
| 20 | + type Model: Send; |
| 21 | + |
| 22 | + async fn all<C>(tx: &C) -> Result<Vec<Self::Model>, DbErr> |
| 23 | + where |
| 24 | + C: ConnectionTrait; |
| 25 | + |
| 26 | + async fn source<S, C>(model: &Self::Model, storage: &S, tx: &C) -> Result<Self, anyhow::Error> |
| 27 | + where |
| 28 | + S: StorageBackend + Send + Sync, |
| 29 | + C: ConnectionTrait; |
| 30 | +} |
| 31 | + |
| 32 | +impl Document for Sbom { |
| 33 | + type Model = sbom::Model; |
| 34 | + |
| 35 | + async fn all<C: ConnectionTrait>(tx: &C) -> Result<Vec<Self::Model>, DbErr> { |
| 36 | + sbom::Entity::find().all(tx).await |
| 37 | + } |
| 38 | + |
| 39 | + async fn source<S, C>(model: &Self::Model, storage: &S, tx: &C) -> Result<Self, anyhow::Error> |
| 40 | + where |
| 41 | + S: StorageBackend + Send + Sync, |
| 42 | + C: ConnectionTrait, |
| 43 | + { |
| 44 | + let source = model.find_related(source_document::Entity).one(tx).await?; |
| 45 | + |
| 46 | + let Some(source) = source else { |
| 47 | + bail!("Missing source document ID for SBOM: {}", model.sbom_id); |
| 48 | + }; |
| 49 | + |
| 50 | + let stream = storage |
| 51 | + .retrieve( |
| 52 | + StorageKey::try_from(Id::Sha256(source.sha256)) |
| 53 | + .map_err(|err| anyhow!("Invalid ID: {err}"))?, |
| 54 | + ) |
| 55 | + .await |
| 56 | + .map_err(|err| anyhow!("Failed to retrieve document: {err}"))? |
| 57 | + .ok_or_else(|| anyhow!("Missing source document for SBOM: {}", model.sbom_id))?; |
| 58 | + |
| 59 | + stream |
| 60 | + .try_collect::<BytesMut>() |
| 61 | + .await |
| 62 | + .map_err(|err| anyhow!("Failed to collect bytes: {err}")) |
| 63 | + .map(|bytes| bytes.freeze()) |
| 64 | + .and_then(|bytes| { |
| 65 | + serde_json::from_slice(&bytes) |
| 66 | + .map(Sbom::Spdx) |
| 67 | + .or_else(|_| serde_json::from_slice(&bytes).map(Sbom::CycloneDx)) |
| 68 | + .map_err(|err| anyhow!("Failed to parse document: {err}")) |
| 69 | + }) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +pub trait Handler<D>: Send |
| 74 | +where |
| 75 | + D: Document, |
| 76 | +{ |
| 77 | + async fn call( |
| 78 | + &self, |
| 79 | + document: D, |
| 80 | + model: D::Model, |
| 81 | + tx: &DatabaseTransaction, |
| 82 | + ) -> anyhow::Result<()>; |
| 83 | +} |
| 84 | + |
| 85 | +pub trait DocumentProcessor { |
| 86 | + async fn process<D>( |
| 87 | + &self, |
| 88 | + storage: &DispatchBackend, |
| 89 | + f: impl Handler<D>, |
| 90 | + ) -> anyhow::Result<(), DbErr> |
| 91 | + where |
| 92 | + D: Document; |
| 93 | +} |
| 94 | + |
| 95 | +impl<'c> DocumentProcessor for SchemaManager<'c> { |
| 96 | + async fn process<D>( |
| 97 | + &self, |
| 98 | + storage: &DispatchBackend, |
| 99 | + f: impl Handler<D>, |
| 100 | + ) -> anyhow::Result<(), DbErr> |
| 101 | + where |
| 102 | + D: Document, |
| 103 | + { |
| 104 | + let db = self.get_connection(); |
| 105 | + let tx = db.begin().await?; |
| 106 | + |
| 107 | + // TODO: soft-lock database |
| 108 | + // In order to prevent new documents with an old version to be created in the meantime, we |
| 109 | + // should soft-lock the database. |
| 110 | + |
| 111 | + let all = D::all(&tx).await?; |
| 112 | + |
| 113 | + stream::iter(all) |
| 114 | + .map(async |model| { |
| 115 | + let doc = D::source(&model, storage, &tx).await.map_err(|err| { |
| 116 | + DbErr::Migration(format!("Failed to load source document: {err}")) |
| 117 | + })?; |
| 118 | + f.call(doc, model, &tx).await.map_err(|err| { |
| 119 | + DbErr::Migration(format!("Failed to process document: {err}")) |
| 120 | + })?; |
| 121 | + |
| 122 | + Ok::<_, DbErr>(()) |
| 123 | + }) |
| 124 | + .buffer_unordered(10) // TODO: make this configurable |
| 125 | + .try_collect::<Vec<_>>() |
| 126 | + .await?; |
| 127 | + |
| 128 | + // TODO: soft-unlock database |
| 129 | + |
| 130 | + Ok(()) |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | +#[macro_export] |
| 135 | +macro_rules! handler { |
| 136 | + (async | $doc:ident: $doc_ty:ty, $model:ident, $tx:ident | $body:block) => {{ |
| 137 | + struct H; |
| 138 | + |
| 139 | + impl $crate::data::Handler<$doc_ty> for H { |
| 140 | + async fn call( |
| 141 | + &self, |
| 142 | + $doc: $doc_ty, |
| 143 | + $model: <$doc_ty as $crate::data::Document>::Model, |
| 144 | + $tx: &sea_orm::DatabaseTransaction, |
| 145 | + ) -> anyhow::Result<()> { |
| 146 | + $body |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + H |
| 151 | + }}; |
| 152 | +} |
| 153 | + |
| 154 | +#[macro_export] |
| 155 | +macro_rules! sbom { |
| 156 | + (async | $doc:ident, $model:ident, $tx:ident | $body:block) => { |
| 157 | + $crate::handler!(async |$doc: $crate::data::Sbom, $model, $tx| $body) |
| 158 | + }; |
| 159 | +} |
0 commit comments