1use std::io::{self, Write};
18use std::net::SocketAddr;
19use std::path::{Path, PathBuf};
20use std::process::{Child, Command};
21use std::sync::Arc;
22use std::time::{Duration, Instant};
23
24use oxrdf::{Literal, NamedNode};
25use oxrdfio::{RdfFormat, RdfSerializer};
26use tokio::io::{AsyncBufReadExt, BufReader};
27use waratah_api::{AppState, QueryDebug, ServerQuery, console_is_stub, console_missing_worker};
28use waratah_compute::{
29 ComputeNode, DescribeMode, HexastoreCatalog, HexastoreFlush, HexastoreInsert, HexastoreScan,
30 HexastoreStats, QueryResults, RetryPolicy, StringRegister, StringRegistryFlush, StringResolve,
31};
32use waratah_proto::pb;
33use waratah_proto::{HexastoreClient, StringRegistryClient};
34use waratah_router::{ClusterConfig, RegistryNodeId};
35use waratah_storage::{
36 CommitTs, GraphName, MAIN_REPOSITORY_ID, PartitionAxis, Quad, SnapshotId, ingest_staging_dir,
37 queries_repo_dir,
38};
39
40use crate::error::DevError;
41use crate::notebook::NotebookSession;
42use crate::shutdown::ShutdownWatch;
43
44const DEMO_COMMIT_TS: CommitTs = CommitTs(1);
46
47const STARTUP_TIMEOUT: Duration = Duration::from_secs(30);
49
50pub const DEFAULT_HTTP_ADDR: &str = "127.0.0.1:8080";
52
53const DEV_PID_FILE: &str = "waratah-dev.pid";
57
58const HTTP_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
64
65#[derive(Debug, Clone)]
67pub enum Backend {
68 Memory,
70 RocksDb(PathBuf),
72}
73
74#[derive(Debug, Clone)]
76pub struct DevOptions {
77 pub config: ClusterConfig,
79 pub backend: Backend,
81 pub bin_dir: PathBuf,
83 pub load_demo: bool,
85 pub query: Option<String>,
87 pub http: Option<SocketAddr>,
89 pub debug: bool,
91 pub standalone: bool,
93 pub describe_mode: DescribeMode,
95 pub default_union: bool,
97 pub seat_by_total_cost: bool,
100 pub force_semi: bool,
102 pub eager_scan_filter: bool,
104 pub strict_sparql: bool,
107 pub ingest_dir: PathBuf,
109 pub queries_dir: Option<PathBuf>,
113 pub spill_dir: Option<PathBuf>,
115 pub notebooks: Option<waratah_notebook::NotebookOptions>,
118 pub ai: Option<waratah_api::AiConfig>,
121 pub ready_file: Option<PathBuf>,
125 pub debug_file: Option<PathBuf>,
129 pub pidfile: bool,
133 pub text_config: Option<waratah_text::TextPluginConfig>,
136}
137
138pub async fn start(mut options: DevOptions) -> Result<(), DevError> {
141 if let Some(http) = options.http {
142 options.config = options.config.with_advertised_urls(
143 format!("http://{http}/rdf4j/"),
144 format!("http://{http}/waratah/"),
145 );
146 }
147 write_pidfile(&options)?;
148 let notebooks = if options.query.is_none() {
151 NotebookSession::start(&options)?
155 } else {
156 if options.notebooks.is_some() {
157 eprintln!("note: --query ignores --with-notebooks (no HTTP server to proxy)");
158 }
159 if options.ai.is_some() {
160 eprintln!("note: --query ignores --with-ai (no HTTP server to proxy)");
161 }
162 None
163 };
164 let shutdown = ShutdownWatch::install();
165 let result = async {
169 if options.standalone {
170 let (compute, warm) = crate::standalone::open_compute(&options)?;
171 let compute = compute
172 .with_describe_mode(options.describe_mode)
173 .with_default_union(options.default_union)
174 .with_seat_by_total_cost(options.seat_by_total_cost)
175 .with_force_semi(options.force_semi)
176 .with_eager_scan_filter(options.eager_scan_filter)
177 .with_spill_root(options.spill_dir.clone());
178 println!("compute coordinator ready (in-process storage)");
179 run_session(
180 compute,
181 &options,
182 notebooks.as_ref(),
183 &shutdown,
184 WarmGate {
185 warm: Some(warm),
186 warnings: Vec::new(),
187 },
188 )
189 .await
190 } else {
191 let mut cluster = SpawnedCluster::spawn(&options)?;
192 let session = async {
193 let compute = ComputeNode::connect(&options.config, RetryPolicy::default_dev())
194 .await?
195 .with_describe_mode(options.describe_mode)
196 .with_default_union(options.default_union)
197 .with_seat_by_total_cost(options.seat_by_total_cost)
198 .with_force_semi(options.force_semi)
199 .with_eager_scan_filter(options.eager_scan_filter)
200 .with_spill_root(options.spill_dir.clone());
201 let warnings = wait_cluster_warm(&options.config).await?;
206 println!(
207 "compute coordinator ready ({} processes)",
208 options.config.process_count()
209 );
210 run_session(
211 compute,
212 &options,
213 notebooks.as_ref(),
214 &shutdown,
215 WarmGate {
216 warm: None,
217 warnings,
218 },
219 )
220 .await
221 }
222 .await;
223 cluster.shutdown();
224 session
225 }
226 }
227 .await;
228 if let Some(notebooks) = notebooks {
229 notebooks.stop().await;
230 }
231 remove_pidfile(&options);
232 result
233}
234
235pub async fn stop(data_dir: Option<PathBuf>) -> Result<(), DevError> {
241 let pid_file = pidfile_path(data_dir.as_deref());
242 let text = std::fs::read_to_string(&pid_file).map_err(|_| {
243 DevError::DevStop(format!(
244 "no pidfile at {} — `waratah start` writes one next to --data-dir \
245 (or into the working directory for a memory-backend daemon)",
246 pid_file.display()
247 ))
248 })?;
249 let pid: libc::pid_t = text
250 .trim()
251 .parse()
252 .map_err(|_| DevError::DevStop(format!("pidfile {} is not a pid", pid_file.display())))?;
253 if pid == std::process::id() as libc::pid_t {
254 return Err(DevError::DevStop(
255 "pidfile names this process; refusing to stop ourselves".to_owned(),
256 ));
257 }
258 if unsafe { libc::kill(pid, libc::SIGTERM) } != 0 {
260 return Err(DevError::DevStop(format!(
261 "could not signal pid {pid}: {}",
262 std::io::Error::last_os_error()
263 )));
264 }
265 let deadline = Instant::now() + Duration::from_secs(20);
268 while Instant::now() < deadline {
269 if !process_alive(pid) {
270 println!("cluster (pid {pid}) stopped");
271 return Ok(());
272 }
273 tokio::time::sleep(Duration::from_millis(100)).await;
274 }
275 eprintln!("cluster (pid {pid}) did not exit within 20s; sending SIGKILL");
276 unsafe { libc::kill(pid, libc::SIGKILL) };
278 Ok(())
279}
280
281fn process_alive(pid: libc::pid_t) -> bool {
286 if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat"))
287 && let Some(rest) = stat.rsplit(')').next()
288 && rest.trim_start().starts_with('Z')
289 {
290 return false;
291 }
292 unsafe { libc::kill(pid, 0) == 0 }
295}
296
297fn data_dir(options: &DevOptions) -> Option<&Path> {
298 match &options.backend {
299 Backend::RocksDb(path) => Some(path),
300 Backend::Memory => None,
301 }
302}
303
304fn pidfile_dir(options: &DevOptions) -> PathBuf {
308 match data_dir(options) {
309 Some(dir) => dir.to_path_buf(),
310 None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
311 }
312}
313
314pub(crate) fn pidfile_path(data_dir: Option<&Path>) -> PathBuf {
317 match data_dir {
318 Some(dir) => dir.join(DEV_PID_FILE),
319 None => std::env::current_dir()
320 .unwrap_or_else(|_| PathBuf::from("."))
321 .join(DEV_PID_FILE),
322 }
323}
324
325pub(crate) fn remove_pidfile_if_names(path: &Path, pid: libc::pid_t) -> bool {
330 match std::fs::read_to_string(path) {
331 Ok(text) if text.trim() == pid.to_string() => std::fs::remove_file(path).is_ok(),
332 _ => false,
333 }
334}
335
336fn write_pidfile(options: &DevOptions) -> Result<(), DevError> {
341 if !options.pidfile {
342 return Ok(());
343 }
344 let path = pidfile_path(data_dir(options));
345 if let Ok(text) = std::fs::read_to_string(&path)
346 && let Ok(pid) = text.trim().parse::<u32>()
347 && pid != std::process::id()
348 && process_alive(pid as libc::pid_t)
349 {
350 return Err(DevError::PidfileInUse { path, pid });
351 }
352 if let Err(error) = std::fs::create_dir_all(pidfile_dir(options)) {
357 eprintln!(
358 "could not create {}: {error}",
359 pidfile_dir(options).display()
360 );
361 return Ok(());
362 }
363 if let Err(error) = std::fs::write(&path, std::process::id().to_string()) {
364 eprintln!("could not write {}: {error}", path.display());
365 }
366 Ok(())
367}
368
369fn another_server_using_storage(data_dir: Option<&Path>) -> bool {
377 let Some(dir) = data_dir else {
378 return false;
379 };
380 let Ok(text) = std::fs::read_to_string(pidfile_path(Some(dir))) else {
381 return false;
382 };
383 let Ok(pid) = text.trim().parse::<u32>() else {
384 return false;
385 };
386 pid != std::process::id() && process_alive(pid as libc::pid_t)
387}
388
389fn remove_pidfile(options: &DevOptions) {
390 if !options.pidfile {
391 return;
392 }
393 remove_pidfile_if_names(
397 &pidfile_path(data_dir(options)),
398 std::process::id() as libc::pid_t,
399 );
400}
401
402fn log_spill_root(spill_root: Option<&Path>) {
408 match spill_root {
409 Some(root) => {
410 println!("spill root: {}", root.display());
411 if is_tmpfs(root) {
412 eprintln!(
413 "WARN: spill root {} is tmpfs-backed; spilled pages will remain in RAM. \
414 Set --spill-dir to a disk-backed path.",
415 root.display()
416 );
417 }
418 }
419 None => {
420 eprintln!(
421 "WARN: no spill root configured (memory backend); query spill files go to {} \
422 which may be RAM-backed (tmpfs) — spilled pages will remain in RAM. \
423 Use --data-dir or --spill-dir for disk-backed spill.",
424 std::env::temp_dir().display()
425 );
426 }
427 }
428}
429
430#[cfg(target_os = "linux")]
433fn is_tmpfs(path: &Path) -> bool {
434 use std::ffi::CString;
435 let Ok(cpath) = CString::new(path.as_os_str().as_encoded_bytes()) else {
436 return false;
437 };
438 let mut stat: libc::statfs = unsafe { std::mem::zeroed() };
439 let rc = unsafe { libc::statfs(cpath.as_ptr(), &mut stat) };
442 rc == 0 && stat.f_type == libc::TMPFS_MAGIC as libc::__fsword_t
445}
446
447#[cfg(not(target_os = "linux"))]
448fn is_tmpfs(_path: &Path) -> bool {
449 false
450}
451
452pub(crate) struct WarmGate {
457 warm: Option<std::sync::Arc<waratah_storage::WarmState>>,
458 warnings: Vec<String>,
459}
460
461impl WarmGate {
462 async fn wait_ready(&self) {
466 let Some(warm) = &self.warm else {
467 return;
468 };
469 while !warm.is_done() {
470 if warm.stuck_warning().is_some() {
471 return;
472 }
473 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
474 }
475 }
476}
477
478async fn run_session<H, R>(
479 mut compute: ComputeNode<H, R>,
480 options: &DevOptions,
481 notebooks: Option<&NotebookSession>,
482 shutdown: &ShutdownWatch,
483 warm_gate: WarmGate,
484) -> Result<(), DevError>
485where
486 H: HexastoreInsert
487 + HexastoreScan
488 + HexastoreCatalog
489 + HexastoreFlush
490 + HexastoreStats
491 + waratah_compute::HexastoreAdmin
492 + waratah_compute::HexastoreAxisHeadStats
493 + waratah_compute::HexastoreGeo
494 + Clone
495 + Send
496 + Sync
497 + 'static,
498 R: StringRegister
499 + StringResolve
500 + StringRegistryFlush
501 + waratah_compute::BlobStoreClient
502 + waratah_compute::RegistryAdmin
503 + Clone
504 + Send
505 + Sync
506 + 'static,
507{
508 const REBUILD_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30 * 60);
513
514 log_spill_root(compute.spill_root());
515
516 if options.strict_sparql {
519 waratah_compute::strict_sparql::set_strict_sparql(true);
520 println!("strict-sparql mode: documented deviations are gated off");
521 }
522
523 if options.load_demo {
524 let quads = demo_dataset();
525 let result = compute.insert_quads(&quads, DEMO_COMMIT_TS).await?;
526 println!(
527 "loaded {} quads at commit_ts={} ({} registry entries)",
528 result.quads, DEMO_COMMIT_TS.0, result.registered
529 );
530 compute.flush_memtables().await?;
531 println!("flushed memtables on S/P/O");
532 }
533
534 let profile = compute.refresh_stats().await?;
539 println!(
540 "rolled up sketch profile ({} puts observed on preferred axis)",
541 profile.total_puts
542 );
543
544 if let Ok(describe) = compute
550 .queries()
551 .hexastore()
552 .describe(PartitionAxis::O)
553 .await
554 {
555 compute.set_geo_index_epoch(describe.geo_index_epoch);
556 if let Some(epoch) = describe.geo_index_epoch {
557 println!("geo rebuild-index epoch: {epoch}");
558 }
559 }
560
561 let temporal_config = waratah_temporal::ingest_coverer_config();
570 match compute
571 .queries()
572 .hexastore()
573 .describe(PartitionAxis::O)
574 .await
575 {
576 Ok(describe) => {
577 compute.set_temporal_index_epoch(describe.temporal_index_epoch);
578 match describe.temporal_index_epoch {
579 Some(epoch) => println!("temporal rebuild-index epoch: {epoch}"),
580 None => {
581 println!(
582 "temporal index epoch missing; auto-rebuild starting (startup blocks until it lands)"
583 );
584 match compute
585 .queries()
586 .hexastore()
587 .rebuild_temporal_index(temporal_config)
588 .await
589 {
590 Ok((started, already_in_progress)) => {
591 if already_in_progress {
592 println!("rebuild already in progress; waiting for the epoch");
593 } else if started {
594 println!("rebuild started on the O partition");
595 }
596 let deadline = std::time::Instant::now() + REBUILD_WAIT_TIMEOUT;
605 loop {
606 if std::time::Instant::now() >= deadline {
607 eprintln!(
608 "warning: temporal auto-rebuild did not finish within {:?}; continuing UNINDEXED",
609 REBUILD_WAIT_TIMEOUT
610 );
611 break;
612 }
613 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
614 match compute
615 .queries()
616 .hexastore()
617 .describe(PartitionAxis::O)
618 .await
619 {
620 Ok(describe) => match describe.temporal_index_epoch {
621 Some(epoch) => {
622 compute.set_temporal_index_epoch(Some(epoch));
623 println!(
624 "temporal rebuild-index complete (epoch {epoch})"
625 );
626 break;
627 }
628 None => {
629 if !describe.temporal_rebuild_in_progress {
630 eprintln!(
631 "warning: temporal rebuild ended without stamping an epoch; continuing UNINDEXED (run `waratah temporal rebuild-index`)"
632 );
633 break;
634 }
635 continue;
636 }
637 },
638 Err(error) => {
639 eprintln!(
640 "warning: temporal auto-rebuild wait failed ({error}); continuing UNINDEXED"
641 );
642 break;
643 }
644 }
645 }
646 }
647 Err(error) => {
648 eprintln!(
649 "warning: temporal auto-rebuild trigger failed ({error}); continuing UNINDEXED"
650 );
651 }
652 }
653 }
654 }
655 }
656 Err(error) => {
657 eprintln!("warning: temporal epoch probe failed ({error}); continuing UNINDEXED");
658 }
659 }
660
661 let geo_report = match compute
670 .queries()
671 .hexastore()
672 .describe(PartitionAxis::O)
673 .await
674 {
675 Ok(describe) => {
676 compute.set_geo_index_epoch(describe.geo_index_epoch);
677 match describe.geo_index_epoch {
678 Some(epoch) => {
679 println!("geo rebuild-index epoch: {epoch}");
680 None
681 }
682 None => {
683 println!(
684 "geo index epoch missing; auto-upgrade/rebuild starting (startup blocks until it lands)"
685 );
686 match crate::geo_upgrade::drive_geo_upgrade(
687 compute.queries().hexastore(),
688 compute.queries().registry(),
689 )
690 .await
691 {
692 Ok(Some(report)) => {
693 println!("geo index upgrade done: {}", report.summary());
694 match compute
695 .queries()
696 .hexastore()
697 .describe(PartitionAxis::O)
698 .await
699 {
700 Ok(describe) => describe.geo_index_epoch,
701 Err(_) => None,
702 }
703 }
704 Ok(None) => {
707 let deadline = std::time::Instant::now() + REBUILD_WAIT_TIMEOUT;
708 loop {
709 if std::time::Instant::now() >= deadline {
710 eprintln!(
711 "warning: geo auto-rebuild did not finish within {:?}; continuing UNINDEXED",
712 REBUILD_WAIT_TIMEOUT
713 );
714 break None;
715 }
716 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
717 match compute
718 .queries()
719 .hexastore()
720 .describe(PartitionAxis::O)
721 .await
722 {
723 Ok(describe) => match describe.geo_index_epoch {
724 Some(epoch) => break Some(epoch),
725 None => {
726 if !describe.geo_rebuild_in_progress {
727 eprintln!(
728 "warning: geo rebuild ended without stamping an epoch; continuing UNINDEXED (run `waratah geo rebuild-index`)"
729 );
730 break None;
731 }
732 continue;
733 }
734 },
735 Err(error) => {
736 eprintln!(
737 "warning: geo auto-rebuild wait failed ({error}); continuing UNINDEXED"
738 );
739 break None;
740 }
741 }
742 }
743 }
744 Err(error) => {
745 eprintln!(
746 "warning: geo auto-upgrade failed ({error}); continuing UNINDEXED"
747 );
748 None
749 }
750 }
751 }
752 }
753 }
754 Err(error) => {
755 eprintln!("warning: geo epoch probe failed ({error}); continuing UNINDEXED");
756 None
757 }
758 };
759 compute.set_geo_index_epoch(geo_report);
761
762 if let Some(text_config) = options.text_config.clone() {
771 let fingerprint = text_config.fingerprint();
772 match compute
773 .queries()
774 .hexastore()
775 .describe(PartitionAxis::O)
776 .await
777 {
778 Ok(describe) => {
779 compute.set_text_index_state(
780 describe.text_index_epoch,
781 describe.text_index_fingerprint.clone(),
782 );
783 match describe.text_index_epoch {
784 Some(epoch) if describe.text_index_fingerprint == fingerprint => {
785 println!(
786 "text rebuild-index epoch: {epoch} ({} docs, analyzer {}, seed {})",
787 describe.text_index_terms, text_config.analyzer, text_config.seed_chars
788 );
789 }
790 Some(_epoch) => {
791 return Err(DevError::Backend(format!(
792 "the text index was built with {} but this process requires {fingerprint}. \
793 This build never rebuilds it automatically: stop the cluster and run \
794 `waratah text rebuild-index --data-dir <data-dir>` (it rebuilds from \
795 the hexastore), or remove the index directory and re-import",
796 describe.text_index_fingerprint
797 )));
798 }
799 None => {
800 if another_server_using_storage(data_dir(options)) {
810 return Err(DevError::Backend(
811 "cannot create text index while another compute node \
812 is using this storage; stop the other server first \
813 (its startup build covers the store), or run \
814 `waratah text rebuild-index` offline"
815 .to_owned(),
816 ));
817 }
818 println!(
819 "text index epoch missing; auto-build starting (startup blocks until it lands)"
820 );
821 let allow = text_config.predicate_allowlist();
822 match waratah_text::drive_text_rebuild(
823 compute.queries().hexastore(),
824 compute.queries().registry(),
825 &text_config.analyzer,
826 text_config.seed_chars as u32,
827 &fingerprint,
828 allow.as_ref(),
829 true,
835 )
836 .await
837 {
838 Ok(Some(report)) => {
839 println!("text index build done: {}", report.summary());
840 if let Ok(describe) = compute
841 .queries()
842 .hexastore()
843 .describe(PartitionAxis::O)
844 .await
845 {
846 compute.set_text_index_state(
847 describe.text_index_epoch,
848 describe.text_index_fingerprint.clone(),
849 );
850 }
851 }
852 Ok(None) => {
855 let deadline = std::time::Instant::now() + REBUILD_WAIT_TIMEOUT;
856 loop {
857 if std::time::Instant::now() >= deadline {
858 eprintln!(
859 "warning: text auto-build did not finish within {:?}; continuing UNINDEXED",
860 REBUILD_WAIT_TIMEOUT
861 );
862 break;
863 }
864 tokio::time::sleep(std::time::Duration::from_millis(250)).await;
865 match compute
866 .queries()
867 .hexastore()
868 .describe(PartitionAxis::O)
869 .await
870 {
871 Ok(describe) => match describe.text_index_epoch {
872 Some(epoch) => {
873 compute.set_text_index_state(
874 Some(epoch),
875 describe.text_index_fingerprint.clone(),
876 );
877 println!(
878 "text rebuild-index complete (epoch {epoch})"
879 );
880 break;
881 }
882 None => {
883 if !describe.text_rebuild_in_progress {
884 eprintln!(
885 "warning: text build ended without stamping an epoch; continuing UNINDEXED (run `waratah text rebuild-index`)"
886 );
887 break;
888 }
889 continue;
890 }
891 },
892 Err(error) => {
893 eprintln!(
894 "warning: text auto-build wait failed ({error}); continuing UNINDEXED"
895 );
896 break;
897 }
898 }
899 }
900 }
901 Err(error) => {
902 eprintln!(
903 "warning: text auto-build failed ({error}); continuing UNINDEXED"
904 );
905 }
906 }
907 }
908 }
909 }
910 Err(error) => {
911 eprintln!("warning: text epoch probe failed ({error}); continuing UNINDEXED");
912 }
913 }
914 }
915
916 let (debug, debug_target) = match &options.debug_file {
919 Some(path) => {
920 let file = std::fs::OpenOptions::new()
921 .create(true)
922 .write(true)
923 .truncate(true)
924 .open(path)?;
925 let handle = std::sync::Arc::new(std::sync::Mutex::new(file));
926 (
927 QueryDebug::to_file(handle),
928 format!("file {}", path.display()),
929 )
930 }
931 None => (QueryDebug::from_enabled(options.debug), "stderr".to_owned()),
932 };
933 if options.debug {
934 eprintln!(
935 "SPARQL debug logging enabled (query text, timing, and client errors on {debug_target})"
936 );
937 }
938
939 match &options.query {
940 Some(sparql) => {
941 warm_gate.wait_ready().await;
942 run_query(&compute, sparql, &debug).await
943 }
944 None => match options.http {
945 Some(addr) => {
946 spawn_compute_admin(options)?;
947 if console_is_stub() {
948 eprintln!(
949 "warning: Waratah console is a build-time stub (no grevillea dist-console was embedded). \
950 Run `pnpm build:console` in grevillea or set WARATAH_CONSOLE_DIST and rebuild."
951 );
952 } else if console_missing_worker() {
953 eprintln!(
954 "warning: embedded console has no sw.js, so SPARQL graph downloads will fail. \
955 Run `pnpm build:console` in grevillea and rebuild waratah."
956 );
957 }
958 println!("Waratah console: http://{addr}/");
959 println!("RDF4J REST API: http://{addr}/rdf4j/");
960 println!(" protocol: http://{addr}/rdf4j/protocol");
961 println!(" repository: http://{addr}/rdf4j/repositories/main");
962 println!(
963 " explain: http://{addr}/rdf4j/repositories/main/explain?query=..."
964 );
965 println!(" cluster: http://{addr}/waratah/cluster");
966 println!(" health: http://{addr}/waratah/health");
967 if notebooks.is_some() {
968 println!(
969 " notebooks: http://{addr}/jupyter (status: http://{addr}/waratah/notebooks)"
970 );
971 }
972 if let Some(ai) = &options.ai {
973 let upstreams = ai
974 .upstreams
975 .iter()
976 .map(|upstream| upstream.id.as_str())
977 .collect::<Vec<_>>()
978 .join(", ");
979 println!(" ai: http://{addr}/waratah/ai (upstreams: {upstreams})");
980 }
981 let staging = ingest_staging_dir(&options.ingest_dir, MAIN_REPOSITORY_ID);
982 std::fs::create_dir_all(&staging)?;
983 println!(" ingest: http://{addr}/waratah/repositories/main/ingest");
984 println!(" ingest-dir: {}", staging.display());
985 match &options.queries_dir {
986 Some(dir) => {
987 println!(
988 " queries: http://{addr}/waratah/repositories/main/queries"
989 );
990 let repo_dir = queries_repo_dir(dir, MAIN_REPOSITORY_ID);
991 println!(" queries-dir: {}", repo_dir.display());
992 if !repo_dir.is_dir() {
996 eprintln!(
997 "warning: queries-dir {} does not exist; \
998 /queries will answer 404 until it does",
999 repo_dir.display()
1000 );
1001 }
1002 }
1003 None if options.load_demo => {
1004 println!(
1005 " queries: http://{addr}/waratah/repositories/main/queries"
1006 );
1007 println!(" queries-dir: (built-in demo queries)");
1008 }
1009 None => {}
1010 }
1011 let listener = waratah_api::bind_http(addr).await?;
1017 if let Some(status) = &options.ready_file {
1026 crate::daemon::report_ready(status);
1027 }
1028 let mut app_state = AppState::new(compute)
1029 .with_query_debug(debug)
1030 .with_ingest_dir(options.ingest_dir.clone())
1031 .with_warm_state(warm_gate.warm.clone())
1032 .with_startup_warnings(warm_gate.warnings.clone());
1033 app_state = match options.queries_dir.clone() {
1036 Some(dir) => app_state.with_queries_dir(dir),
1037 None if options.load_demo => app_state.with_inline_queries(demo_queries()),
1038 None => app_state,
1039 };
1040 if let Some(notebooks) = notebooks {
1041 app_state = app_state.with_notebooks(notebooks.state.clone());
1042 }
1043 if let Some(ai) = &options.ai {
1044 app_state =
1045 app_state.with_ai(Arc::new(waratah_api::AiService::new(ai.clone())));
1046 }
1047 serve_http_until(listener, app_state, shutdown).await?;
1048 Ok(())
1049 }
1050 None => {
1051 warm_gate.wait_ready().await;
1052 spawn_compute_admin(options)?;
1053 repl(&compute, &debug, shutdown).await
1054 }
1055 },
1056 }
1057}
1058
1059async fn serve_http_until<C>(
1068 listener: tokio::net::TcpListener,
1069 state: AppState<C>,
1070 shutdown: &ShutdownWatch,
1071) -> Result<(), DevError>
1072where
1073 C: waratah_api::ComputeBackend + Clone + Send + Sync + 'static,
1074{
1075 let server = waratah_api::serve_bound_with_shutdown(listener, state, shutdown.triggered());
1076 tokio::pin!(server);
1077 tokio::select! {
1078 result = &mut server => return result.map_err(DevError::from),
1079 _ = shutdown.triggered() => {}
1080 }
1081 match tokio::time::timeout(HTTP_DRAIN_TIMEOUT, &mut server).await {
1082 Ok(result) => result.map_err(DevError::from),
1083 Err(_elapsed) => {
1084 eprintln!("forcing HTTP connections closed (open kernel channels do not drain)");
1085 Ok(())
1086 }
1087 }
1088}
1089
1090fn spawn_compute_admin(options: &DevOptions) -> Result<(), DevError> {
1091 let addr = options.config.compute();
1092 let service = waratah_compute::ComputeAdminService::new(
1093 std::sync::Arc::new(options.config.clone()),
1094 options.describe_mode,
1095 options.default_union,
1096 )?
1097 .with_standalone(options.standalone);
1098 let incoming = waratah_compute::bind_compute_admin(addr)?;
1101 println!("compute gRPC Describe/Health listening on {addr}");
1102 tokio::spawn(async move {
1103 if let Err(error) = waratah_compute::serve_compute_admin_incoming(incoming, service).await {
1104 eprintln!("compute gRPC server stopped: {error}");
1105 }
1106 });
1107 Ok(())
1108}
1109
1110async fn run_query<H, R>(
1111 compute: &ComputeNode<H, R>,
1112 sparql: &str,
1113 debug: &QueryDebug,
1114) -> Result<(), DevError>
1115where
1116 H: HexastoreScan + HexastoreCatalog + waratah_compute::HexastoreGeo + Send + Sync,
1117 R: StringResolve + waratah_compute::BlobStoreClient + Send + Sync,
1118{
1119 let span = debug.received(sparql);
1120 let ctx = debug.query_context(&span, compute.queries().context(SnapshotId::latest()));
1121 match compute.query_with(sparql, &ctx).await {
1122 Ok(results) => {
1123 span.finished(results.len());
1124 print_query_results(&results)?;
1125 io::stdout().flush()?;
1126 Ok(())
1127 }
1128 Err(error) => {
1129 span.fail_msg(&error);
1130 Err(error.into())
1131 }
1132 }
1133}
1134
1135async fn repl<H, R>(
1137 compute: &ComputeNode<H, R>,
1138 debug: &QueryDebug,
1139 shutdown: &ShutdownWatch,
1140) -> Result<(), DevError>
1141where
1142 H: HexastoreScan + HexastoreCatalog + waratah_compute::HexastoreGeo + Send + Sync,
1143 R: StringResolve + waratah_compute::BlobStoreClient + Send + Sync,
1144{
1145 let mut lines = BufReader::new(tokio::io::stdin()).lines();
1146 eprintln!("enter one SPARQL query per line; `quit` or EOF to stop");
1147 loop {
1148 eprint!("waratah> ");
1149 io::stderr().flush()?;
1150 let line = tokio::select! {
1151 line = lines.next_line() => line,
1152 _ = shutdown.triggered() => break,
1153 };
1154 let Some(line) = line? else {
1155 break;
1156 };
1157 let query = line.trim();
1158 if query.is_empty() {
1159 continue;
1160 }
1161 if matches!(query, "quit" | "exit") {
1162 break;
1163 }
1164 let span = debug.received(query);
1165 let ctx = debug.query_context(&span, compute.queries().context(SnapshotId::latest()));
1166 match compute.query_with(query, &ctx).await {
1167 Ok(results) => {
1168 span.finished(results.len());
1169 if let Err(error) = print_query_results(&results) {
1170 eprintln!("error: {error}");
1171 }
1172 io::stdout().flush()?;
1173 }
1174 Err(error) => {
1175 span.fail_msg(&error);
1176 eprintln!("error: {error}");
1177 }
1178 }
1179 }
1180 Ok(())
1181}
1182
1183fn print_query_results(results: &QueryResults) -> Result<(), DevError> {
1184 match results {
1185 QueryResults::Solutions { .. } | QueryResults::Boolean(_) => {
1186 print!("{}", results.to_tsv());
1187 }
1188 QueryResults::Graph { triples } => {
1189 let mut serializer =
1190 RdfSerializer::from_format(RdfFormat::Turtle).for_writer(Vec::new());
1191 for triple in triples {
1192 let quad = Quad {
1193 subject: triple.subject.clone(),
1194 predicate: triple.predicate.clone(),
1195 object: triple.object.clone(),
1196 graph_name: GraphName::DefaultGraph,
1197 };
1198 serializer.serialize_quad(&quad)?;
1199 }
1200 let bytes = serializer.finish()?;
1201 print!("{}", String::from_utf8_lossy(&bytes));
1202 }
1203 }
1204 Ok(())
1205}
1206
1207pub(crate) struct SpawnedCluster {
1209 children: Vec<(String, Child)>,
1210}
1211
1212impl SpawnedCluster {
1213 pub(crate) fn spawn(options: &DevOptions) -> Result<Self, DevError> {
1214 let mut cluster = Self {
1215 children: Vec::new(),
1216 };
1217 let serve_cores = crate::affinity::serve_core_set();
1223
1224 for axis in PartitionAxis::ALL {
1225 let addr = options.config.hexastore(axis)?;
1226 let mut command = Command::new(binary(&options.bin_dir, "waratah-partition"));
1227 if let Some(set) = &serve_cores {
1228 crate::affinity::confine_child(&mut command, set);
1229 }
1230 command
1231 .arg("--axis")
1232 .arg(axis.as_str())
1233 .arg("--listen")
1234 .arg(addr.to_string());
1235 match &options.backend {
1236 Backend::Memory => {
1237 command.arg("--memory");
1238 }
1239 Backend::RocksDb(path) => {
1240 command.arg("--data-dir").arg(path);
1241 }
1242 }
1243 if axis == PartitionAxis::O
1249 && let Some(text) = &options.text_config
1250 {
1251 command
1252 .arg("--text-analyzer")
1253 .arg(&text.analyzer)
1254 .arg("--text-seed-chars")
1255 .arg(text.seed_chars.to_string())
1256 .arg("--text-fingerprint")
1257 .arg(text.fingerprint());
1258 }
1259 if options.debug {
1260 command.arg("--trace");
1263 }
1264 cluster.push(format!("hexastore-{axis}"), addr, command)?;
1265 }
1266
1267 let addr = options.config.registry(RegistryNodeId(0))?;
1268 let mut command = Command::new(binary(&options.bin_dir, "waratah-registry"));
1269 if let Some(set) = &serve_cores {
1270 crate::affinity::confine_child(&mut command, set);
1271 }
1272 command.arg("--listen").arg(addr.to_string());
1273 if let Backend::RocksDb(path) = &options.backend {
1274 command.arg("--data-dir").arg(path);
1275 }
1276 if options.debug {
1277 command.arg("--trace");
1279 }
1280 cluster.push("string-registry".to_owned(), addr, command)?;
1281
1282 Ok(cluster)
1283 }
1284
1285 fn push(
1286 &mut self,
1287 name: String,
1288 addr: SocketAddr,
1289 mut command: Command,
1290 ) -> Result<(), DevError> {
1291 let child = command.spawn().map_err(|source| DevError::Spawn {
1292 program: format!("{:?}", command.get_program()),
1293 source,
1294 })?;
1295 self.children.push((name.clone(), child));
1296 wait_until_listening(&name, addr)?;
1297 println!("{name} listening on {addr}");
1298 Ok(())
1299 }
1300
1301 pub(crate) fn shutdown(&mut self) {
1302 for (name, child) in &mut self.children {
1303 if let Err(error) = child.kill() {
1304 eprintln!("could not stop {name}: {error}");
1305 }
1306 let _ = child.wait();
1307 }
1308 self.children.clear();
1309 }
1310}
1311
1312impl Drop for SpawnedCluster {
1313 fn drop(&mut self) {
1314 self.shutdown();
1315 }
1316}
1317
1318fn binary(bin_dir: &Path, name: &str) -> PathBuf {
1319 bin_dir.join(format!("{name}{}", std::env::consts::EXE_SUFFIX))
1320}
1321
1322fn wait_until_listening(name: &str, addr: SocketAddr) -> Result<(), DevError> {
1324 let deadline = Instant::now() + STARTUP_TIMEOUT;
1325 while Instant::now() < deadline {
1326 if std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(200)).is_ok() {
1327 return Ok(());
1328 }
1329 std::thread::sleep(Duration::from_millis(50));
1330 }
1331 Err(DevError::StartupTimeout {
1332 process: name.to_owned(),
1333 addr,
1334 })
1335}
1336
1337async fn wait_cluster_warm(config: &ClusterConfig) -> Result<Vec<String>, DevError> {
1346 let mut clients: Vec<(String, WarmProbe)> = Vec::new();
1348 for axis in PartitionAxis::ALL {
1349 let addr = config.hexastore(axis)?;
1350 let client = HexastoreClient::connect(format!("http://{addr}"))
1351 .await
1352 .map_err(|source| DevError::Spawn {
1353 program: format!("hexastore-{} health client", axis.as_str()),
1354 source: std::io::Error::other(source.to_string()),
1355 })?;
1356 clients.push((
1357 format!("axis-{}", axis.as_str()),
1358 WarmProbe::Hexastore(client),
1359 ));
1360 }
1361 let registry_addr = config.registry(RegistryNodeId(0))?;
1362 let registry_client = StringRegistryClient::connect(format!("http://{registry_addr}"))
1363 .await
1364 .map_err(|source| DevError::Spawn {
1365 program: "string-registry health client".to_owned(),
1366 source: std::io::Error::other(source.to_string()),
1367 })?;
1368 clients.push(("registry".to_owned(), WarmProbe::Registry(registry_client)));
1369
1370 let deadline = Instant::now() + waratah_storage::WARM_MAX_WAIT;
1371 loop {
1372 let mut pending: Vec<String> = Vec::new();
1373 for (name, probe) in &mut clients {
1374 let ready = match probe {
1375 WarmProbe::Hexastore(client) => client
1376 .health(pb::HealthRequest {})
1377 .await
1378 .map(|response| response.into_inner().warm_ready)
1379 .unwrap_or(false),
1380 WarmProbe::Registry(client) => client
1381 .health(pb::HealthRequest {})
1382 .await
1383 .map(|response| response.into_inner().warm_ready)
1384 .unwrap_or(false),
1385 };
1386 if !ready {
1387 pending.push(name.clone());
1388 }
1389 }
1390 if pending.is_empty() {
1391 return Ok(Vec::new());
1392 }
1393 if Instant::now() >= deadline {
1394 eprintln!(
1395 "warning: cache-warm stuck for {:?}; pending: {pending:?} — starting without a full warm",
1396 waratah_storage::WARM_MAX_WAIT
1397 );
1398 return Ok(vec![format!("cache-warm stuck; pending: {pending:?}")]);
1399 }
1400 tokio::time::sleep(Duration::from_millis(200)).await;
1401 }
1402}
1403
1404enum WarmProbe {
1407 Hexastore(HexastoreClient<tonic::transport::Channel>),
1408 Registry(StringRegistryClient<tonic::transport::Channel>),
1409}
1410
1411pub fn demo_queries() -> Vec<ServerQuery> {
1417 fn query(id: &str, name: &str, description: &str, body: &str) -> ServerQuery {
1418 ServerQuery {
1419 id: id.to_owned(),
1420 name: name.to_owned(),
1421 description: Some(description.to_owned()),
1422 query: format!("PREFIX ex: <http://ex/>\n{body}"),
1423 }
1424 }
1425
1426 vec![
1427 query(
1428 "people",
1429 "People",
1430 "Every ex:Person with its name",
1431 "SELECT ?person ?name WHERE {\n ?person a ex:Person ;\n ex:name ?name .\n}\nORDER BY ?name\n",
1432 ),
1433 query(
1434 "cities",
1435 "Cities by weather",
1436 "Cities and the weather recorded for them",
1437 "SELECT ?city ?weather WHERE {\n ?city a ex:City ;\n ex:hasWeather ?weather .\n}\nORDER BY ?city\n",
1438 ),
1439 query(
1440 "people-and-weather",
1441 "People and weather",
1442 "Where each person lives and what the weather is there",
1443 "SELECT ?person ?weather WHERE {\n ?person ex:livesIn ?city .\n ?city ex:hasWeather ?weather .\n}\nORDER BY ?person\n",
1444 ),
1445 ]
1446}
1447
1448pub fn demo_dataset() -> Vec<Quad> {
1456 fn iri(local: &str) -> NamedNode {
1457 NamedNode::new(format!("http://ex/{local}")).expect("valid demo IRI")
1458 }
1459 fn label(local: &str, text: &str) -> Quad {
1460 Quad::new(
1461 iri(local),
1462 oxrdf::vocab::rdfs::LABEL,
1463 Literal::from(text),
1464 GraphName::DefaultGraph,
1465 )
1466 }
1467 fn sub_class_of(child: &str, parent: &str) -> Quad {
1468 Quad::new(
1469 iri(child),
1470 oxrdf::vocab::rdfs::SUB_CLASS_OF,
1471 iri(parent),
1472 GraphName::DefaultGraph,
1473 )
1474 }
1475
1476 vec![
1477 Quad::new(
1478 iri("alice"),
1479 oxrdf::vocab::rdf::TYPE,
1480 iri("Person"),
1481 GraphName::DefaultGraph,
1482 ),
1483 Quad::new(
1484 iri("alice"),
1485 iri("name"),
1486 Literal::from("Alice"),
1487 GraphName::DefaultGraph,
1488 ),
1489 Quad::new(
1490 iri("bob"),
1491 oxrdf::vocab::rdf::TYPE,
1492 iri("Person"),
1493 GraphName::DefaultGraph,
1494 ),
1495 Quad::new(
1496 iri("bob"),
1497 iri("name"),
1498 Literal::from("Bob"),
1499 GraphName::DefaultGraph,
1500 ),
1501 Quad::new(
1502 iri("brisbane"),
1503 oxrdf::vocab::rdf::TYPE,
1504 iri("City"),
1505 GraphName::DefaultGraph,
1506 ),
1507 Quad::new(
1508 iri("hobart"),
1509 oxrdf::vocab::rdf::TYPE,
1510 iri("City"),
1511 GraphName::DefaultGraph,
1512 ),
1513 Quad::new(
1514 iri("alice"),
1515 iri("livesIn"),
1516 iri("brisbane"),
1517 GraphName::DefaultGraph,
1518 ),
1519 Quad::new(
1520 iri("bob"),
1521 iri("livesIn"),
1522 iri("hobart"),
1523 GraphName::DefaultGraph,
1524 ),
1525 Quad::new(
1526 iri("brisbane"),
1527 iri("hasWeather"),
1528 Literal::from("Sunny"),
1529 GraphName::DefaultGraph,
1530 ),
1531 Quad::new(
1532 iri("hobart"),
1533 iri("hasWeather"),
1534 Literal::from("Cold"),
1535 GraphName::DefaultGraph,
1536 ),
1537 sub_class_of("Person", "Agent"),
1540 sub_class_of("Agent", "Thing"),
1541 sub_class_of("City", "Place"),
1542 sub_class_of("Place", "Thing"),
1543 label("alice", "Alice"),
1545 label("bob", "Bob"),
1546 label("brisbane", "Brisbane"),
1547 label("hobart", "Hobart"),
1548 label("Person", "Person"),
1549 label("City", "City"),
1550 label("Agent", "Agent"),
1551 label("Place", "Place"),
1552 label("Thing", "Thing"),
1553 label("name", "name"),
1554 label("livesIn", "lives in"),
1555 label("hasWeather", "has weather"),
1556 ]
1557}
1558
1559#[cfg(test)]
1560mod tests {
1561 use super::*;
1562
1563 #[test]
1564 fn demo_dataset_matches_the_architecture_example() {
1565 let quads = demo_dataset();
1566 assert_eq!(quads.len(), 26);
1567 assert!(
1568 quads
1569 .iter()
1570 .any(|quad| quad.object == Literal::from("Sunny").into())
1571 );
1572 }
1573
1574 #[test]
1575 fn demo_queries_have_unique_ids_and_bodies() {
1576 let queries = demo_queries();
1577 assert_eq!(queries.len(), 3);
1578 let mut ids: Vec<&str> = queries.iter().map(|query| query.id.as_str()).collect();
1579 ids.sort_unstable();
1580 let unique = ids.len();
1581 ids.dedup();
1582 assert_eq!(ids.len(), unique, "demo query ids must be unique");
1583 for query in &queries {
1584 assert!(!query.name.is_empty());
1585 assert!(query.query.starts_with("PREFIX ex: <http://ex/>"));
1586 assert!(query.query.contains("SELECT"));
1587 assert!(query.query.contains("}\nORDER BY ?"));
1589 }
1590 }
1591
1592 #[test]
1593 fn binary_paths_sit_next_to_the_orchestrator() {
1594 let path = binary(Path::new("/opt/waratah"), "waratah-partition");
1595 assert!(path.starts_with("/opt/waratah"));
1596 assert!(
1597 path.file_name()
1598 .unwrap()
1599 .to_string_lossy()
1600 .starts_with("waratah-partition")
1601 );
1602 }
1603
1604 #[test]
1605 fn tmpfs_detection_flags_dev_shm_and_missing_paths() {
1606 #[cfg(target_os = "linux")]
1609 if Path::new("/dev/shm").exists() {
1610 assert!(is_tmpfs(Path::new("/dev/shm")));
1611 }
1612 assert!(!is_tmpfs(Path::new("/waratah-no-such-spill-path")));
1613 }
1614
1615 #[test]
1616 fn another_server_detection_reads_the_data_dir_pidfile() {
1617 assert!(!another_server_using_storage(None));
1620
1621 let dir = std::env::temp_dir().join(format!("waratah-m1-detect-{}", std::process::id()));
1622 std::fs::create_dir_all(&dir).unwrap();
1623 let pid_file = dir.join(DEV_PID_FILE);
1624
1625 std::fs::write(&pid_file, std::process::id().to_string()).unwrap();
1627 assert!(!another_server_using_storage(Some(&dir)));
1628
1629 std::fs::write(&pid_file, "not-a-pid").unwrap();
1631 assert!(!another_server_using_storage(Some(&dir)));
1632
1633 #[cfg(target_os = "linux")]
1637 {
1638 let stat = std::fs::read_to_string("/proc/self/stat").unwrap();
1639 let after_comm = stat.rsplit(')').next().unwrap();
1640 let ppid: u32 = after_comm
1641 .split_whitespace()
1642 .nth(1)
1643 .expect("ppid follows the state field")
1644 .parse()
1645 .unwrap();
1646 std::fs::write(&pid_file, ppid.to_string()).unwrap();
1647 assert!(
1648 another_server_using_storage(Some(&dir)),
1649 "a live foreign pid in the data dir's pidfile is a peer (ppid {ppid})"
1650 );
1651 }
1652
1653 std::fs::remove_file(&pid_file).unwrap();
1655 assert!(!another_server_using_storage(Some(&dir)));
1656 std::fs::remove_dir(&dir).ok();
1657 }
1658}