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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! The single writer task: serializes quad batches as they arrive.
//!
//! Format follows the output file name: `.nq`, `.nt`, `.trig`, each
//! optionally followed by `.gz`. `.nt` writes the union of all graphs.
//! With `canonical`, output is RDFC-1.0 canonical N-Quads/N-Triples; that
//! needs the whole dataset in memory, everything else streams.

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),
}

/// Fully resolved output: where, which syntax, compressed, canonical.
#[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)
    }

    /// Output to a local file or an S3 object; the syntax follows from the
    /// name (`.nq`, `.nt`, `.trig`, each optionally `.gz`).
    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(),
        })
    }

    /// Whether to end the output with a checksum of its own leading bytes.
    pub fn with_checksum(mut self, checksum: ChecksumMode) -> Self {
        self.checksum = checksum;
        self
    }

    /// Where the output can be fetched: a `file:` or `s3:` IRI, or nothing
    /// for stdout.
    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()
    }

    /// The IANA media type of the RDF syntax, before any compression.
    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 }

    /// The Content-Type of the output object.
    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")?)
            },
            // Unbuffered stdout costs one write system call per quad.
            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)
    }

    /// The encoding producers apply themselves: line-based syntaxes stream
    /// pre-encoded bytes; TriG and canonical output need structured triples.
    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),
        }
    }

    /// Consume all batches; returns the number of quads received. An S3
    /// output is published only if everything was written and `verdict`
    /// says the run succeeded; otherwise its upload is aborted, so a failed
    /// run never creates the object (or its S3 event).
    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,
        }
    }

    /// The trailer, if this output gets one.
    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 {
            // The encoder's shutdown ends the gzip member; Digesting keeps
            // the sink itself open for the trailer member.
            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
        }
    }

    /// Line-based output: producers already encoded every batch, so the
    /// writer only moves bytes.
    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)
    }

    /// Gzipped line-based output, compressed on all cores into a single
    /// standard gzip member (blocks share their predecessor's dictionary,
    /// like pigz), so every gzip reader can decompress it.
    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());
        // Level 6, as gzip and the single-threaded encoder default to. With
        // zlib-ng it costs half the CPU of zlib at a slightly better ratio.
        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)
    }

    /// TriG: serialized here, where prefixes and graph blocks are known.
    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());
    }
}