triplify 0.2.2

Triplify turns any tabular data dump (CSV, XLSX, Parquet, ...) into raw RDF using the EKGF Raw Data Ontology, with DCAT, PROV and git provenance, without any mapping
Documentation
//! Checksum trailer: the output describes its own integrity.
//!
//! A file cannot contain the checksum of its own final bytes, so the writer
//! hashes every byte it writes and then appends a few quads stating the
//! SHA-256 of those leading bytes and their number
//! (`raw:checksumByteCount`). For `.gz` output the trailer is a separate,
//! final gzip member, so the checksum covers the data member exactly as
//! stored, and every multi-member gzip reader sees the trailer as ordinary
//! N-Quads. Verifying means `head -c N file | sha256sum`.

use {
    crate::vocab::{raw, rdf, spdx, xsd},
    oxrdf::{GraphName, Literal, NamedNode, Quad},
    oxrdfio::{RdfFormat, RdfSerializer},
    sha2::{Digest as _, Sha256},
    std::{
        io::Write,
        pin::Pin,
        sync::{Arc, Mutex},
        task::{Context, Poll},
    },
    tokio::io::AsyncWrite,
};

/// Whether the output ends with a checksum of its own leading bytes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum ChecksumMode {
    // Append the SHA-256 of all preceding bytes, as a final gzip member
    // for `.gz` output and as final lines otherwise. (Plain comments keep
    // `--help` in its compact form.)
    #[default]
    Trailer,
    // Write the data only.
    None,
}

impl ChecksumMode {
    pub fn is_trailer(self) -> bool { self == Self::Trailer }
}

/// The nodes the trailer describes: the output distribution, its checksum,
/// and the run's provenance graph that holds them.
#[derive(Debug, Clone)]
pub struct TrailerIris {
    output:   NamedNode,
    checksum: NamedNode,
    graph:    NamedNode,
}

impl TrailerIris {
    pub fn new(
        output: NamedNode,
        checksum: NamedNode,
        graph: NamedNode,
    ) -> Self {
        Self { output, checksum, graph }
    }
}

/// Running SHA-256 and length of the bytes written so far.
#[derive(Default)]
pub struct ByteDigest {
    sha:   Sha256,
    bytes: u64,
}

impl ByteDigest {
    fn update(&mut self, data: &[u8]) {
        self.sha.update(data);
        self.bytes += data.len() as u64;
    }

    fn covered(self) -> Covered {
        Covered {
            hex:   hex::encode(self.sha.finalize()),
            bytes: self.bytes,
        }
    }
}

/// What a finished digest covers: the hash and the number of leading bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Covered {
    hex:   String,
    bytes: u64,
}

/// The quads appended after the data.
pub struct Trailer {
    iris:    TrailerIris,
    covered: Covered,
}

impl Trailer {
    fn new(iris: TrailerIris, covered: Covered) -> Self {
        Self { iris, covered }
    }

    fn quads(&self) -> Vec<Quad> {
        let graph = GraphName::NamedNode(self.iris.graph.clone());
        let ck = &self.iris.checksum;
        let quad = |s: &NamedNode, p, o: oxrdf::Term| {
            Quad::new(s.clone(), p, o, graph.clone())
        };
        vec![
            quad(
                &self.iris.output,
                spdx::CHECKSUM.into_owned(),
                ck.clone().into(),
            ),
            quad(
                ck,
                rdf::TYPE.into_owned(),
                spdx::CHECKSUM_CLASS.into_owned().into(),
            ),
            quad(
                ck,
                spdx::ALGORITHM.into_owned(),
                spdx::SHA256.into_owned().into(),
            ),
            quad(
                ck,
                spdx::CHECKSUM_VALUE.into_owned(),
                Literal::new_typed_literal(&self.covered.hex, xsd::HEX_BINARY)
                    .into(),
            ),
            quad(
                ck,
                raw::CHECKSUM_BYTE_COUNT.into_owned(),
                Literal::new_typed_literal(
                    self.covered.bytes.to_string(),
                    xsd::NON_NEGATIVE_INTEGER,
                )
                .into(),
            ),
        ]
    }

    /// The trailer in the output's syntax, as its own gzip member when the
    /// output is gzipped. N-Triples drops the graph, like the data does.
    fn encode(
        &self,
        format: RdfFormat,
        keep_graphs: bool,
        gzip: bool,
    ) -> anyhow::Result<Vec<u8>> {
        let mut ser = RdfSerializer::from_format(format).for_writer(Vec::new());
        for q in self.quads() {
            let q = if keep_graphs {
                q
            } else {
                Quad { graph_name: GraphName::DefaultGraph, ..q }
            };
            ser.serialize_quad(&q)?;
        }
        let text = ser.finish()?;
        if !gzip {
            return Ok(text);
        }
        let mut gz = flate2::write::GzEncoder::new(
            Vec::new(),
            flate2::Compression::new(6),
        );
        gz.write_all(&text)?;
        Ok(gz.finish()?)
    }

    fn quad_count(&self) -> u64 { self.quads().len() as u64 }
}

/// Builds the trailer bytes once the data is complete.
pub(crate) struct TrailerSpec {
    pub(crate) iris:        TrailerIris,
    pub(crate) format:      RdfFormat,
    pub(crate) keep_graphs: bool,
    pub(crate) gzip:        bool,
}

impl TrailerSpec {
    /// The encoded trailer and its quad count.
    pub(crate) fn render(
        self,
        digest: ByteDigest,
    ) -> anyhow::Result<(Vec<u8>, u64)> {
        let trailer = Trailer::new(self.iris, digest.covered());
        Ok((
            trailer.encode(self.format, self.keep_graphs, self.gzip)?,
            trailer.quad_count(),
        ))
    }
}

/// An async sink that hashes what it writes. Shutting it down only flushes:
/// the trailer still has to follow, so the inner sink stays open until
/// [`Digesting::into_parts`] hands it back.
pub(crate) struct Digesting<W> {
    inner:  W,
    digest: Option<ByteDigest>,
}

impl<W> Digesting<W> {
    pub(crate) fn new(inner: W, hash: bool) -> Self {
        Self { inner, digest: hash.then(ByteDigest::default) }
    }

    pub(crate) fn into_parts(self) -> (W, Option<ByteDigest>) {
        (self.inner, self.digest)
    }
}

impl<W: AsyncWrite + Unpin> AsyncWrite for Digesting<W> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        let this = &mut *self;
        let poll = Pin::new(&mut this.inner).poll_write(cx, buf);
        if let (Poll::Ready(Ok(n)), Some(d)) = (&poll, this.digest.as_mut()) {
            d.update(&buf[..*n]);
        }
        poll
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.inner).poll_flush(cx)
    }
}

/// The blocking counterpart, shared because the parallel gzip encoder takes
/// ownership of its writer and does not return it.
pub(crate) struct SharedDigesting(Arc<Mutex<Digesting<Box<dyn Write + Send>>>>);

impl SharedDigesting {
    pub(crate) fn new(
        inner: Box<dyn Write + Send>,
        hash: bool,
    ) -> (Self, Self) {
        let shared = Arc::new(Mutex::new(Digesting::new(inner, hash)));
        (Self(shared.clone()), Self(shared))
    }

    /// The writer and digest, once the encoder has released its handle.
    pub(crate) fn into_parts(
        self,
    ) -> anyhow::Result<(Box<dyn Write + Send>, Option<ByteDigest>)> {
        let inner = Arc::try_unwrap(self.0)
            .map_err(|_| {
                anyhow::anyhow!("gzip encoder still holds the output")
            })?
            .into_inner()
            .map_err(|_| anyhow::anyhow!("poisoned output lock"))?;
        Ok(inner.into_parts())
    }
}

impl Write for SharedDigesting {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let mut d = self
            .0
            .lock()
            .map_err(|_| std::io::Error::other("poisoned output lock"))?;
        let n = d.inner.write(buf)?;
        if let Some(digest) = d.digest.as_mut() {
            digest.update(&buf[..n]);
        }
        Ok(n)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.0
            .lock()
            .map_err(|_| std::io::Error::other("poisoned output lock"))?
            .inner
            .flush()
    }
}

#[cfg(test)]
mod tests {
    use {super::*, std::io::Read};

    fn iris() -> TrailerIris {
        TrailerIris::new(
            NamedNode::new_unchecked("urn:out"),
            NamedNode::new_unchecked("urn:ck"),
            NamedNode::new_unchecked("urn:g"),
        )
    }

    #[test]
    fn digest_counts_and_hashes_bytes() {
        let mut d = ByteDigest::default();
        d.update(b"ab");
        d.update(b"c");
        let c = d.covered();
        assert_eq!(c.bytes, 3);
        assert_eq!(
            c.hex,
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    #[test]
    fn gzip_trailer_is_its_own_member_of_nquads() {
        let mut d = ByteDigest::default();
        d.update(b"data");
        let spec = TrailerSpec {
            iris:        iris(),
            format:      RdfFormat::NQuads,
            keep_graphs: true,
            gzip:        true,
        };
        let (bytes, quads) = spec.render(d).unwrap();
        assert_eq!(quads, 5);
        let mut text = String::new();
        flate2::read::GzDecoder::new(&bytes[..])
            .read_to_string(&mut text)
            .unwrap();
        assert!(text.contains(
            "<urn:ck> <https://ekgf.org/ontology/raw#checksumByteCount> \"4\""
        ));
        assert!(text.lines().all(|l| l.ends_with("<urn:g> .")));
    }

    #[test]
    fn ntriples_trailer_drops_the_graph() {
        let spec = TrailerSpec {
            iris:        iris(),
            format:      RdfFormat::NTriples,
            keep_graphs: false,
            gzip:        false,
        };
        let (bytes, _) = spec.render(ByteDigest::default()).unwrap();
        let text = String::from_utf8(bytes).unwrap();
        assert!(!text.contains("<urn:g>"));
        assert_eq!(text.lines().count(), 5);
    }
}