1use std::fs::File;
8use std::future::Future;
9use std::io::{BufReader, Read};
10use std::path::{Path, PathBuf};
11use std::sync::mpsc::{self, Receiver, SyncSender};
12use std::thread::{self, JoinHandle};
13use std::time::{SystemTime, UNIX_EPOCH};
14
15use oxrdfio::{RdfFormat, RdfParser};
16use waratah_storage::{CommitTs, NamedNode, Quad, Term};
17
18use crate::error::ComputeError;
19use crate::fanout::{GEO_INDEX_WIRE_BUDGET_BYTES, INSERT_QUAD_CHUNK, InsertResult};
20
21pub fn rdf_format_from_path(path: &Path) -> Result<(RdfFormat, bool), ComputeError> {
23 let mut gzip = false;
24 let mut ext = extension_lower(path);
25 if ext == "gz" {
26 gzip = true;
27 let stem = path.file_stem().map(Path::new).unwrap_or(path);
28 ext = extension_lower(stem);
29 }
30 let format = format_from_extension(&ext).ok_or_else(|| ComputeError::UnsupportedRdfFormat {
31 path: path.to_path_buf(),
32 })?;
33 Ok((format, gzip))
34}
35
36pub fn rdf_format_from_name(name: &str) -> Option<RdfFormat> {
38 match name {
39 "turtle" => Some(RdfFormat::Turtle),
40 "ntriples" => Some(RdfFormat::NTriples),
41 "nquads" => Some(RdfFormat::NQuads),
42 "trig" => Some(RdfFormat::TriG),
43 "rdfxml" => Some(RdfFormat::RdfXml),
44 _ => None,
45 }
46}
47
48pub fn rdf_syntax_name(format: RdfFormat) -> &'static str {
50 match format {
51 RdfFormat::Turtle => "turtle",
52 RdfFormat::NTriples => "ntriples",
53 RdfFormat::NQuads => "nquads",
54 RdfFormat::TriG => "trig",
55 RdfFormat::RdfXml => "rdfxml",
56 _ => "unknown",
57 }
58}
59
60pub fn extension_for_format(format: RdfFormat) -> &'static str {
62 match format {
63 RdfFormat::Turtle => "ttl",
64 RdfFormat::NTriples => "nt",
65 RdfFormat::NQuads => "nq",
66 RdfFormat::TriG => "trig",
67 RdfFormat::RdfXml => "rdf",
68 _ => "ttl",
69 }
70}
71
72pub fn now_commit_ts() -> CommitTs {
74 let millis = SystemTime::now()
75 .duration_since(UNIX_EPOCH)
76 .map(|d| d.as_millis() as u64)
77 .unwrap_or(1);
78 CommitTs(millis.max(1))
79}
80
81#[derive(Debug, Clone, Default)]
83pub struct RdfParseOptions {
84 pub base_iri: Option<String>,
86 pub graph: Option<String>,
91}
92
93pub struct RdfParsePipeline {
95 pub handle: JoinHandle<Result<(), ComputeError>>,
97 pub rx: Receiver<Result<Vec<Quad>, ComputeError>>,
99}
100
101pub fn spawn_rdf_parser(path: PathBuf, options: RdfParseOptions) -> RdfParsePipeline {
103 let (tx, rx) = mpsc::sync_channel(1);
104 let handle = thread::spawn(move || parse_and_send(path, options, tx));
105 RdfParsePipeline { handle, rx }
106}
107
108pub fn join_rdf_parser(handle: JoinHandle<Result<(), ComputeError>>) -> Result<(), ComputeError> {
110 match handle.join() {
111 Ok(result) => result,
112 Err(_) => Err(ComputeError::ParserThreadPanicked),
113 }
114}
115
116pub async fn insert_rdf_file<F, Fut>(
121 path: &Path,
122 options: RdfParseOptions,
123 mut insert: F,
124) -> Result<InsertResult, ComputeError>
125where
126 F: FnMut(&[Quad]) -> Fut,
127 Fut: Future<Output = Result<InsertResult, ComputeError>>,
128{
129 let pipeline = spawn_rdf_parser(path.to_path_buf(), options);
130 let mut totals = InsertResult {
131 quads: 0,
132 registered: 0,
133 inserted_per_axis: std::collections::BTreeMap::new(),
134 spike_reductions: 0,
135 };
136 for chunk in pipeline.rx {
137 let quads = chunk?;
138 let result = insert(&quads).await?;
139 totals.quads += result.quads;
140 totals.registered += result.registered;
141 totals.spike_reductions += result.spike_reductions;
142 for (axis, n) in result.inserted_per_axis {
143 *totals.inserted_per_axis.entry(axis).or_insert(0) += n;
144 }
145 }
146 join_rdf_parser(pipeline.handle)?;
147 Ok(totals)
148}
149
150fn format_from_extension(ext: &str) -> Option<RdfFormat> {
151 RdfFormat::from_extension(ext).or(match ext {
152 "turtle" => Some(RdfFormat::Turtle),
153 "owl" => Some(RdfFormat::RdfXml),
154 _ => None,
155 })
156}
157
158fn extension_lower(path: &Path) -> String {
159 path.extension()
160 .and_then(|e| e.to_str())
161 .unwrap_or("")
162 .to_ascii_lowercase()
163}
164
165fn open_rdf_reader(path: &Path, gzip: bool) -> Result<Box<dyn Read + Send>, ComputeError> {
166 let file = File::open(path)?;
167 if gzip {
168 Ok(Box::new(BufReader::new(flate2::read::MultiGzDecoder::new(
169 file,
170 ))))
171 } else {
172 Ok(Box::new(BufReader::new(file)))
173 }
174}
175
176fn file_url(path: &Path) -> String {
177 let abs = if path.is_absolute() {
178 path.to_path_buf()
179 } else {
180 std::env::current_dir()
181 .unwrap_or_else(|_| PathBuf::from("."))
182 .join(path)
183 };
184 format!("file://{}", abs.display())
185}
186
187fn parse_and_send(
191 path: PathBuf,
192 options: RdfParseOptions,
193 tx: SyncSender<Result<Vec<Quad>, ComputeError>>,
194) -> Result<(), ComputeError> {
195 let (format, gzip) = rdf_format_from_path(&path)?;
196 let reader = open_rdf_reader(&path, gzip)?;
197 let base = options.base_iri.unwrap_or_else(|| file_url(&path));
198 let mut parser = RdfParser::from_format(format)
199 .with_base_iri(&base)
200 .map_err(|source| ComputeError::InvalidBaseIri {
201 iri: base.clone(),
202 source,
203 })?;
204 if let Some(graph) = options.graph.filter(|s| !s.is_empty()) {
205 let node = NamedNode::new(&graph).map_err(|source| ComputeError::InvalidGraphIri {
206 iri: graph.clone(),
207 source,
208 })?;
209 parser = parser.with_default_graph(node);
210 }
211 let parser = parser.rename_blank_nodes().for_reader(reader);
212
213 let mut batch = Vec::with_capacity(INSERT_QUAD_CHUNK);
214 let mut geo_literals = 0usize;
220 for quad in parser {
221 let quad = match quad {
222 Ok(quad) => quad,
223 Err(source) => {
224 let err = ComputeError::RdfParse {
225 path: path.clone(),
226 source,
227 };
228 let _ = tx.send(Err(err));
229 return Ok(());
230 }
231 };
232 if object_is_plugin_claimed(&quad) {
233 geo_literals += 1;
234 }
235 batch.push(quad);
236 let geo_bytes = geo_literals.saturating_mul(ESTIMATED_GEO_POSTING_BYTES);
237 if batch.len() >= INSERT_QUAD_CHUNK || geo_bytes >= GEO_INDEX_WIRE_BUDGET_BYTES {
238 let chunk = std::mem::replace(&mut batch, Vec::with_capacity(INSERT_QUAD_CHUNK));
239 geo_literals = 0;
240 if tx.send(Ok(chunk)).is_err() {
241 return Ok(());
242 }
243 }
244 }
245 if !batch.is_empty() && tx.send(Ok(batch)).is_err() {
246 return Ok(());
247 }
248 Ok(())
249}
250
251pub const ESTIMATED_GEO_POSTING_BYTES: usize = 32 * 56;
254
255fn object_is_plugin_claimed(quad: &Quad) -> bool {
259 let plugins = crate::plugin::process_plugins();
260 if plugins.is_empty() {
261 return false;
262 }
263 let Term::Literal(literal) = &quad.object else {
264 return false;
265 };
266 plugins
267 .plugin_for_datatype(&literal.datatype().into_owned())
268 .is_some()
269}
270
271#[cfg(test)]
272mod tests {
273 use std::io::Write;
274 use std::sync::{Arc, Mutex};
275
276 use oxrdfio::RdfParser;
277 use waratah_storage::GraphName;
278
279 use super::*;
280
281 #[test]
282 fn guesses_plain_and_gzipped_extensions() {
283 assert_eq!(
284 rdf_format_from_path(Path::new("data.ttl")).unwrap(),
285 (RdfFormat::Turtle, false)
286 );
287 assert_eq!(
288 rdf_format_from_path(Path::new("data.nt.gz")).unwrap(),
289 (RdfFormat::NTriples, true)
290 );
291 assert_eq!(
292 rdf_format_from_path(Path::new("graph.trig.gz")).unwrap(),
293 (RdfFormat::TriG, true)
294 );
295 assert_eq!(
296 rdf_format_from_path(Path::new("quads.nq")).unwrap(),
297 (RdfFormat::NQuads, false)
298 );
299 assert!(rdf_format_from_path(Path::new("notes.csv")).is_err());
300 }
301
302 #[test]
303 fn format_names_roundtrip() {
304 for name in ["turtle", "ntriples", "nquads", "trig", "rdfxml"] {
305 let format = rdf_format_from_name(name).unwrap();
306 assert_eq!(rdf_syntax_name(format), name);
307 }
308 assert!(rdf_format_from_name("csv").is_none());
309 }
310
311 #[test]
312 fn streams_gzipped_ntriples() {
313 let dir = tempfile::tempdir().unwrap();
314 let path = dir.path().join("tiny.nt.gz");
315 let mut encoder = flate2::write::GzEncoder::new(
316 File::create(&path).unwrap(),
317 flate2::Compression::default(),
318 );
319 encoder
320 .write_all(b"<http://ex/s> <http://ex/p> \"o\" .\n")
321 .unwrap();
322 encoder.finish().unwrap();
323
324 let (format, gzip) = rdf_format_from_path(&path).unwrap();
325 assert_eq!(format, RdfFormat::NTriples);
326 assert!(gzip);
327
328 let reader = open_rdf_reader(&path, gzip).unwrap();
329 let quads: Vec<Quad> = RdfParser::from_format(format)
330 .for_reader(reader)
331 .collect::<Result<_, _>>()
332 .unwrap();
333 assert_eq!(quads.len(), 1);
334 assert_eq!(quads[0].subject.to_string(), "<http://ex/s>");
335 }
336
337 #[tokio::test]
338 async fn insert_rdf_file_parses_turtle() {
339 let dir = tempfile::tempdir().unwrap();
340 let path = dir.path().join("tiny.ttl");
341 std::fs::write(&path, "<http://ex/s> <http://ex/p> <http://ex/o> .\n").unwrap();
342 let got = Arc::new(Mutex::new(Vec::new()));
343 let captured = got.clone();
344 let result = insert_rdf_file(&path, RdfParseOptions::default(), move |quads| {
345 captured.lock().unwrap().extend_from_slice(quads);
346 let n = quads.len() as u64;
347 async move {
348 Ok(InsertResult {
349 quads: n,
350 registered: 0,
351 inserted_per_axis: std::collections::BTreeMap::new(),
352 spike_reductions: 0,
353 })
354 }
355 })
356 .await
357 .unwrap();
358 assert_eq!(result.quads, 1);
359 assert_eq!(got.lock().unwrap().len(), 1);
360 }
361
362 #[tokio::test]
363 async fn insert_rdf_file_assigns_named_graph() {
364 let dir = tempfile::tempdir().unwrap();
365 let path = dir.path().join("tiny.ttl");
366 std::fs::write(&path, "<http://ex/s> <http://ex/p> <http://ex/o> .\n").unwrap();
367 let got = Arc::new(Mutex::new(Vec::new()));
368 let captured = got.clone();
369 insert_rdf_file(
370 &path,
371 RdfParseOptions {
372 graph: Some("http://ex/g1".into()),
373 ..RdfParseOptions::default()
374 },
375 move |quads| {
376 captured.lock().unwrap().extend_from_slice(quads);
377 let n = quads.len() as u64;
378 async move {
379 Ok(InsertResult {
380 quads: n,
381 registered: 0,
382 inserted_per_axis: std::collections::BTreeMap::new(),
383 spike_reductions: 0,
384 })
385 }
386 },
387 )
388 .await
389 .unwrap();
390 let quads = got.lock().unwrap();
391 assert_eq!(quads.len(), 1);
392 assert_eq!(
393 quads[0].graph_name,
394 GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap())
395 );
396 }
397
398 #[tokio::test]
399 async fn insert_rdf_file_graph_remaps_trig_default_only() {
400 let dir = tempfile::tempdir().unwrap();
401 let path = dir.path().join("tiny.trig");
402 std::fs::write(
403 &path,
404 "<http://ex/s> <http://ex/p> <http://ex/o> .\n\
405 GRAPH <http://ex/g2> { <http://ex/s2> <http://ex/p2> <http://ex/o2> . }\n",
406 )
407 .unwrap();
408 let got = Arc::new(Mutex::new(Vec::new()));
409 let captured = got.clone();
410 insert_rdf_file(
411 &path,
412 RdfParseOptions {
413 graph: Some("http://ex/g1".into()),
414 ..RdfParseOptions::default()
415 },
416 move |quads| {
417 captured.lock().unwrap().extend_from_slice(quads);
418 let n = quads.len() as u64;
419 async move {
420 Ok(InsertResult {
421 quads: n,
422 registered: 0,
423 inserted_per_axis: std::collections::BTreeMap::new(),
424 spike_reductions: 0,
425 })
426 }
427 },
428 )
429 .await
430 .unwrap();
431 let quads = got.lock().unwrap();
432 assert_eq!(quads.len(), 2);
433 let g1 = GraphName::NamedNode(NamedNode::new("http://ex/g1").unwrap());
434 let g2 = GraphName::NamedNode(NamedNode::new("http://ex/g2").unwrap());
435 for q in quads.iter() {
436 match q.subject.to_string().as_str() {
437 "<http://ex/s>" => assert_eq!(&q.graph_name, &g1),
438 "<http://ex/s2>" => assert_eq!(&q.graph_name, &g2),
439 other => panic!("unexpected subject {other}"),
440 }
441 }
442 }
443
444 #[tokio::test]
445 async fn insert_rdf_file_rejects_invalid_graph_iri() {
446 let dir = tempfile::tempdir().unwrap();
447 let path = dir.path().join("tiny.ttl");
448 std::fs::write(&path, "<http://ex/s> <http://ex/p> <http://ex/o> .\n").unwrap();
449 let err = insert_rdf_file(
450 &path,
451 RdfParseOptions {
452 graph: Some("not a uri".into()),
453 ..RdfParseOptions::default()
454 },
455 |_quads| async {
456 Ok(InsertResult {
457 quads: 0,
458 registered: 0,
459 inserted_per_axis: std::collections::BTreeMap::new(),
460 spike_reductions: 0,
461 })
462 },
463 )
464 .await
465 .unwrap_err();
466 assert!(matches!(err, ComputeError::InvalidGraphIri { .. }));
467 }
468}