use {
crate::{
checksum::{
ChecksumMode,
Digesting,
SharedDigesting,
TrailerIris,
TrailerSpec,
},
emit::QuadBatch,
encode::Encoding,
location::Location,
s3::{S3Store, S3Upload, S3Url},
},
anyhow::Context,
async_compression::tokio::write::GzipEncoder,
oxrdf::{
Dataset,
NamedNode,
graph::{CanonicalizationAlgorithm, CanonicalizationHashAlgorithm},
},
oxrdfio::{RdfFormat, RdfSerializer},
std::{path::PathBuf, pin::Pin, sync::Arc},
tokio::io::{AsyncWrite, AsyncWriteExt, BufWriter},
};
const PREFIXES: &[(&str, &str)] = &[
("raw", crate::vocab::raw::NS),
("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
("xsd", "http://www.w3.org/2001/XMLSchema#"),
("prov", "http://www.w3.org/ns/prov#"),
("dcat", "http://www.w3.org/ns/dcat#"),
("dcterms", "http://purl.org/dc/terms/"),
("spdx", "http://spdx.org/rdf/terms#"),
];
type Sink = Pin<Box<dyn AsyncWrite + Send>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Syntax {
NTriples,
NQuads,
TriG,
}
impl Syntax {
fn format(self) -> RdfFormat {
match self {
Self::NTriples => RdfFormat::NTriples,
Self::NQuads => RdfFormat::NQuads,
Self::TriG => RdfFormat::TriG,
}
}
fn keeps_graphs(self) -> bool { self != Self::NTriples }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
Stdout,
File(PathBuf),
S3(S3Url),
}
#[derive(Debug, Clone)]
pub struct Output {
target: Target,
syntax: Syntax,
gzip: bool,
canonical: bool,
checksum: ChecksumMode,
}
fn self_target(t: &Target) -> String {
match t {
Target::Stdout => "stdout".into(),
Target::File(p) => p.display().to_string(),
Target::S3(u) => u.to_string(),
}
}
impl Output {
pub fn stdout(canonical: bool) -> Self {
Self {
target: Target::Stdout,
syntax: Syntax::NQuads,
gzip: false,
canonical,
checksum: ChecksumMode::default(),
}
}
pub fn file(path: PathBuf, canonical: bool) -> anyhow::Result<Self> {
Self::to(Location::Local(path), canonical)
}
pub fn to(location: Location, canonical: bool) -> anyhow::Result<Self> {
let name = location
.file_name()
.context("output has no file name")?
.to_ascii_lowercase();
let (stem, gzip) = match name.strip_suffix(".gz") {
Some(stem) => (stem.to_owned(), true),
None => (name, false),
};
let syntax = match stem.rsplit_once('.').map(|(_, e)| e) {
Some("nq") => Syntax::NQuads,
Some("nt") => Syntax::NTriples,
Some("trig") => Syntax::TriG,
other => {
anyhow::bail!(
"unsupported output extension {other:?}; use .nq, .nt or \
.trig (optionally .gz)"
)
},
};
anyhow::ensure!(
!canonical || syntax != Syntax::TriG,
"RDFC-1.0 canonical output is N-Quads or N-Triples, not TriG"
);
let target = match location {
Location::Local(path) => Target::File(path),
Location::S3(url) => Target::S3(url),
};
Ok(Self {
target,
syntax,
gzip,
canonical,
checksum: ChecksumMode::default(),
})
}
pub fn with_checksum(mut self, checksum: ChecksumMode) -> Self {
self.checksum = checksum;
self
}
pub fn download_url(&self) -> Option<NamedNode> {
let url = match &self.target {
Target::Stdout => return None,
Target::File(p) => {
url::Url::from_file_path(std::path::absolute(p).ok()?)
.ok()
.map(String::from)?
},
Target::S3(u) => u.to_string(),
};
NamedNode::new(url).ok()
}
pub fn media_type(&self) -> &'static str {
match self.syntax {
Syntax::NQuads => "application/n-quads",
Syntax::NTriples => "application/n-triples",
Syntax::TriG => "application/trig",
}
}
pub fn is_gzip(&self) -> bool { self.gzip }
fn content_type(&self) -> &'static str {
match (self.gzip, self.syntax) {
(true, _) => "application/gzip",
(false, Syntax::NQuads) => "application/n-quads",
(false, Syntax::NTriples) => "application/n-triples",
(false, Syntax::TriG) => "application/trig",
}
}
async fn sink(
&self,
upload: Option<tokio::io::DuplexStream>,
) -> anyhow::Result<Sink> {
let raw: Sink = match &self.target {
Target::S3(_) => {
Box::pin(upload.context("S3 output without an upload")?)
},
Target::Stdout => {
Box::pin(BufWriter::with_capacity(
1 << 20,
tokio::io::stdout(),
))
},
Target::File(p) => {
Box::pin(BufWriter::with_capacity(
1 << 20,
tokio::fs::File::create(p).await.with_context(|| {
format!("cannot create {}", p.display())
})?,
))
},
};
Ok(raw)
}
pub fn encoding(&self) -> Option<Encoding> {
match (self.syntax, self.canonical) {
(_, true) | (Syntax::TriG, _) => None,
(Syntax::NQuads, false) => Some(Encoding::NQuads),
(Syntax::NTriples, false) => Some(Encoding::NTriples),
}
}
pub async fn run(
self,
rx: flume::Receiver<QuadBatch>,
store: Arc<S3Store>,
verdict: tokio::sync::oneshot::Receiver<bool>,
trailer: TrailerIris,
) -> anyhow::Result<u64> {
let mut upload = match &self.target {
Target::S3(url) => {
Some(S3Upload::start(&store, url, self.content_type()).await?)
},
_ => None,
};
let pipe = upload.as_mut().map(S3Upload::writer);
let target = self.target.clone();
let result = self.write(rx, pipe, trailer).await;
match (upload, result) {
(Some(upload), Ok(count)) => {
if verdict.await.unwrap_or(false) {
upload.commit().await?;
} else {
upload.abort().await;
tracing::warn!(
"{}: not published, the run failed",
self_target(&target)
);
}
Ok(count)
},
(Some(upload), Err(e)) => {
upload.abort().await;
Err(e)
},
(None, result) => result,
}
}
fn trailer_spec(&self, iris: TrailerIris) -> Option<TrailerSpec> {
self.checksum.is_trailer().then(|| {
TrailerSpec {
iris,
format: self.syntax.format(),
keep_graphs: self.syntax.keeps_graphs(),
gzip: self.gzip,
}
})
}
async fn write(
self,
rx: flume::Receiver<QuadBatch>,
pipe: Option<tokio::io::DuplexStream>,
trailer: TrailerIris,
) -> anyhow::Result<u64> {
let spec = self.trailer_spec(trailer);
if self.gzip && self.encoding().is_some() {
return tokio::task::spawn_blocking(move || {
self.write_encoded_parallel_gzip(&rx, pipe, spec)
})
.await?;
}
let mut sink = Digesting::new(self.sink(pipe).await?, spec.is_some());
let mut count = if self.gzip {
let mut gz = GzipEncoder::new(sink);
let count = self.write_body(&mut gz, rx).await?;
gz.shutdown().await?;
sink = gz.into_inner();
count
} else {
let count = self.write_body(&mut sink, rx).await?;
sink.flush().await?;
count
};
let (mut raw, digest) = sink.into_parts();
if let (Some(spec), Some(digest)) = (spec, digest) {
let (bytes, quads) = spec.render(digest)?;
raw.write_all(&bytes).await?;
count += quads;
}
raw.shutdown().await?;
Ok(count)
}
async fn write_body<W: AsyncWrite + Unpin + Send>(
&self,
sink: &mut W,
rx: flume::Receiver<QuadBatch>,
) -> anyhow::Result<u64> {
if self.canonical {
self.write_canonical(sink, rx).await
} else {
self.write_streaming(sink, rx).await
}
}
async fn write_streaming<W: AsyncWrite + Unpin + Send>(
&self,
sink: &mut W,
rx: flume::Receiver<QuadBatch>,
) -> anyhow::Result<u64> {
if self.encoding().is_some() {
Self::write_encoded(sink, rx).await
} else {
self.write_serialized(sink, rx).await
}
}
async fn write_encoded<W: AsyncWrite + Unpin + Send>(
sink: &mut W,
rx: flume::Receiver<QuadBatch>,
) -> anyhow::Result<u64> {
let mut count = 0u64;
while let Ok(batch) = rx.recv_async().await {
let QuadBatch::Encoded { bytes, quads } = batch else {
anyhow::bail!("structured batch sent to a line-based writer");
};
sink.write_all(&bytes).await?;
count += quads;
}
Ok(count)
}
fn write_encoded_parallel_gzip(
&self,
rx: &flume::Receiver<QuadBatch>,
pipe: Option<tokio::io::DuplexStream>,
spec: Option<TrailerSpec>,
) -> anyhow::Result<u64> {
use {
gzp::{
ZWriter,
deflate::Gzip,
par::compress::{ParCompress, ParCompressBuilder},
},
std::io::Write as _,
};
let out: Box<dyn std::io::Write + Send> = match &self.target {
Target::Stdout => Box::new(std::io::stdout()),
Target::S3(_) => {
Box::new(tokio_util::io::SyncIoBridge::new(
pipe.context("S3 output without an upload")?,
))
},
Target::File(p) => {
Box::new(std::fs::File::create(p).with_context(|| {
format!("cannot create {}", p.display())
})?)
},
};
let (out, kept) = SharedDigesting::new(out, spec.is_some());
let threads =
std::thread::available_parallelism().map_or(4, |n| n.get());
let mut gz: ParCompress<Gzip, _> = ParCompressBuilder::new()
.compression_level(gzp::Compression::new(6))
.num_threads(threads)
.map_err(|e| anyhow::anyhow!("gzip threads: {e}"))?
.from_writer(out);
let mut count = 0u64;
for batch in rx.iter() {
let QuadBatch::Encoded { bytes, quads } = batch else {
anyhow::bail!("structured batch sent to a line-based writer");
};
gz.write_all(&bytes)?;
count += quads;
}
gz.finish().map_err(|e| anyhow::anyhow!("gzip: {e}"))?;
let (mut out, digest) = kept.into_parts()?;
if let (Some(spec), Some(digest)) = (spec, digest) {
let (bytes, quads) = spec.render(digest)?;
out.write_all(&bytes)?;
count += quads;
}
out.flush()?;
Ok(count)
}
async fn write_serialized<W: AsyncWrite + Unpin + Send>(
&self,
sink: &mut W,
rx: flume::Receiver<QuadBatch>,
) -> anyhow::Result<u64> {
let mut ser = RdfSerializer::from_format(self.syntax.format());
for (prefix, ns) in PREFIXES {
ser = ser.with_prefix(*prefix, *ns)?;
}
let mut ser = ser.for_tokio_async_writer(sink);
let mut count = 0u64;
let keep = self.syntax.keeps_graphs();
while let Ok(batch) = rx.recv_async().await {
anyhow::ensure!(
matches!(batch, QuadBatch::Triples { .. }),
"encoded batch sent to a serializing writer"
);
count += batch.quad_count();
for quad in batch.into_quads(keep) {
ser.serialize_quad(&quad).await?;
}
}
ser.finish().await?;
Ok(count)
}
async fn write_canonical<W: AsyncWrite + Unpin + Send>(
&self,
sink: &mut W,
rx: flume::Receiver<QuadBatch>,
) -> anyhow::Result<u64> {
let mut dataset = Dataset::new();
let mut count = 0u64;
let keep = self.syntax.keeps_graphs();
while let Ok(batch) = rx.recv_async().await {
count += batch.quad_count();
for quad in batch.into_quads(keep) {
dataset.insert(&quad);
}
}
dataset.canonicalize(CanonicalizationAlgorithm::Rdfc10 {
hash_algorithm: CanonicalizationHashAlgorithm::Sha256,
});
let mut lines: Vec<String> = dataset
.iter()
.map(|q| {
let mut s = q.to_string();
s.push_str(" .\n");
s
})
.collect();
lines.sort_unstable();
for line in lines {
sink.write_all(line.as_bytes()).await?;
}
Ok(count)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extensions() {
let o = Output::file("x/out.nt.gz".into(), false).unwrap();
assert_eq!((o.syntax, o.gzip), (Syntax::NTriples, true));
let o = Output::file("out.NQ".into(), true).unwrap();
assert_eq!((o.syntax, o.gzip), (Syntax::NQuads, false));
assert!(Output::file("out.trig".into(), true).is_err());
assert!(Output::file("out.ttl".into(), false).is_err());
}
}