1use std::collections::HashSet;
25use std::fs::{self, File};
26use std::io::Read;
27use std::path::{Path, PathBuf};
28use std::sync::{Arc, Mutex, OnceLock};
29
30use serde::Serialize;
31use waratah_storage::queries_repo_dir;
32
33const MAX_QUERY_BYTES: usize = 64 * 1024;
37
38const QUERY_EXTENSION: &str = "rq";
40
41const SIDECAR_EXTENSION: &str = "toml";
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
47pub struct ServerQuery {
48 pub id: String,
52 pub name: String,
54 #[serde(skip_serializing_if = "Option::is_none")]
56 pub description: Option<String>,
57 pub query: String,
61}
62
63#[derive(Debug, Clone)]
65pub enum QueryLibrary {
66 Directory(PathBuf),
69 Inline(Arc<[ServerQuery]>),
72}
73
74#[derive(Debug, thiserror::Error)]
78pub enum QueryLibraryError {
79 #[error("no query library is published for repository {0}")]
82 Missing(String),
83 #[error("{message}: {path}")]
87 Invalid {
88 path: PathBuf,
90 message: String,
92 },
93}
94
95impl QueryLibrary {
96 pub fn load(&self, repository_id: &str) -> Result<Vec<ServerQuery>, QueryLibraryError> {
100 match self {
101 Self::Inline(entries) => Ok(entries.to_vec()),
102 Self::Directory(root) => {
103 load_directory(repository_id, &queries_repo_dir(root, repository_id))
104 }
105 }
106 }
107}
108
109fn load_directory(repository_id: &str, dir: &Path) -> Result<Vec<ServerQuery>, QueryLibraryError> {
111 let mut paths: Vec<PathBuf> = Vec::new();
112 let entries = match fs::read_dir(dir) {
113 Ok(entries) => entries,
114 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
118 return Err(QueryLibraryError::Missing(repository_id.to_owned()));
119 }
120 Err(error) => {
121 return Err(invalid(
122 dir,
123 format!("cannot read query library directory ({error})"),
124 ));
125 }
126 };
127 for entry in entries {
128 let entry = entry.map_err(|error| {
129 invalid(
130 dir,
131 format!("cannot read query library directory ({error})"),
132 )
133 })?;
134 paths.push(entry.path());
135 }
136 paths.sort();
137
138 let query_stems: HashSet<String> = paths
143 .iter()
144 .filter(|path| has_extension(path, QUERY_EXTENSION))
145 .filter(|path| path.is_file())
146 .filter_map(|path| utf8_stem(path))
147 .collect();
148
149 let mut loaded: Vec<(i64, ServerQuery)> = Vec::new();
150 for path in &paths {
151 let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
155 continue;
156 };
157 if file_name.starts_with('.') || path.is_dir() {
158 continue;
159 }
160 if has_extension(path, QUERY_EXTENSION) {
161 let Some(stem) = utf8_stem(path) else {
162 warn_once(path, "query filename is not valid UTF-8");
163 continue;
164 };
165 if let Some(entry) = load_query_file(path, &stem)? {
166 loaded.push(entry);
167 }
168 } else if has_extension(path, SIDECAR_EXTENSION) {
169 let Some(stem) = utf8_stem(path) else {
170 continue;
171 };
172 if !query_stems.contains(&stem) {
173 warn_once(path, "sidecar without a matching .rq file");
174 }
175 } else if has_extension_case_insensitive(path, QUERY_EXTENSION)
176 || has_extension_case_insensitive(path, SIDECAR_EXTENSION)
177 {
178 warn_once(
181 path,
182 "query library extensions must be lowercase (.rq / .toml)",
183 );
184 }
185 }
188
189 loaded.sort_by(|left, right| (left.0, &left.1.id).cmp(&(right.0, &right.1.id)));
192 Ok(loaded.into_iter().map(|(_, query)| query).collect())
193}
194
195fn load_query_file(path: &Path, id: &str) -> Result<Option<(i64, ServerQuery)>, QueryLibraryError> {
202 match fs::metadata(path) {
205 Ok(metadata) if metadata.is_file() => {}
206 Ok(_) => {
207 warn_once(path, "query is not a regular file");
208 return Ok(None);
209 }
210 Err(_) => {
212 warn_once(path, "query file is not readable (stat failed)");
213 return Ok(None);
214 }
215 }
216
217 let file = File::open(path)
221 .map_err(|error| invalid(path, format!("cannot open query file ({error})")))?;
222 let mut bytes = Vec::new();
223 file.take(MAX_QUERY_BYTES as u64 + 1)
224 .read_to_end(&mut bytes)
225 .map_err(|error| invalid(path, format!("cannot read query file ({error})")))?;
226 if bytes.len() > MAX_QUERY_BYTES {
227 warn_once(path, "query file exceeds the 64 KiB size limit");
228 return Ok(None);
229 }
230 let query = match String::from_utf8(bytes) {
231 Ok(text) => normalize_query_text(text),
232 Err(_) => {
233 warn_once(path, "query file is not valid UTF-8");
234 return Ok(None);
235 }
236 };
237 if query.trim().is_empty() {
238 warn_once(path, "query file is empty");
239 return Ok(None);
240 }
241
242 let sidecar = load_sidecar(path)?;
243 let (name, description, order) = match sidecar {
244 Some(sidecar) => (
245 non_blank(sidecar.name),
246 non_blank(sidecar.description),
247 sidecar.order.unwrap_or(0),
248 ),
249 None => (None, None, 0),
250 };
251 let name = name.unwrap_or_else(|| humanize_stem(id));
252
253 Ok(Some((
254 order,
255 ServerQuery {
256 id: id.to_owned(),
257 name,
258 description,
259 query,
260 },
261 )))
262}
263
264fn load_sidecar(query_path: &Path) -> Result<Option<QuerySidecar>, QueryLibraryError> {
268 let sidecar_path = query_path.with_extension(SIDECAR_EXTENSION);
269 if !sidecar_path.is_file() {
270 return Ok(None);
271 }
272 let text = fs::read_to_string(&sidecar_path).map_err(|error| {
273 invalid(
274 &sidecar_path,
275 format!("cannot read query sidecar ({error})"),
276 )
277 })?;
278 toml::from_str(&text)
279 .map(Some)
280 .map_err(|error| invalid(&sidecar_path, format!("invalid query sidecar ({error})")))
281}
282
283#[derive(Debug, Default, serde::Deserialize)]
285#[serde(deny_unknown_fields)]
286struct QuerySidecar {
287 name: Option<String>,
289 description: Option<String>,
291 order: Option<i64>,
293}
294
295fn humanize_stem(stem: &str) -> String {
300 let mut name = stem.replace(['_', '-'], " ");
301 if let Some(first) = name.get_mut(..1) {
304 first.make_ascii_uppercase();
305 }
306 name
307}
308
309fn normalize_query_text(mut text: String) -> String {
313 if text.starts_with('\u{feff}') {
314 text.replace_range(..'\u{feff}'.len_utf8(), "");
315 }
316 text.replace("\r\n", "\n").replace('\r', "\n")
317}
318
319fn non_blank(value: Option<String>) -> Option<String> {
321 value.filter(|text| !text.trim().is_empty())
322}
323
324fn utf8_stem(path: &Path) -> Option<String> {
328 path.file_stem()
329 .and_then(|stem| stem.to_str())
330 .map(str::to_owned)
331}
332
333fn invalid(path: &Path, message: String) -> QueryLibraryError {
334 QueryLibraryError::Invalid {
335 path: path.to_path_buf(),
336 message,
337 }
338}
339
340fn has_extension(path: &Path, extension: &str) -> bool {
341 path.extension()
342 .is_some_and(|ext| ext.to_str() == Some(extension))
343}
344
345fn has_extension_case_insensitive(path: &Path, extension: &str) -> bool {
349 path.extension().is_some_and(|ext| {
350 ext.to_str()
351 .is_some_and(|ext| ext.eq_ignore_ascii_case(extension))
352 })
353}
354
355fn warn_once(path: &Path, reason: &'static str) {
361 static WARNED: OnceLock<Mutex<HashSet<(PathBuf, &'static str)>>> = OnceLock::new();
362 let warned = WARNED.get_or_init(|| Mutex::new(HashSet::new()));
363 if warned
364 .lock()
365 .expect("query library warn-dedupe lock poisoned")
366 .insert((path.to_path_buf(), reason))
367 {
368 eprintln!("warning: query library skips {}: {reason}", path.display());
369 }
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375 use tempfile::tempdir;
376
377 fn write(dir: &Path, name: &str, contents: &[u8]) {
378 std::fs::write(dir.join(name), contents).unwrap();
379 }
380
381 #[test]
382 fn humanizes_stems() {
383 assert_eq!(humanize_stem("cities"), "Cities");
384 assert_eq!(humanize_stem("cities_by_country"), "Cities by country");
385 assert_eq!(humanize_stem("rdf4j_stats"), "Rdf4j stats");
386 assert_eq!(humanize_stem("2024_cities"), "2024 cities");
387 assert_eq!(humanize_stem("already-Cased"), "Already Cased");
388 assert_eq!(humanize_stem("城市"), "城市");
390 }
391
392 #[test]
393 fn normalizes_bom_and_line_endings() {
394 assert_eq!(
395 normalize_query_text("\u{feff}SELECT 1".to_owned()),
396 "SELECT 1"
397 );
398 assert_eq!(normalize_query_text("a\r\nb\rc".to_owned()), "a\nb\nc");
399 assert_eq!(normalize_query_text("a\nb".to_owned()), "a\nb");
400 }
401
402 #[test]
403 fn directory_sorts_by_order_then_id_and_derives_names() {
404 let dir = tempdir().unwrap();
405 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
406 fs::create_dir_all(&repo).unwrap();
407 write(&repo, "alpha.rq", b"SELECT ?s WHERE { ?s ?p ?o }");
408 write(&repo, "beta.rq", b"SELECT 1");
409 write(
410 &repo,
411 "beta.toml",
412 b"name = \"Beta cities\"\ndescription = \"Two-word description\"\norder = 10\n",
413 );
414 write(&repo, "gamma.rq", b"SELECT 2");
415 write(&repo, "README.md", b"not a query\n");
416 write(&repo, ".hidden.rq", b"SELECT 3");
417 write(&repo, "delta.toml", b"name = \"Orphan\"\n");
419
420 let library = QueryLibrary::Directory(dir.path().to_path_buf());
421 let queries = library.load("main").unwrap();
422 assert_eq!(
423 queries,
424 vec![
425 ServerQuery {
426 id: "alpha".into(),
427 name: "Alpha".into(),
428 description: None,
429 query: "SELECT ?s WHERE { ?s ?p ?o }".into(),
430 },
431 ServerQuery {
432 id: "gamma".into(),
433 name: "Gamma".into(),
434 description: None,
435 query: "SELECT 2".into(),
436 },
437 ServerQuery {
438 id: "beta".into(),
439 name: "Beta cities".into(),
440 description: Some("Two-word description".into()),
441 query: "SELECT 1".into(),
442 },
443 ]
444 );
445 }
446
447 #[test]
448 fn blank_sidecar_fields_fall_back_to_derived_name() {
449 let dir = tempdir().unwrap();
450 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
451 fs::create_dir_all(&repo).unwrap();
452 write(&repo, "delta.rq", b"SELECT 4");
453 write(&repo, "delta.toml", b"name = \"\"\ndescription = \" \"\n");
454
455 let library = QueryLibrary::Directory(dir.path().to_path_buf());
456 let queries = library.load("main").unwrap();
457 assert_eq!(queries.len(), 1);
458 assert_eq!(queries[0].name, "Delta");
459 assert_eq!(queries[0].description, None);
460 }
461
462 #[test]
463 fn missing_repository_directory_is_missing() {
464 let dir = tempdir().unwrap();
465 let library = QueryLibrary::Directory(dir.path().to_path_buf());
466 assert!(matches!(
467 library.load("main"),
468 Err(QueryLibraryError::Missing(repo)) if repo == "main"
469 ));
470 }
471
472 #[test]
473 fn skips_oversized_empty_and_non_utf8_entries() {
474 let dir = tempdir().unwrap();
475 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
476 fs::create_dir_all(&repo).unwrap();
477 let oversized = vec![b'#'; MAX_QUERY_BYTES + 1];
478 write(&repo, "big.rq", &oversized);
479 write(&repo, "empty.rq", b" \n");
480 write(&repo, "binary.rq", b"\xff\xfe\xfd");
481 write(&repo, "good.rq", b"SELECT 5");
482 write(
483 &repo,
484 "orphan.toml",
485 b"description = \"nothing points here\"\n",
486 );
487
488 let library = QueryLibrary::Directory(dir.path().to_path_buf());
489 let queries = library.load("main").unwrap();
490 assert_eq!(queries.len(), 1);
491 assert_eq!(queries[0].id, "good");
492 }
493
494 #[test]
495 fn strict_sidecar_rejects_unknown_keys() {
496 let dir = tempdir().unwrap();
497 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
498 fs::create_dir_all(&repo).unwrap();
499 write(&repo, "typo.rq", b"SELECT 6");
500 write(&repo, "typo.toml", b"nam = \"misspelled\"\n");
501
502 let library = QueryLibrary::Directory(dir.path().to_path_buf());
503 match library.load("main") {
504 Err(QueryLibraryError::Invalid { path, message }) => {
505 assert!(path.ends_with("typo.toml"));
506 assert!(message.contains("invalid query sidecar"));
507 }
508 other => panic!("expected Invalid, got {other:?}"),
509 }
510 }
511
512 #[test]
513 fn bom_and_crlf_round_trip_through_the_loader() {
514 let dir = tempdir().unwrap();
515 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
516 fs::create_dir_all(&repo).unwrap();
517 write(
518 &repo,
519 "weather.rq",
520 "\u{feff}PREFIX ex: <http://ex/>\r\nSELECT ?w WHERE { ?c ex:hasWeather ?w . }\r\n"
521 .as_bytes(),
522 );
523
524 let library = QueryLibrary::Directory(dir.path().to_path_buf());
525 let queries = library.load("main").unwrap();
526 assert_eq!(
527 queries[0].query,
528 "PREFIX ex: <http://ex/>\nSELECT ?w WHERE { ?c ex:hasWeather ?w . }\n"
529 );
530 }
531
532 #[test]
533 fn inline_entries_keep_declaration_order() {
534 let entries = vec![
535 ServerQuery {
536 id: "z_last".into(),
537 name: "Z last".into(),
538 description: None,
539 query: "SELECT 1".into(),
540 },
541 ServerQuery {
542 id: "a_first".into(),
543 name: "A first".into(),
544 description: None,
545 query: "SELECT 2".into(),
546 },
547 ];
548 let library = QueryLibrary::Inline(entries.clone().into());
549 assert_eq!(library.load("main").unwrap(), entries);
551 }
552
553 #[test]
554 fn repeated_loads_are_deterministic() {
555 let dir = tempdir().unwrap();
556 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
557 fs::create_dir_all(&repo).unwrap();
558 for stem in ["one", "two", "three", "four"] {
559 write(&repo, &format!("{stem}.rq"), b"SELECT 1");
560 }
561 let library = QueryLibrary::Directory(dir.path().to_path_buf());
562 let first = library.load("main").unwrap();
563 let second = library.load("main").unwrap();
564 assert_eq!(first, second);
565 assert_eq!(
566 first.iter().map(|q| q.id.as_str()).collect::<Vec<_>>(),
567 vec!["four", "one", "three", "two"]
568 );
569 }
570
571 #[test]
572 #[cfg(unix)]
573 fn non_utf8_filenames_are_skipped_not_lossy_folded() {
574 use std::os::unix::ffi::OsStrExt;
575 let dir = tempdir().unwrap();
579 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
580 fs::create_dir_all(&repo).unwrap();
581 let unsafe_name = |bytes: &[u8]| std::ffi::OsStr::from_bytes(bytes).to_os_string();
582 std::fs::write(repo.join(unsafe_name(b"a\xff")), b"SELECT 6").unwrap();
583 std::fs::write(repo.join(unsafe_name(b"a\xfe")), b"SELECT 7").unwrap();
584 write(&repo, "good.rq", b"SELECT 1");
585
586 let library = QueryLibrary::Directory(dir.path().to_path_buf());
587 let queries = library.load("main").unwrap();
588 assert_eq!(queries.len(), 1);
589 assert_eq!(queries[0].id, "good");
590 }
591
592 #[cfg(unix)]
593 #[test]
594 fn dangling_symlink_is_skipped_not_a_server_error() {
595 let dir = tempdir().unwrap();
596 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
597 fs::create_dir_all(&repo).unwrap();
598 std::os::unix::fs::symlink(repo.join("missing.rq"), repo.join("gone.rq")).unwrap();
599 write(&repo, "real.rq", b"SELECT 1");
600
601 let library = QueryLibrary::Directory(dir.path().to_path_buf());
602 let queries = library.load("main").unwrap();
603 assert_eq!(queries.len(), 1);
604 assert_eq!(queries[0].id, "real");
605 }
606
607 #[test]
608 fn directory_named_like_a_query_does_not_match_its_sidecar() {
609 let dir = tempdir().unwrap();
613 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
614 fs::create_dir_all(repo.join("meta.rq")).unwrap();
615 write(&repo, "meta.toml", b"name = \"Orphan\"\n");
616 write(&repo, "real.rq", b"SELECT 1");
617
618 let library = QueryLibrary::Directory(dir.path().to_path_buf());
619 let queries = library.load("main").unwrap();
620 assert_eq!(queries.len(), 1);
621 assert_eq!(queries[0].id, "real");
622 }
623
624 #[test]
625 fn uppercase_extension_is_skipped() {
626 let dir = tempdir().unwrap();
627 let repo = waratah_storage::queries_repo_dir(dir.path(), "main");
628 fs::create_dir_all(&repo).unwrap();
629 write(&repo, "LOUD.RQ", b"SELECT 1");
630 write(&repo, "quiet.rq", b"SELECT 2");
631
632 let library = QueryLibrary::Directory(dir.path().to_path_buf());
633 let queries = library.load("main").unwrap();
634 assert_eq!(
635 queries.iter().map(|q| q.id.as_str()).collect::<Vec<_>>(),
636 vec!["quiet"]
637 );
638 }
639}