1use std::collections::BTreeMap;
8use std::future::Future;
9use std::net::SocketAddr;
10use std::pin::Pin;
11use std::sync::Arc;
12
13use tokio_stream::{Stream, StreamExt};
14use tonic::transport::Channel;
15use waratah_proto::{
16 GRPC_MAX_MESSAGE_SIZE, HexastoreClient, PatternSlot, QuadVersion, StringRegistryClient,
17 count_mode_to_proto, insert_request, pb, permutation_to_proto, quad_from_proto_omitting,
18 register_request, resolve_request, scan_request_page, with_comparisons, with_omitted_slots,
19 with_verdict_wanted,
20};
21use waratah_router::{ClusterConfig, RegistryNodeId};
22use waratah_stats::PUSHDOWN_TERMS_LIMIT;
23use waratah_storage::IriOnlyMask;
24use waratah_storage::{
25 AxisHeadCountHit, DomainCountMode, DomainScanCountHit, DomainScanHit, EncodedQuad, EncodedTerm,
26 EncodedTriplePattern, GeoCellInterval, GeoEnvelope, GeoIndexPut, IndexPermutation,
27 PartitionAxis, ScanPage, SlotComparison, SnapshotId, StrHash, TemporalCellInterval,
28 TemporalIndexPut, TemporalQueryPredicate, TextIndexDoc, TextSearchRequest, TextSubjectRequest,
29 TextSubjectRow,
30};
31
32use crate::dataset::GraphFilter;
33use crate::error::ComputeError;
34
35static WIRE_STREAM_ITEMS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
41static WIRE_STREAM_ROWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
42
43pub fn note_wire_stream_item(rows: usize) {
45 WIRE_STREAM_ITEMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
46 WIRE_STREAM_ROWS.fetch_add(rows as u64, std::sync::atomic::Ordering::Relaxed);
47}
48
49pub fn take_wire_stream_totals() -> (u64, u64) {
52 (
53 WIRE_STREAM_ITEMS.swap(0, std::sync::atomic::Ordering::Relaxed),
54 WIRE_STREAM_ROWS.swap(0, std::sync::atomic::Ordering::Relaxed),
55 )
56}
57
58#[derive(Debug, Clone, PartialEq)]
64pub struct BroadcastFilter {
65 pub slot: PatternSlot,
67 pub terms: Arc<[EncodedTerm]>,
69}
70
71pub type QuadPageStream = Pin<Box<dyn Stream<Item = Result<ScanPage, tonic::Status>> + Send>>;
89
90pub fn scan_page_as_wire_frames(page: ScanPage) -> QuadPageStream {
103 match page.exhausted {
104 Some(verdict) if verdict.is_terminal() => Box::pin(tokio_stream::iter(vec![
105 Ok(ScanPage {
106 rows: page.rows,
107 exhausted: None,
108 }),
109 Ok(ScanPage {
110 rows: Vec::new(),
111 exhausted: Some(verdict),
112 }),
113 ])),
114 _ => Box::pin(tokio_stream::once(Ok(page))),
115 }
116}
117
118pub trait HexastoreInsert: Send + Sync {
120 fn replace_quads(
124 &self,
125 pairs: &[waratah_storage::ReplacePair],
126 commit_ts: waratah_storage::CommitTs,
127 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
128 let _ = (pairs, commit_ts);
129 std::future::ready(Err(tonic::Status::unimplemented(
130 "this client does not serve replace",
131 )))
132 }
133
134 fn insert_quads(
136 &self,
137 axis: PartitionAxis,
138 versions: &[QuadVersion],
139 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
140}
141
142pub trait HexastoreAxisHeadStats: Send + Sync {
147 fn axis_head_max_commit_ts(
152 &self,
153 permutation: IndexPermutation,
154 head_prefixes: &[Vec<u8>],
155 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
156}
157
158pub type DetachedScanOutcome =
162 Result<(Vec<EncodedQuad>, Option<waratah_storage::ScanExhaustion>), tonic::Status>;
163
164#[allow(clippy::too_many_arguments)]
171pub trait HexastoreScan: Clone + Send + Sync + 'static {
172 #[allow(clippy::too_many_arguments)]
209 fn scan_pattern(
210 &self,
211 axis: PartitionAxis,
212 pattern: &EncodedTriplePattern,
213 snapshot: SnapshotId,
214 limit: u64,
215 permutation: Option<IndexPermutation>,
216 filter: Option<&BroadcastFilter>,
217 graph_filter: Option<&GraphFilter>,
218 start_after: Option<&EncodedQuad>,
219 merge_default_graph: bool,
220 iri_only: IriOnlyMask,
222 omitted: u8,
234 verdict_wanted: bool,
235 ) -> impl Future<Output = Result<ScanPage, tonic::Status>> + Send;
236
237 #[allow(clippy::too_many_arguments)]
255 fn scan_pattern_with_comparisons(
256 &self,
257 axis: PartitionAxis,
258 pattern: &EncodedTriplePattern,
259 snapshot: SnapshotId,
260 limit: u64,
261 permutation: Option<IndexPermutation>,
262 filter: Option<&BroadcastFilter>,
263 graph_filter: Option<&GraphFilter>,
264 start_after: Option<&EncodedQuad>,
265 merge_default_graph: bool,
266 iri_only: IriOnlyMask,
267 comparisons: &[SlotComparison],
268 omitted: u8,
269 verdict_wanted: bool,
270 ) -> impl Future<Output = Result<ScanPage, tonic::Status>> + Send {
271 let _ = comparisons;
273 async move {
274 self.scan_pattern(
275 axis,
276 pattern,
277 snapshot,
278 limit,
279 permutation,
280 filter,
281 graph_filter,
282 start_after,
283 merge_default_graph,
284 iri_only,
285 omitted,
286 verdict_wanted,
287 )
288 .await
289 }
290 }
291
292 #[allow(clippy::too_many_arguments)]
312 fn scan_pattern_stream(
313 &self,
314 axis: PartitionAxis,
315 pattern: &EncodedTriplePattern,
316 snapshot: SnapshotId,
317 limit: u64,
318 permutation: Option<IndexPermutation>,
319 filter: Option<&BroadcastFilter>,
320 graph_filter: Option<&GraphFilter>,
321 start_after: Option<&EncodedQuad>,
322 merge_default_graph: bool,
323 iri_only: IriOnlyMask,
324 omitted: u8,
325 verdict_wanted: bool,
326 ) -> impl Future<Output = Result<QuadPageStream, tonic::Status>> + Send {
327 async move {
328 let rows = self
329 .scan_pattern(
330 axis,
331 pattern,
332 snapshot,
333 limit,
334 permutation,
335 filter,
336 graph_filter,
337 start_after,
338 merge_default_graph,
339 iri_only,
340 omitted,
341 verdict_wanted,
342 )
343 .await?;
344 Ok(scan_page_as_wire_frames(rows))
345 }
346 }
347
348 #[allow(clippy::too_many_arguments)]
361 fn scan_pattern_stream_with_comparisons(
362 &self,
363 axis: PartitionAxis,
364 pattern: &EncodedTriplePattern,
365 snapshot: SnapshotId,
366 limit: u64,
367 permutation: Option<IndexPermutation>,
368 filter: Option<&BroadcastFilter>,
369 graph_filter: Option<&GraphFilter>,
370 start_after: Option<&EncodedQuad>,
371 merge_default_graph: bool,
372 iri_only: IriOnlyMask,
373 comparisons: &[SlotComparison],
374 omitted: u8,
375 verdict_wanted: bool,
376 ) -> impl Future<Output = Result<QuadPageStream, tonic::Status>> + Send {
377 let _ = comparisons;
379 async move {
380 self.scan_pattern_stream(
381 axis,
382 pattern,
383 snapshot,
384 limit,
385 permutation,
386 filter,
387 graph_filter,
388 start_after,
389 merge_default_graph,
390 iri_only,
391 omitted,
392 verdict_wanted,
393 )
394 .await
395 }
396 }
397
398 #[allow(clippy::too_many_arguments)]
417 fn scan_pattern_detached(
418 &self,
419 axis: PartitionAxis,
420 pattern: &EncodedTriplePattern,
421 snapshot: SnapshotId,
422 limit: u64,
423 permutation: Option<IndexPermutation>,
424 filter: Option<&BroadcastFilter>,
425 graph_filter: Option<&GraphFilter>,
426 start_after: Option<&EncodedQuad>,
427 merge_default_graph: bool,
428 iri_only: IriOnlyMask,
429 omitted: u8,
430 verdict_wanted: bool,
431 ) -> tokio::task::JoinHandle<DetachedScanOutcome> {
432 self.scan_pattern_detached_with_comparisons(
433 axis,
434 pattern,
435 snapshot,
436 limit,
437 permutation,
438 filter,
439 graph_filter,
440 start_after,
441 merge_default_graph,
442 iri_only,
443 &[],
444 omitted,
445 verdict_wanted,
446 )
447 }
448
449 #[allow(clippy::too_many_arguments)]
456 fn scan_pattern_detached_with_comparisons(
457 &self,
458 axis: PartitionAxis,
459 pattern: &EncodedTriplePattern,
460 snapshot: SnapshotId,
461 limit: u64,
462 permutation: Option<IndexPermutation>,
463 filter: Option<&BroadcastFilter>,
464 graph_filter: Option<&GraphFilter>,
465 start_after: Option<&EncodedQuad>,
466 merge_default_graph: bool,
467 iri_only: IriOnlyMask,
468 comparisons: &[SlotComparison],
469 omitted: u8,
470 verdict_wanted: bool,
471 ) -> tokio::task::JoinHandle<DetachedScanOutcome> {
472 let client = self.clone();
473 let pattern = pattern.clone();
474 let filter = filter.cloned();
475 let graph_filter = graph_filter.cloned();
476 let start_after = start_after.cloned();
477 let comparisons = comparisons.to_vec();
478 tokio::spawn(async move {
479 if limit as usize > crate::query::tunables::scan_batch() {
480 let mut pages = client
484 .scan_pattern_stream_with_comparisons(
485 axis,
486 &pattern,
487 snapshot,
488 limit,
489 permutation,
490 filter.as_ref(),
491 graph_filter.as_ref(),
492 start_after.as_ref(),
493 merge_default_graph,
494 iri_only,
495 &comparisons,
496 omitted,
497 verdict_wanted,
498 )
499 .await?;
500 let mut rows = Vec::new();
501 let mut verdict: Option<waratah_storage::ScanExhaustion> = None;
502 while let Some(page) = pages.next().await {
503 let page = page?;
504 verdict = page.exhausted;
505 rows.extend(page.rows);
506 if rows.len() >= limit as usize {
507 break;
508 }
509 }
510 Ok((rows, verdict))
511 } else {
512 client
513 .scan_pattern_with_comparisons(
514 axis,
515 &pattern,
516 snapshot,
517 limit,
518 permutation,
519 filter.as_ref(),
520 graph_filter.as_ref(),
521 start_after.as_ref(),
522 merge_default_graph,
523 iri_only,
524 &comparisons,
525 omitted,
526 verdict_wanted,
527 )
528 .await
529 .map(|page| (page.rows, page.exhausted))
530 }
531 })
532 }
533
534 #[allow(clippy::too_many_arguments)]
539 fn count_pattern(
540 &self,
541 axis: PartitionAxis,
542 pattern: &EncodedTriplePattern,
543 snapshot: SnapshotId,
544 limit: u64,
545 permutation: Option<IndexPermutation>,
546 filter: Option<&BroadcastFilter>,
547 graph_filter: Option<&GraphFilter>,
548 merge_default_graph: bool,
549 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
550
551 #[allow(clippy::too_many_arguments)]
561 fn scan_domain(
562 &self,
563 permutation: IndexPermutation,
564 constraints: &[EncodedTerm],
565 snapshot: SnapshotId,
566 limit: u64,
567 start_after_constraint: Option<&EncodedTerm>,
568 start_after_term: Option<&EncodedTerm>,
569 graph_name: Option<&EncodedTerm>,
570 graph_filter: Option<&GraphFilter>,
571 iri_only_head: bool,
573 ) -> impl Future<Output = Result<Vec<DomainScanHit>, tonic::Status>> + Send;
574
575 #[allow(clippy::too_many_arguments)]
583 fn scan_domain_counts(
584 &self,
585 permutation: IndexPermutation,
586 constraints: &[EncodedTerm],
587 snapshot: SnapshotId,
588 limit: u64,
589 start_after_constraint: Option<&EncodedTerm>,
590 start_after_term: Option<&EncodedTerm>,
591 graph_name: Option<&EncodedTerm>,
592 graph_filter: Option<&GraphFilter>,
593 iri_only_head: bool,
595 merge_default_graph: bool,
596 mode: DomainCountMode,
598 ) -> impl Future<Output = Result<Vec<DomainScanCountHit>, tonic::Status>> + Send;
599
600 #[allow(clippy::too_many_arguments)]
608 fn scan_axis_head(
609 &self,
610 permutation: IndexPermutation,
611 snapshot: SnapshotId,
612 limit: u64,
613 start_after_term: Option<&EncodedTerm>,
614 graph_name: Option<&EncodedTerm>,
615 graph_filter: Option<&GraphFilter>,
616 iri_only_head: bool,
618 head_prefixes: &[Vec<u8>],
619 ) -> impl Future<Output = Result<Vec<EncodedTerm>, tonic::Status>> + Send;
620
621 #[allow(clippy::too_many_arguments)]
624 fn count_axis_heads(
625 &self,
626 permutation: IndexPermutation,
627 snapshot: SnapshotId,
628 graph_name: Option<&EncodedTerm>,
629 graph_filter: Option<&GraphFilter>,
630 iri_only_head: bool,
631 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
632
633 #[allow(clippy::too_many_arguments)]
636 fn scan_axis_head_counts(
637 &self,
638 permutation: IndexPermutation,
639 snapshot: SnapshotId,
640 limit: u64,
641 start_after_term: Option<&EncodedTerm>,
642 graph_name: Option<&EncodedTerm>,
643 graph_filter: Option<&GraphFilter>,
644 iri_only_head: bool,
645 ) -> impl Future<Output = Result<Vec<AxisHeadCountHit>, tonic::Status>> + Send;
646}
647
648pub trait HexastoreFlush: Send + Sync {
650 fn flush_memtables(
652 &self,
653 axis: PartitionAxis,
654 ) -> impl Future<Output = Result<(), tonic::Status>> + Send;
655}
656
657pub trait HexastoreCompact: Send + Sync {
659 fn compact_range(
661 &self,
662 axis: PartitionAxis,
663 ) -> impl Future<Output = Result<(), tonic::Status>> + Send;
664}
665
666pub trait HexastoreStats: Send + Sync {
668 fn stats_profile(
671 &self,
672 axis: PartitionAxis,
673 ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
674
675 fn geo_histogram(
680 &self,
681 axis: PartitionAxis,
682 section: waratah_proto::pb::GeoHistogramSection,
683 ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
684
685 fn temporal_histogram(
688 &self,
689 axis: PartitionAxis,
690 ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
691
692 fn text_seed_sketch(
697 &self,
698 axis: PartitionAxis,
699 ) -> impl Future<Output = Result<Vec<u8>, tonic::Status>> + Send;
700}
701
702#[derive(Debug, Clone)]
704pub struct HexastoreDescribe {
705 pub axis: PartitionAxis,
707 pub node_id: String,
709 pub listen: String,
711 pub data_dir: String,
713 pub backend: String,
715 pub version: String,
717 pub repository_id: String,
719 pub serving: bool,
721 pub metrics: crate::cluster::LsmMetricsView,
723 pub geo_index_epoch: Option<u64>,
727 pub temporal_index_epoch: Option<u64>,
730 pub temporal_rebuild_in_progress: bool,
732 pub geo_rebuild_in_progress: bool,
734 pub text_index_epoch: Option<u64>,
738 pub text_index_fingerprint: String,
740 pub text_index_terms: u64,
742 pub text_rebuild_in_progress: bool,
744}
745
746#[derive(Debug, Clone)]
748pub struct RegistryDescribe {
749 pub node_id: String,
751 pub listen: String,
753 pub data_dir: String,
755 pub backend: String,
757 pub version: String,
759 pub repository_id: String,
761 pub shard_count: u64,
763 pub entry_count: Option<u64>,
765 pub serving: bool,
767 pub metrics: crate::cluster::LsmMetricsView,
769}
770
771pub trait HexastoreAdmin: Send + Sync {
773 fn describe(
775 &self,
776 axis: PartitionAxis,
777 ) -> impl Future<Output = Result<HexastoreDescribe, tonic::Status>> + Send;
778}
779
780pub trait RegistryAdmin: Send + Sync {
782 fn describe(
784 &self,
785 node: waratah_router::RegistryNodeId,
786 ) -> impl Future<Output = Result<RegistryDescribe, tonic::Status>> + Send;
787}
788
789pub trait HexastoreCatalog: Send + Sync {
793 fn list_named_graphs(
795 &self,
796 snapshot: SnapshotId,
797 ) -> impl Future<Output = Result<Vec<EncodedTerm>, tonic::Status>> + Send;
798
799 fn add_named_graph(
801 &self,
802 graph: &EncodedTerm,
803 commit_ts: waratah_storage::CommitTs,
804 ) -> impl Future<Output = Result<(), tonic::Status>> + Send;
805}
806
807pub trait HexastoreGeo: Send + Sync {
812 fn put_geo_index(
814 &self,
815 puts: &[GeoIndexPut],
816 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
817 let _ = puts;
818 std::future::ready(Err(tonic::Status::unimplemented(
819 "this client does not serve the geometry index",
820 )))
821 }
822
823 fn delete_geo_term(
825 &self,
826 term: &[u8],
827 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
828 let _ = term;
829 std::future::ready(Err(tonic::Status::unimplemented(
830 "this client does not serve the geometry index",
831 )))
832 }
833
834 #[allow(clippy::too_many_arguments)]
838 fn geo_candidate_scan(
839 &self,
840 intervals: &[GeoCellInterval],
841 snapshot: SnapshotId,
842 query_envelope: Option<GeoEnvelope>,
843 limit: u64,
844 ) -> impl Future<Output = Result<TermPageStream, tonic::Status>> + Send {
845 let _ = (intervals, snapshot, query_envelope, limit);
846 std::future::ready(Err(tonic::Status::unimplemented(
847 "this client does not serve the geometry index",
848 )))
849 }
850
851 fn put_temporal_index(
853 &self,
854 puts: &[TemporalIndexPut],
855 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
856 let _ = puts;
857 std::future::ready(Err(tonic::Status::unimplemented(
858 "this client does not serve the temporal index",
859 )))
860 }
861
862 fn temporal_candidate_scan(
866 &self,
867 intervals: &[TemporalCellInterval],
868 snapshot: SnapshotId,
869 predicate: TemporalQueryPredicate,
870 limit: u64,
871 ) -> impl Future<Output = Result<TermPageStream, tonic::Status>> + Send {
872 let _ = (intervals, snapshot, predicate, limit);
873 std::future::ready(Err(tonic::Status::unimplemented(
874 "this client does not serve the temporal index",
875 )))
876 }
877
878 fn rebuild_geo_index(
885 &self,
886 ) -> impl Future<Output = Result<(bool, bool, u64), tonic::Status>> + Send {
887 std::future::ready(Err(tonic::Status::unimplemented(
888 "this client does not serve the geometry index",
889 )))
890 }
891
892 fn renew_geo_rebuild_lease(&self) -> impl Future<Output = Result<(), tonic::Status>> + Send {
895 std::future::ready(Err(tonic::Status::unimplemented(
896 "this client does not serve the geometry index",
897 )))
898 }
899
900 fn finish_geo_index_rebuild(&self) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
903 std::future::ready(Err(tonic::Status::unimplemented(
904 "this client does not serve the geometry index",
905 )))
906 }
907
908 fn rebuild_temporal_index(
912 &self,
913 config: waratah_storage::DyadicCovererConfig,
914 ) -> impl Future<Output = Result<(bool, bool), tonic::Status>> + Send {
915 let _ = config;
916 std::future::ready(Err(tonic::Status::unimplemented(
917 "this client does not serve the temporal index",
918 )))
919 }
920
921 fn put_text_index(
926 &self,
927 docs: &[TextIndexDoc],
928 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
929 let _ = docs;
930 std::future::ready(Err(tonic::Status::unimplemented(
931 "this client does not serve the text index",
932 )))
933 }
934
935 fn text_candidate_scan(
939 &self,
940 request: &TextSearchRequest,
941 snapshot: SnapshotId,
942 ) -> impl Future<Output = Result<TermPageStream, tonic::Status>> + Send {
943 let _ = (request, snapshot);
944 std::future::ready(Err(tonic::Status::unimplemented(
945 "this client does not serve the text index",
946 )))
947 }
948
949 fn text_subject_scan(
960 &self,
961 request: &TextSubjectRequest,
962 snapshot: SnapshotId,
963 ) -> impl Future<Output = Result<SubjectRowStream, tonic::Status>> + Send {
964 let _ = (request, snapshot);
965 std::future::ready(Err(tonic::Status::unimplemented(
966 "this client does not serve the text index",
967 )))
968 }
969
970 fn rebuild_text_index(
977 &self,
978 analyzer: &str,
979 seed_chars: u32,
980 fingerprint: &str,
981 wipe: bool,
982 ) -> impl Future<Output = Result<(bool, bool, u64), tonic::Status>> + Send {
983 let _ = (analyzer, seed_chars, fingerprint, wipe);
984 std::future::ready(Err(tonic::Status::unimplemented(
985 "this client does not serve the text index",
986 )))
987 }
988
989 fn renew_text_rebuild_lease(
992 &self,
993 lease_token: u64,
994 ) -> impl Future<Output = Result<(), tonic::Status>> + Send {
995 let _ = lease_token;
996 std::future::ready(Err(tonic::Status::unimplemented(
997 "this client does not serve the text index",
998 )))
999 }
1000
1001 fn finish_text_index_rebuild(
1007 &self,
1008 lease_token: u64,
1009 stamp: bool,
1010 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send {
1011 let _ = (lease_token, stamp);
1012 std::future::ready(Err(tonic::Status::unimplemented(
1013 "this client does not serve the text index",
1014 )))
1015 }
1016}
1017
1018pub type TermPageStream =
1020 Pin<Box<dyn Stream<Item = Result<Vec<EncodedTerm>, tonic::Status>> + Send>>;
1021
1022pub type SubjectRowStream =
1024 Pin<Box<dyn Stream<Item = Result<Vec<TextSubjectRow>, tonic::Status>> + Send>>;
1025
1026fn text_subject_row_from_proto(row: &pb::TextSubjectRow) -> Result<TextSubjectRow, tonic::Status> {
1032 let subject = waratah_proto::term_from_bytes(&row.subject)
1033 .map_err(|error| tonic::Status::internal(error.to_string()))?;
1034 let graph = row
1035 .graph
1036 .as_deref()
1037 .map(waratah_proto::term_from_bytes)
1038 .transpose()
1039 .map_err(|error| tonic::Status::internal(error.to_string()))?;
1040 Ok(TextSubjectRow { subject, graph })
1041}
1042
1043pub trait BlobStoreClient: Send + Sync {
1068 fn put_blob_chunks(
1072 &self,
1073 blob_id: StrHash,
1074 payload: Arc<[u8]>,
1075 ) -> impl Future<Output = Result<(), tonic::Status>> + Send {
1076 let _ = (blob_id, payload);
1077 std::future::ready(Err(tonic::Status::unimplemented(
1078 "this client has no blob store",
1079 )))
1080 }
1081
1082 fn put_blobs(
1086 &self,
1087 blobs: &[(StrHash, Arc<[u8]>)],
1088 ) -> impl Future<Output = Result<(), tonic::Status>> + Send {
1089 let _ = blobs;
1090 std::future::ready(Err(tonic::Status::unimplemented(
1091 "this client has no blob store",
1092 )))
1093 }
1094
1095 fn get_blobs(
1097 &self,
1098 ids: &[StrHash],
1099 ) -> impl Future<Output = Result<Vec<Option<Vec<u8>>>, tonic::Status>> + Send {
1100 let _ = ids;
1101 std::future::ready(Err(tonic::Status::unimplemented(
1102 "this client has no blob store",
1103 )))
1104 }
1105}
1106
1107pub trait StringRegistryFlush: Send + Sync {
1109 fn flush_memtables(&self) -> impl Future<Output = Result<(), tonic::Status>> + Send;
1111}
1112
1113pub trait StringRegistryCompact: Send + Sync {
1115 fn compact_range(&self) -> impl Future<Output = Result<(), tonic::Status>> + Send;
1117}
1118
1119pub trait StringRegister: Send + Sync {
1121 fn register_strings(
1123 &self,
1124 entries: &[(StrHash, String)],
1125 ) -> impl Future<Output = Result<u64, tonic::Status>> + Send;
1126}
1127
1128pub trait StringResolve: Send + Sync {
1130 fn resolve_strings(
1132 &self,
1133 hashes: &[StrHash],
1134 ) -> impl Future<Output = Result<Vec<Option<String>>, tonic::Status>> + Send;
1135}
1136
1137#[derive(Debug, Clone)]
1139pub struct GrpcHexastoreClients {
1140 clients: BTreeMap<&'static str, HexastoreClient<Channel>>,
1141 stream_clients: BTreeMap<&'static str, HexastoreClient<Channel>>,
1150}
1151
1152impl GrpcHexastoreClients {
1153 pub async fn connect(config: &ClusterConfig) -> Result<Self, ComputeError> {
1155 let mut clients = BTreeMap::new();
1156 let mut stream_clients = BTreeMap::new();
1157 for axis in PartitionAxis::ALL {
1158 let addr = config.hexastore(axis)?;
1159 let endpoint =
1166 tonic::transport::Endpoint::from_shared(http_url(addr))?.tcp_nodelay(true);
1167 let client = HexastoreClient::connect(endpoint)
1168 .await?
1169 .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
1170 clients.insert(axis.as_str(), client);
1171 let stream_endpoint =
1174 tonic::transport::Endpoint::from_shared(http_url(addr))?.tcp_nodelay(true);
1175 let stream_client = HexastoreClient::connect(stream_endpoint)
1176 .await?
1177 .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
1178 stream_clients.insert(axis.as_str(), stream_client);
1179 }
1180 Ok(Self {
1181 clients,
1182 stream_clients,
1183 })
1184 }
1185
1186 fn client(&self, axis: PartitionAxis) -> HexastoreClient<Channel> {
1187 self.clients
1188 .get(axis.as_str())
1189 .expect("ClusterConfig validation requires every axis")
1190 .clone()
1191 }
1192
1193 fn stream_client(&self, axis: PartitionAxis) -> HexastoreClient<Channel> {
1194 self.stream_clients
1195 .get(axis.as_str())
1196 .expect("ClusterConfig validation requires every axis")
1197 .clone()
1198 }
1199}
1200
1201impl HexastoreInsert for GrpcHexastoreClients {
1202 async fn insert_quads(
1203 &self,
1204 axis: PartitionAxis,
1205 versions: &[QuadVersion],
1206 ) -> Result<u64, tonic::Status> {
1207 let mut client = self.client(axis);
1208 let response = client.insert_quads(insert_request(axis, versions)).await?;
1209 Ok(response.into_inner().inserted)
1210 }
1211 async fn replace_quads(
1212 &self,
1213 pairs: &[waratah_storage::ReplacePair],
1214 commit_ts: waratah_storage::CommitTs,
1215 ) -> Result<u64, tonic::Status> {
1216 const FRAME_BUDGET: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE / 2;
1220 let mut frames: Vec<Vec<pb::replace_quads_request::Pair>> = vec![Vec::new()];
1221 let mut frame_bytes = 0usize;
1222 for pair in pairs {
1223 let proto_pair = waratah_proto::replace_pair_to_proto(pair);
1224 let bytes = proto_pair.subject.len()
1225 + proto_pair.predicate.len()
1226 + proto_pair.graph_name.len()
1227 + proto_pair.old_object.len()
1228 + proto_pair.new_object.len()
1229 + 16;
1230 if frame_bytes + bytes > FRAME_BUDGET && !frames.last().unwrap().is_empty() {
1231 frames.push(Vec::new());
1232 frame_bytes = 0;
1233 }
1234 frame_bytes += bytes;
1235 frames.last_mut().unwrap().push(proto_pair);
1236 }
1237 let mut replaced = 0u64;
1238 for frame in &frames {
1239 let mut s_client = self.client(PartitionAxis::S);
1240 let mut p_client = self.client(PartitionAxis::P);
1241 let mut o_client = self.client(PartitionAxis::O);
1242 let make_request = || pb::ReplaceQuadsRequest {
1243 pairs: frame.clone(),
1244 commit_ts: commit_ts.0,
1245 };
1246 let (s, p, o) = tokio::join!(
1247 s_client.replace_quads(make_request()),
1248 p_client.replace_quads(make_request()),
1249 o_client.replace_quads(make_request()),
1250 );
1251 replaced += s?.into_inner().replaced;
1252 replaced += p?.into_inner().replaced;
1253 replaced += o?.into_inner().replaced;
1254 }
1255 Ok(replaced)
1256 }
1257}
1258
1259impl HexastoreAxisHeadStats for GrpcHexastoreClients {
1260 async fn axis_head_max_commit_ts(
1261 &self,
1262 permutation: IndexPermutation,
1263 head_prefixes: &[Vec<u8>],
1264 ) -> Result<u64, tonic::Status> {
1265 let response = self
1266 .client(PartitionAxis::from(permutation))
1267 .axis_head_max_commit_ts(pb::AxisHeadMaxCommitTsRequest {
1268 permutation: permutation_to_proto(permutation) as i32,
1269 head_prefixes: head_prefixes.to_vec(),
1270 })
1271 .await?;
1272 Ok(response.into_inner().max_commit_ts)
1273 }
1274}
1275
1276impl HexastoreScan for GrpcHexastoreClients {
1277 #[allow(clippy::too_many_arguments)]
1278 async fn scan_pattern(
1279 &self,
1280 axis: PartitionAxis,
1281 pattern: &EncodedTriplePattern,
1282 snapshot: SnapshotId,
1283 limit: u64,
1284 permutation: Option<IndexPermutation>,
1285 filter: Option<&BroadcastFilter>,
1286 graph_filter: Option<&GraphFilter>,
1287 start_after: Option<&EncodedQuad>,
1288 merge_default_graph: bool,
1289 iri_only: IriOnlyMask,
1290 omitted: u8,
1291 verdict_wanted: bool,
1292 ) -> Result<ScanPage, tonic::Status> {
1293 self.scan_pattern_with_comparisons(
1294 axis,
1295 pattern,
1296 snapshot,
1297 limit,
1298 permutation,
1299 filter,
1300 graph_filter,
1301 start_after,
1302 merge_default_graph,
1303 iri_only,
1304 &[],
1305 omitted,
1306 verdict_wanted,
1307 )
1308 .await
1309 }
1310
1311 #[allow(clippy::too_many_arguments)]
1312 async fn scan_pattern_with_comparisons(
1313 &self,
1314 axis: PartitionAxis,
1315 pattern: &EncodedTriplePattern,
1316 snapshot: SnapshotId,
1317 limit: u64,
1318 permutation: Option<IndexPermutation>,
1319 filter: Option<&BroadcastFilter>,
1320 graph_filter: Option<&GraphFilter>,
1321 start_after: Option<&EncodedQuad>,
1322 merge_default_graph: bool,
1323 iri_only: IriOnlyMask,
1324 comparisons: &[SlotComparison],
1325 omitted: u8,
1326 verdict_wanted: bool,
1327 ) -> Result<ScanPage, tonic::Status> {
1328 let mut client = self.client(axis);
1329 let request = with_comparisons(
1332 pattern_scan_request(
1333 pattern,
1334 snapshot,
1335 limit,
1336 permutation,
1337 filter,
1338 graph_filter,
1339 start_after,
1340 merge_default_graph,
1341 iri_only,
1342 ),
1343 comparisons,
1344 )?;
1345 let response = client
1346 .scan_pattern(with_verdict_wanted(
1347 with_omitted_slots(request, omitted),
1348 verdict_wanted,
1349 ))
1350 .await?;
1351 let inner = response.into_inner();
1352 let rows = inner
1353 .quads
1354 .iter()
1355 .map(|quad| {
1356 quad_from_proto_omitting(quad, pattern, omitted)
1357 .map_err(|e| tonic::Status::internal(e.to_string()))
1358 })
1359 .collect::<Result<Vec<_>, _>>()?;
1360 Ok(ScanPage {
1361 rows,
1362 exhausted: waratah_proto::scan_exhaustion_from_proto_opt(inner.exhausted),
1363 })
1364 }
1365
1366 #[allow(clippy::too_many_arguments)]
1367 async fn scan_pattern_stream(
1368 &self,
1369 axis: PartitionAxis,
1370 pattern: &EncodedTriplePattern,
1371 snapshot: SnapshotId,
1372 limit: u64,
1373 permutation: Option<IndexPermutation>,
1374 filter: Option<&BroadcastFilter>,
1375 graph_filter: Option<&GraphFilter>,
1376 start_after: Option<&EncodedQuad>,
1377 merge_default_graph: bool,
1378 iri_only: IriOnlyMask,
1379 omitted: u8,
1380 verdict_wanted: bool,
1381 ) -> Result<QuadPageStream, tonic::Status> {
1382 self.scan_pattern_stream_with_comparisons(
1383 axis,
1384 pattern,
1385 snapshot,
1386 limit,
1387 permutation,
1388 filter,
1389 graph_filter,
1390 start_after,
1391 merge_default_graph,
1392 iri_only,
1393 &[],
1394 omitted,
1395 verdict_wanted,
1396 )
1397 .await
1398 }
1399
1400 #[allow(clippy::too_many_arguments)]
1401 async fn scan_pattern_stream_with_comparisons(
1402 &self,
1403 axis: PartitionAxis,
1404 pattern: &EncodedTriplePattern,
1405 snapshot: SnapshotId,
1406 limit: u64,
1407 permutation: Option<IndexPermutation>,
1408 filter: Option<&BroadcastFilter>,
1409 graph_filter: Option<&GraphFilter>,
1410 start_after: Option<&EncodedQuad>,
1411 merge_default_graph: bool,
1412 iri_only: IriOnlyMask,
1413 comparisons: &[SlotComparison],
1414 omitted: u8,
1415 verdict_wanted: bool,
1416 ) -> Result<QuadPageStream, tonic::Status> {
1417 let mut client = self.stream_client(axis);
1422 let request = with_comparisons(
1423 pattern_scan_request(
1424 pattern,
1425 snapshot,
1426 limit,
1427 permutation,
1428 filter,
1429 graph_filter,
1430 start_after,
1431 merge_default_graph,
1432 iri_only,
1433 ),
1434 comparisons,
1435 )?;
1436 let response = client
1437 .scan_pattern_stream(with_verdict_wanted(
1438 with_omitted_slots(request, omitted),
1439 verdict_wanted,
1440 ))
1441 .await?;
1442 let pattern = pattern.clone();
1450 let pages = response.into_inner().map(move |page| {
1451 page.and_then(|page| {
1452 note_wire_stream_item(page.quads.len());
1453 let exhausted = waratah_proto::scan_exhaustion_from_proto_opt(page.exhausted);
1454 page.quads
1455 .iter()
1456 .map(|quad| {
1457 quad_from_proto_omitting(quad, &pattern, omitted)
1458 .map_err(|e| tonic::Status::internal(e.to_string()))
1459 })
1460 .collect::<Result<Vec<_>, _>>()
1461 .map(|rows| ScanPage { rows, exhausted })
1462 })
1463 });
1464 Ok(Box::pin(pages))
1465 }
1466
1467 #[allow(clippy::too_many_arguments)]
1468 async fn count_pattern(
1469 &self,
1470 axis: PartitionAxis,
1471 pattern: &EncodedTriplePattern,
1472 snapshot: SnapshotId,
1473 limit: u64,
1474 permutation: Option<IndexPermutation>,
1475 filter: Option<&BroadcastFilter>,
1476 graph_filter: Option<&GraphFilter>,
1477 merge_default_graph: bool,
1478 ) -> Result<u64, tonic::Status> {
1479 let mut client = self.client(axis);
1480 let response = client
1481 .count_pattern(pattern_scan_request(
1482 pattern,
1483 snapshot,
1484 limit,
1485 permutation,
1486 filter,
1487 graph_filter,
1488 None,
1489 merge_default_graph,
1490 IriOnlyMask::NONE,
1492 ))
1493 .await?;
1494 Ok(response.into_inner().count)
1495 }
1496
1497 #[allow(clippy::too_many_arguments)]
1498 async fn scan_domain(
1499 &self,
1500 permutation: IndexPermutation,
1501 constraints: &[EncodedTerm],
1502 snapshot: SnapshotId,
1503 limit: u64,
1504 start_after_constraint: Option<&EncodedTerm>,
1505 start_after_term: Option<&EncodedTerm>,
1506 graph_name: Option<&EncodedTerm>,
1507 graph_filter: Option<&GraphFilter>,
1508 iri_only_head: bool,
1509 ) -> Result<Vec<DomainScanHit>, tonic::Status> {
1510 assert_wire_budget(constraints);
1511 let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1512 let response = self
1513 .client(PartitionAxis::from(permutation))
1514 .domain_scan(waratah_proto::pb::DomainScanRequest {
1515 permutation: permutation_to_proto(permutation) as i32,
1516 constraints: constraints
1517 .iter()
1518 .map(waratah_proto::term_to_bytes)
1519 .collect(),
1520 snapshot_id: snapshot.0,
1521 limit,
1522 graph_name: graph_name.map(|term| {
1525 let bytes = waratah_proto::term_to_bytes(term);
1526 if bytes.is_empty() {
1527 Vec::new()
1530 } else {
1531 bytes
1532 }
1533 }),
1534 graph_filter_terms: graph_terms
1535 .iter()
1536 .map(waratah_proto::term_to_bytes)
1537 .collect(),
1538 graph_filter_allow: graph_allow,
1539 start_after_constraint: start_after_constraint
1540 .map(waratah_proto::term_to_bytes)
1541 .unwrap_or_default(),
1542 start_after_term: start_after_term
1543 .map(waratah_proto::term_to_bytes)
1544 .unwrap_or_default(),
1545 iri_only_head,
1546 })
1547 .await?;
1548 response
1549 .into_inner()
1550 .hits
1551 .iter()
1552 .map(|hit| {
1553 Ok(DomainScanHit {
1554 constraint: waratah_proto::term_from_bytes(&hit.constraint)
1555 .map_err(|e| tonic::Status::internal(e.to_string()))?,
1556 term: waratah_proto::term_from_bytes(&hit.term)
1557 .map_err(|e| tonic::Status::internal(e.to_string()))?,
1558 })
1559 })
1560 .collect()
1561 }
1562
1563 #[allow(clippy::too_many_arguments)]
1564 async fn scan_domain_counts(
1565 &self,
1566 permutation: IndexPermutation,
1567 constraints: &[EncodedTerm],
1568 snapshot: SnapshotId,
1569 limit: u64,
1570 start_after_constraint: Option<&EncodedTerm>,
1571 start_after_term: Option<&EncodedTerm>,
1572 graph_name: Option<&EncodedTerm>,
1573 graph_filter: Option<&GraphFilter>,
1574 iri_only_head: bool,
1575 merge_default_graph: bool,
1576 mode: DomainCountMode,
1577 ) -> Result<Vec<DomainScanCountHit>, tonic::Status> {
1578 assert_wire_budget(constraints);
1579 let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1580 let response = self
1581 .client(PartitionAxis::from(permutation))
1582 .domain_scan_counts(waratah_proto::pb::DomainScanCountRequest {
1583 permutation: permutation_to_proto(permutation) as i32,
1584 constraints: constraints
1585 .iter()
1586 .map(waratah_proto::term_to_bytes)
1587 .collect(),
1588 snapshot_id: snapshot.0,
1589 limit,
1590 graph_name: graph_name.map(|term| {
1593 let bytes = waratah_proto::term_to_bytes(term);
1594 if bytes.is_empty() {
1595 Vec::new()
1598 } else {
1599 bytes
1600 }
1601 }),
1602 graph_filter_terms: graph_terms
1603 .iter()
1604 .map(waratah_proto::term_to_bytes)
1605 .collect(),
1606 graph_filter_allow: graph_allow,
1607 start_after_constraint: start_after_constraint
1608 .map(waratah_proto::term_to_bytes)
1609 .unwrap_or_default(),
1610 start_after_term: start_after_term
1611 .map(waratah_proto::term_to_bytes)
1612 .unwrap_or_default(),
1613 iri_only_head,
1614 merge_default_graph,
1615 count_mode: count_mode_to_proto(mode) as i32,
1616 })
1617 .await?;
1618 response
1619 .into_inner()
1620 .hits
1621 .iter()
1622 .map(|hit| {
1623 Ok(DomainScanCountHit {
1624 constraint: waratah_proto::term_from_bytes(&hit.constraint)
1625 .map_err(|e| tonic::Status::internal(e.to_string()))?,
1626 term: waratah_proto::term_from_bytes(&hit.term)
1627 .map_err(|e| tonic::Status::internal(e.to_string()))?,
1628 count: hit.count,
1629 })
1630 })
1631 .collect()
1632 }
1633
1634 #[allow(clippy::too_many_arguments)]
1635 async fn scan_axis_head(
1636 &self,
1637 permutation: IndexPermutation,
1638 snapshot: SnapshotId,
1639 limit: u64,
1640 start_after_term: Option<&EncodedTerm>,
1641 graph_name: Option<&EncodedTerm>,
1642 graph_filter: Option<&GraphFilter>,
1643 iri_only_head: bool,
1644 head_prefixes: &[Vec<u8>],
1645 ) -> Result<Vec<EncodedTerm>, tonic::Status> {
1646 let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1647 let response = self
1648 .client(PartitionAxis::from(permutation))
1649 .axis_head_scan(waratah_proto::pb::AxisHeadScanRequest {
1650 permutation: permutation_to_proto(permutation) as i32,
1651 snapshot_id: snapshot.0,
1652 limit,
1653 graph_name: graph_name.map(waratah_proto::term_to_bytes),
1654 graph_filter_terms: graph_terms
1655 .iter()
1656 .map(waratah_proto::term_to_bytes)
1657 .collect(),
1658 graph_filter_allow: graph_allow,
1659 start_after_term: start_after_term
1660 .map(waratah_proto::term_to_bytes)
1661 .unwrap_or_default(),
1662 iri_only_head,
1663 head_prefixes: head_prefixes.to_vec(),
1664 })
1665 .await?;
1666 response
1667 .into_inner()
1668 .terms
1669 .iter()
1670 .map(|bytes| {
1671 waratah_proto::term_from_bytes(bytes)
1672 .map_err(|e| tonic::Status::internal(e.to_string()))
1673 })
1674 .collect()
1675 }
1676
1677 #[allow(clippy::too_many_arguments)]
1678 async fn count_axis_heads(
1679 &self,
1680 permutation: IndexPermutation,
1681 snapshot: SnapshotId,
1682 graph_name: Option<&EncodedTerm>,
1683 graph_filter: Option<&GraphFilter>,
1684 iri_only_head: bool,
1685 ) -> Result<u64, tonic::Status> {
1686 let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1687 let response = self
1688 .client(PartitionAxis::from(permutation))
1689 .axis_head_scan_counts(pb::AxisHeadScanCountsRequest {
1690 permutation: permutation_to_proto(permutation) as i32,
1691 snapshot_id: snapshot.0,
1692 mode: pb::AxisHeadCountMode::Total as i32,
1693 graph_name: graph_name.map(waratah_proto::term_to_bytes),
1694 graph_filter_terms: graph_terms
1695 .iter()
1696 .map(waratah_proto::term_to_bytes)
1697 .collect(),
1698 graph_filter_allow: graph_allow,
1699 start_after_term: Vec::new(),
1700 iri_only_head,
1701 limit: 0,
1702 })
1703 .await?;
1704 Ok(response.into_inner().total)
1705 }
1706
1707 #[allow(clippy::too_many_arguments)]
1708 async fn scan_axis_head_counts(
1709 &self,
1710 permutation: IndexPermutation,
1711 snapshot: SnapshotId,
1712 limit: u64,
1713 start_after_term: Option<&EncodedTerm>,
1714 graph_name: Option<&EncodedTerm>,
1715 graph_filter: Option<&GraphFilter>,
1716 iri_only_head: bool,
1717 ) -> Result<Vec<AxisHeadCountHit>, tonic::Status> {
1718 let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1719 let response = self
1720 .client(PartitionAxis::from(permutation))
1721 .axis_head_scan_counts(pb::AxisHeadScanCountsRequest {
1722 permutation: permutation_to_proto(permutation) as i32,
1723 snapshot_id: snapshot.0,
1724 mode: pb::AxisHeadCountMode::PerHead as i32,
1725 graph_name: graph_name.map(waratah_proto::term_to_bytes),
1726 graph_filter_terms: graph_terms
1727 .iter()
1728 .map(waratah_proto::term_to_bytes)
1729 .collect(),
1730 graph_filter_allow: graph_allow,
1731 start_after_term: start_after_term
1732 .map(waratah_proto::term_to_bytes)
1733 .unwrap_or_default(),
1734 iri_only_head,
1735 limit,
1736 })
1737 .await?;
1738 response
1739 .into_inner()
1740 .hits
1741 .iter()
1742 .map(|hit| {
1743 Ok(AxisHeadCountHit {
1744 term: waratah_proto::term_from_bytes(&hit.term)
1745 .map_err(|e| tonic::Status::internal(e.to_string()))?,
1746 count: hit.count,
1747 })
1748 })
1749 .collect()
1750 }
1751}
1752
1753fn assert_wire_budget(terms: &[EncodedTerm]) {
1770 debug_assert!(
1771 terms.len() <= PUSHDOWN_TERMS_LIMIT as usize,
1772 "oversized scan request: {} terms (threshold {}) — \
1773 a scan road bypassed the wire-budget boundary",
1774 terms.len(),
1775 PUSHDOWN_TERMS_LIMIT
1776 );
1777}
1778
1779#[allow(clippy::too_many_arguments)]
1780fn pattern_scan_request(
1781 pattern: &EncodedTriplePattern,
1782 snapshot: SnapshotId,
1783 limit: u64,
1784 permutation: Option<IndexPermutation>,
1785 filter: Option<&BroadcastFilter>,
1786 graph_filter: Option<&GraphFilter>,
1787 start_after: Option<&EncodedQuad>,
1788 merge_default_graph: bool,
1789 iri_only: IriOnlyMask,
1790) -> waratah_proto::pb::ScanPatternRequest {
1791 let (slot, terms) = match filter {
1792 Some(f) if !f.terms.is_empty() => (Some(f.slot), &*f.terms),
1793 _ => (None, &[][..]),
1794 };
1795 assert_wire_budget(terms);
1803 let (graph_terms, graph_allow) = GraphFilter::to_wire(graph_filter);
1804 scan_request_page(
1805 pattern,
1806 snapshot,
1807 limit,
1808 permutation,
1809 slot,
1810 terms,
1811 start_after,
1812 graph_terms,
1813 graph_allow,
1814 merge_default_graph,
1815 iri_only,
1816 )
1817}
1818
1819impl HexastoreFlush for GrpcHexastoreClients {
1820 async fn flush_memtables(&self, axis: PartitionAxis) -> Result<(), tonic::Status> {
1821 let mut client = self.client(axis);
1822 client
1823 .flush_memtables(waratah_proto::pb::FlushMemtablesRequest {})
1824 .await?;
1825 Ok(())
1826 }
1827}
1828
1829impl HexastoreCompact for GrpcHexastoreClients {
1830 async fn compact_range(&self, axis: PartitionAxis) -> Result<(), tonic::Status> {
1831 let mut client = self.client(axis);
1832 client
1833 .compact_range(waratah_proto::pb::CompactRangeRequest {})
1834 .await?;
1835 Ok(())
1836 }
1837}
1838
1839impl HexastoreStats for GrpcHexastoreClients {
1840 async fn stats_profile(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1841 let mut client = self.client(axis);
1842 let response = client
1843 .get_stats_profile(waratah_proto::pb::GetStatsProfileRequest {})
1844 .await?;
1845 Ok(response.into_inner().profile)
1846 }
1847
1848 async fn geo_histogram(
1849 &self,
1850 axis: PartitionAxis,
1851 section: waratah_proto::pb::GeoHistogramSection,
1852 ) -> Result<Vec<u8>, tonic::Status> {
1853 let mut client = self.client(axis);
1854 let response = client
1855 .get_geo_histogram(waratah_proto::pb::GetGeoHistogramRequest {
1856 section: section.into(),
1857 })
1858 .await?;
1859 Ok(response.into_inner().histogram)
1860 }
1861
1862 async fn temporal_histogram(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1863 let mut client = self.client(axis);
1864 let response = client
1865 .get_temporal_histogram(waratah_proto::pb::GetTemporalHistogramRequest {})
1866 .await?;
1867 Ok(response.into_inner().histogram)
1868 }
1869
1870 async fn text_seed_sketch(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1871 let mut client = self.client(axis);
1872 let response = client
1873 .get_text_seed_sketch(waratah_proto::pb::GetTextSeedSketchRequest {})
1874 .await?;
1875 Ok(response.into_inner().sketch)
1876 }
1877}
1878
1879impl HexastoreAdmin for GrpcHexastoreClients {
1880 async fn describe(&self, axis: PartitionAxis) -> Result<HexastoreDescribe, tonic::Status> {
1881 let mut client = self.client(axis);
1882 let response = client
1883 .describe(waratah_proto::pb::HexastoreDescribeRequest {})
1884 .await?
1885 .into_inner();
1886 hexastore_describe_from_proto(response)
1887 }
1888}
1889
1890impl HexastoreCatalog for GrpcHexastoreClients {
1891 async fn list_named_graphs(
1892 &self,
1893 snapshot: SnapshotId,
1894 ) -> Result<Vec<EncodedTerm>, tonic::Status> {
1895 let mut client = self.client(PartitionAxis::S);
1896 let response = client
1897 .list_named_graphs(waratah_proto::list_named_graphs_request(snapshot))
1898 .await?;
1899 response
1900 .into_inner()
1901 .graph_names
1902 .iter()
1903 .map(|bytes| {
1904 waratah_proto::term_from_bytes(bytes)
1905 .map_err(|error| tonic::Status::internal(error.to_string()))
1906 })
1907 .collect()
1908 }
1909
1910 async fn add_named_graph(
1911 &self,
1912 graph: &EncodedTerm,
1913 commit_ts: waratah_storage::CommitTs,
1914 ) -> Result<(), tonic::Status> {
1915 let mut client = self.client(PartitionAxis::S);
1916 client
1917 .add_named_graph(waratah_proto::add_named_graph_request(graph, commit_ts))
1918 .await?;
1919 Ok(())
1920 }
1921}
1922
1923impl HexastoreGeo for GrpcHexastoreClients {
1924 async fn rebuild_geo_index(&self) -> Result<(bool, bool, u64), tonic::Status> {
1925 let mut client = self.client(PartitionAxis::O);
1926 let response = client
1927 .rebuild_geo_index(pb::RebuildGeoIndexRequest {})
1928 .await?;
1929 let response = response.into_inner();
1930 Ok((
1931 response.started,
1932 response.already_in_progress,
1933 response.upgrade_ts,
1934 ))
1935 }
1936
1937 async fn renew_geo_rebuild_lease(&self) -> Result<(), tonic::Status> {
1938 let mut client = self.client(PartitionAxis::O);
1939 client
1940 .renew_geo_rebuild_lease(pb::RenewGeoRebuildLeaseRequest {})
1941 .await?;
1942 Ok(())
1943 }
1944
1945 async fn finish_geo_index_rebuild(&self) -> Result<u64, tonic::Status> {
1946 let mut client = self.client(PartitionAxis::O);
1947 let response = client
1948 .finish_geo_index_rebuild(pb::FinishGeoIndexRebuildRequest {})
1949 .await?;
1950 Ok(response.into_inner().epoch)
1951 }
1952 async fn put_geo_index(&self, puts: &[GeoIndexPut]) -> Result<u64, tonic::Status> {
1953 const FRAME_BUDGET: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE / 2;
1956 let mut client = self.client(PartitionAxis::O);
1957 let mut applied = 0u64;
1958 let mut frame: Vec<pb::GeoIndexPut> = Vec::new();
1959 let mut frame_bytes = 0usize;
1960 for put in puts {
1961 let bytes = 8 + put.term.len() + 8 + 21;
1962 if !frame.is_empty() && frame_bytes + bytes > FRAME_BUDGET {
1963 let response = client
1964 .put_geo_index(pb::PutGeoIndexRequest {
1965 puts: std::mem::take(&mut frame),
1966 })
1967 .await?;
1968 applied += response.into_inner().applied;
1969 frame_bytes = 0;
1970 }
1971 frame_bytes += bytes;
1972 frame.push(pb::GeoIndexPut {
1973 s2_cell_id: put.cell_id,
1974 term: put.term.clone(),
1975 commit_ts: put.commit_ts.0,
1976 op: match put.op {
1977 waratah_storage::StorageOp::Put => pb::StorageOp::Put as i32,
1978 waratah_storage::StorageOp::Delete => pb::StorageOp::Delete as i32,
1979 },
1980 visibility: put.visibility.0,
1981 crs84_envelope: put.envelope.map(|env| env.encode().to_vec()),
1982 });
1983 }
1984 if !frame.is_empty() {
1985 let response = client
1986 .put_geo_index(pb::PutGeoIndexRequest { puts: frame })
1987 .await?;
1988 applied += response.into_inner().applied;
1989 }
1990 Ok(applied)
1991 }
1992
1993 async fn delete_geo_term(&self, term: &[u8]) -> Result<u64, tonic::Status> {
1994 let mut client = self.client(PartitionAxis::O);
1995 let response = client
1996 .delete_geo_term(pb::DeleteGeoTermRequest {
1997 term: term.to_vec(),
1998 })
1999 .await?;
2000 Ok(response.into_inner().deleted)
2001 }
2002
2003 async fn geo_candidate_scan(
2004 &self,
2005 intervals: &[GeoCellInterval],
2006 snapshot: SnapshotId,
2007 query_envelope: Option<GeoEnvelope>,
2008 limit: u64,
2009 ) -> Result<TermPageStream, tonic::Status> {
2010 let mut client = self.client(PartitionAxis::O);
2011 let request = pb::GeoCandidateScanRequest {
2012 intervals: intervals
2013 .iter()
2014 .map(|interval| pb::geo_candidate_scan_request::CellInterval {
2015 min_cell_id: interval.min_cell_id,
2016 max_cell_id: interval.max_cell_id,
2017 })
2018 .collect(),
2019 snapshot_id: snapshot.0,
2020 limit,
2021 query_envelope: query_envelope.map(|env| env.encode().to_vec()),
2022 };
2023 let response = client.geo_candidate_scan(request).await?;
2024 let pages = response.into_inner().map(|page| {
2025 page.and_then(|page| {
2026 page.terms
2027 .iter()
2028 .map(|bytes| {
2029 waratah_proto::term_from_bytes(bytes)
2030 .map_err(|e| tonic::Status::internal(e.to_string()))
2031 })
2032 .collect()
2033 })
2034 });
2035 Ok(Box::pin(pages))
2036 }
2037
2038 async fn put_temporal_index(&self, puts: &[TemporalIndexPut]) -> Result<u64, tonic::Status> {
2039 const FRAME_BUDGET: usize = waratah_proto::GRPC_MAX_MESSAGE_SIZE / 2;
2042 let mut client = self.client(PartitionAxis::O);
2043 let mut applied = 0u64;
2044 let mut frame: Vec<pb::TemporalIndexPut> = Vec::new();
2045 let mut frame_bytes = 0usize;
2046 for put in puts {
2047 let bytes = 16 + put.term.len() + 8 + 37;
2048 if !frame.is_empty() && frame_bytes + bytes > FRAME_BUDGET {
2049 let response = client
2050 .put_temporal_index(pb::PutTemporalIndexRequest {
2051 puts: std::mem::take(&mut frame),
2052 })
2053 .await?;
2054 applied += response.into_inner().applied;
2055 frame_bytes = 0;
2056 }
2057 frame_bytes += bytes;
2058 frame.push(pb::TemporalIndexPut {
2059 node_key: put.node_key.to_be_bytes().to_vec(),
2060 term: put.term.clone(),
2061 commit_ts: put.commit_ts.0,
2062 op: match put.op {
2063 waratah_storage::StorageOp::Put => pb::StorageOp::Put,
2064 waratah_storage::StorageOp::Delete => pb::StorageOp::Delete,
2065 } as i32,
2066 visibility: put.visibility.0,
2067 begin: put.begin.to_be_bytes().to_vec(),
2068 end: put.end.to_be_bytes().to_vec(),
2069 });
2070 }
2071 if !frame.is_empty() {
2072 let response = client
2073 .put_temporal_index(pb::PutTemporalIndexRequest { puts: frame })
2074 .await?;
2075 applied += response.into_inner().applied;
2076 }
2077 Ok(applied)
2078 }
2079
2080 async fn temporal_candidate_scan(
2081 &self,
2082 intervals: &[TemporalCellInterval],
2083 snapshot: SnapshotId,
2084 predicate: TemporalQueryPredicate,
2085 limit: u64,
2086 ) -> Result<TermPageStream, tonic::Status> {
2087 let mut client = self.client(PartitionAxis::O);
2088 let request = pb::TemporalCandidateScanRequest {
2089 intervals: intervals
2090 .iter()
2091 .map(|interval| interval.encode().to_vec())
2092 .collect(),
2093 snapshot_id: snapshot.0,
2094 predicate: predicate.encode().to_vec(),
2095 limit,
2096 };
2097 let response = client.temporal_candidate_scan(request).await?;
2098 let pages = response.into_inner().map(|page| {
2099 page.and_then(|page| {
2100 page.terms
2101 .iter()
2102 .map(|bytes| {
2103 waratah_proto::term_from_bytes(bytes)
2104 .map_err(|e| tonic::Status::internal(e.to_string()))
2105 })
2106 .collect()
2107 })
2108 });
2109 Ok(Box::pin(pages))
2110 }
2111
2112 async fn rebuild_temporal_index(
2113 &self,
2114 config: waratah_storage::DyadicCovererConfig,
2115 ) -> Result<(bool, bool), tonic::Status> {
2116 let mut client = self.client(PartitionAxis::O);
2117 let response = client
2118 .rebuild_temporal_index(pb::RebuildTemporalIndexRequest {
2119 min_level: u32::from(config.min_level),
2120 max_level: u32::from(config.max_level),
2121 max_nodes: config.max_nodes as u64,
2122 })
2123 .await?;
2124 let response = response.into_inner();
2125 Ok((response.started, response.already_in_progress))
2126 }
2127
2128 async fn put_text_index(&self, docs: &[TextIndexDoc]) -> Result<u64, tonic::Status> {
2129 const FRAME_BUDGET: usize = crate::fanout::TEXT_INDEX_WIRE_BUDGET_BYTES;
2135 let mut client = self.client(PartitionAxis::O);
2136 let mut applied = 0u64;
2137 let mut frame: Vec<pb::TextIndexDoc> = Vec::new();
2138 let mut frame_bytes = 0usize;
2139 for doc in docs {
2140 let bytes = crate::fanout::text_index_doc_wire_bytes(doc);
2141 if !frame.is_empty() && frame_bytes + bytes > FRAME_BUDGET {
2142 let response = client
2143 .put_text_index(pb::PutTextIndexRequest {
2144 docs: std::mem::take(&mut frame),
2145 })
2146 .await?;
2147 applied += response.into_inner().applied;
2148 frame_bytes = 0;
2149 }
2150 frame_bytes += bytes;
2151 frame.push(waratah_proto::text_index_doc_to_proto(doc));
2152 }
2153 if !frame.is_empty() {
2154 let response = client
2155 .put_text_index(pb::PutTextIndexRequest { docs: frame })
2156 .await?;
2157 applied += response.into_inner().applied;
2158 }
2159 Ok(applied)
2160 }
2161
2162 async fn text_candidate_scan(
2163 &self,
2164 request: &TextSearchRequest,
2165 snapshot: SnapshotId,
2166 ) -> Result<TermPageStream, tonic::Status> {
2167 let mut client = self.client(PartitionAxis::O);
2168 let mode = match request.mode {
2169 waratah_storage::TextCandidateMode::Fts => pb::TextCandidateMode::Fts,
2170 waratah_storage::TextCandidateMode::Prefix => pb::TextCandidateMode::Prefix,
2171 waratah_storage::TextCandidateMode::Suffix => pb::TextCandidateMode::Suffix,
2172 };
2173 let wire = pb::TextCandidateScanRequest {
2174 mode: mode as i32,
2175 query: request.query.clone(),
2176 language: request.language.clone(),
2177 limit: request.limit,
2178 snapshot_id: snapshot.0,
2179 };
2180 let response = client.text_candidate_scan(wire).await?;
2181 let pages = response.into_inner().map(|page| {
2182 page.and_then(|page| {
2183 page.terms
2184 .iter()
2185 .map(|bytes| {
2186 waratah_proto::term_from_bytes(bytes)
2187 .map_err(|e| tonic::Status::internal(e.to_string()))
2188 })
2189 .collect()
2190 })
2191 });
2192 Ok(Box::pin(pages))
2193 }
2194
2195 async fn text_subject_scan(
2196 &self,
2197 request: &TextSubjectRequest,
2198 snapshot: SnapshotId,
2199 ) -> Result<SubjectRowStream, tonic::Status> {
2200 let mut client = self.client(PartitionAxis::O);
2201 let mode = match request.mode {
2202 waratah_storage::TextCandidateMode::Fts => pb::TextCandidateMode::Fts,
2203 waratah_storage::TextCandidateMode::Prefix => pb::TextCandidateMode::Prefix,
2204 waratah_storage::TextCandidateMode::Suffix => pb::TextCandidateMode::Suffix,
2205 };
2206 let wire = pb::TextSubjectScanRequest {
2207 mode: mode as i32,
2208 query: request.query.clone(),
2209 language: request.language.clone(),
2210 limit: request.limit,
2211 snapshot_id: snapshot.0,
2212 predicates: request
2213 .predicates
2214 .iter()
2215 .map(waratah_proto::term_to_bytes)
2216 .collect(),
2217 graph_filter_terms: request
2218 .graph_filter_terms
2219 .iter()
2220 .map(waratah_proto::term_to_bytes)
2221 .collect(),
2222 graph_filter_allow: request.graph_filter_allow,
2223 graph_name: request
2224 .graph_name
2225 .as_ref()
2226 .map(waratah_proto::term_to_bytes),
2227 merge_default_graph: request.merge_default_graph,
2228 return_graph: request.return_graph,
2229 subject_equals_graph: request.subject_equals_graph,
2230 };
2231 let response = client.text_subject_scan(wire).await?;
2232 let pages = response.into_inner().map(|page| {
2233 page.and_then(|page| {
2234 page.rows
2235 .iter()
2236 .map(text_subject_row_from_proto)
2237 .collect::<Result<Vec<_>, tonic::Status>>()
2238 })
2239 });
2240 Ok(Box::pin(pages))
2241 }
2242
2243 async fn rebuild_text_index(
2244 &self,
2245 analyzer: &str,
2246 seed_chars: u32,
2247 fingerprint: &str,
2248 wipe: bool,
2249 ) -> Result<(bool, bool, u64), tonic::Status> {
2250 let mut client = self.client(PartitionAxis::O);
2251 let response = client
2252 .rebuild_text_index(pb::RebuildTextIndexRequest {
2253 analyzer: analyzer.to_owned(),
2254 seed_chars,
2255 fingerprint: fingerprint.to_owned(),
2256 wipe,
2257 })
2258 .await?;
2259 let response = response.into_inner();
2260 Ok((
2261 response.started,
2262 response.already_in_progress,
2263 response.lease_token,
2264 ))
2265 }
2266
2267 async fn renew_text_rebuild_lease(&self, lease_token: u64) -> Result<(), tonic::Status> {
2268 let mut client = self.client(PartitionAxis::O);
2269 client
2270 .renew_text_rebuild_lease(pb::RenewTextRebuildLeaseRequest { lease_token })
2271 .await?;
2272 Ok(())
2273 }
2274
2275 async fn finish_text_index_rebuild(
2276 &self,
2277 lease_token: u64,
2278 stamp: bool,
2279 ) -> Result<u64, tonic::Status> {
2280 let mut client = self.client(PartitionAxis::O);
2281 let response = client
2282 .finish_text_index_rebuild(pb::FinishTextIndexRebuildRequest { lease_token, stamp })
2283 .await?;
2284 Ok(response.into_inner().epoch)
2285 }
2286}
2287
2288#[derive(Debug, Clone)]
2294pub struct GrpcRegistryClients {
2295 clients: BTreeMap<RegistryNodeId, StringRegistryClient<Channel>>,
2296 config: ClusterConfig,
2297}
2298
2299impl GrpcRegistryClients {
2300 pub async fn connect(config: &ClusterConfig) -> Result<Self, ComputeError> {
2302 let mut clients = BTreeMap::new();
2303 for (node, addr) in config.registry_nodes() {
2304 let endpoint =
2305 tonic::transport::Endpoint::from_shared(http_url(addr))?.tcp_nodelay(true);
2306 let client = StringRegistryClient::connect(endpoint)
2307 .await?
2308 .max_decoding_message_size(GRPC_MAX_MESSAGE_SIZE);
2309 clients.insert(node, client);
2310 }
2311 if clients.is_empty() {
2312 return Err(ComputeError::Router(
2313 waratah_router::RouterError::NoRegistryNodes,
2314 ));
2315 }
2316 Ok(Self {
2317 clients,
2318 config: config.clone(),
2319 })
2320 }
2321
2322 fn client_for_addr(
2323 &self,
2324 addr: SocketAddr,
2325 ) -> Result<StringRegistryClient<Channel>, ComputeError> {
2326 for (node, client) in &self.clients {
2327 if self.config.registry(*node)? == addr {
2328 return Ok(client.clone());
2329 }
2330 }
2331 Err(ComputeError::Router(
2332 waratah_router::RouterError::NoRegistryNodes,
2333 ))
2334 }
2335}
2336
2337impl StringRegister for GrpcRegistryClients {
2338 async fn register_strings(&self, entries: &[(StrHash, String)]) -> Result<u64, tonic::Status> {
2339 if entries.is_empty() {
2340 return Ok(0);
2341 }
2342
2343 let mut by_addr: BTreeMap<SocketAddr, Vec<(StrHash, String)>> = BTreeMap::new();
2345 for (hash, raw) in entries {
2346 let addr = self
2347 .config
2348 .registry_for_hash(*hash)
2349 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2350 by_addr.entry(addr).or_default().push((*hash, raw.clone()));
2351 }
2352
2353 let mut registered = 0u64;
2354 for (addr, batch) in by_addr {
2355 let mut client = self
2356 .client_for_addr(addr)
2357 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2358 for chunk in register_byte_chunks(&batch) {
2363 let response = client
2364 .register_strings(register_request(
2365 chunk.iter().map(|(h, r)| (*h, r.as_str())),
2366 ))
2367 .await?;
2368 registered += response.into_inner().registered;
2369 }
2370 }
2371 Ok(registered)
2372 }
2373}
2374
2375fn register_byte_chunks(batch: &[(StrHash, String)]) -> Vec<&[(StrHash, String)]> {
2384 const BUDGET: usize = GRPC_MAX_MESSAGE_SIZE / 2;
2385 const ENTRY_FRAMING: usize = 16;
2386 let mut chunks = Vec::new();
2387 let mut start = 0;
2388 let mut bytes = 0usize;
2389 for (index, (_, raw)) in batch.iter().enumerate() {
2390 let entry = ENTRY_FRAMING + std::mem::size_of::<StrHash>() + raw.len();
2391 if index > start && bytes + entry > BUDGET {
2392 chunks.push(&batch[start..index]);
2393 start = index;
2394 bytes = 0;
2395 }
2396 bytes += entry;
2397 }
2398 chunks.push(&batch[start..]);
2399 chunks
2400}
2401
2402impl StringResolve for GrpcRegistryClients {
2403 async fn resolve_strings(
2404 &self,
2405 hashes: &[StrHash],
2406 ) -> Result<Vec<Option<String>>, tonic::Status> {
2407 if hashes.is_empty() {
2408 return Ok(Vec::new());
2409 }
2410
2411 let mut by_addr: BTreeMap<SocketAddr, Vec<usize>> = BTreeMap::new();
2414 for (index, hash) in hashes.iter().enumerate() {
2415 let addr = self
2416 .config
2417 .registry_for_hash(*hash)
2418 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2419 by_addr.entry(addr).or_default().push(index);
2420 }
2421
2422 let mut resolved = vec![None; hashes.len()];
2423 for (addr, indexes) in by_addr {
2424 let mut client = self
2425 .client_for_addr(addr)
2426 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2427 let mut stream = client
2431 .resolve_strings(resolve_request(indexes.iter().map(|i| hashes[*i])))
2432 .await?
2433 .into_inner();
2434 let mut values = Vec::with_capacity(indexes.len());
2435 while let Some(frame) = stream.next().await {
2436 values.extend(frame?.values);
2437 }
2438 if values.len() != indexes.len() {
2439 return Err(tonic::Status::internal(format!(
2440 "registry {addr} returned {} values for {} hashes",
2441 values.len(),
2442 indexes.len()
2443 )));
2444 }
2445 for (index, value) in indexes.into_iter().zip(values) {
2446 resolved[index] = value.raw;
2447 }
2448 }
2449 Ok(resolved)
2450 }
2451}
2452
2453impl StringRegistryFlush for GrpcRegistryClients {
2454 async fn flush_memtables(&self) -> Result<(), tonic::Status> {
2455 for client in self.clients.values() {
2456 let mut client = client.clone();
2457 client
2458 .flush_memtables(waratah_proto::pb::FlushMemtablesRequest {})
2459 .await?;
2460 }
2461 Ok(())
2462 }
2463}
2464
2465impl StringRegistryCompact for GrpcRegistryClients {
2466 async fn compact_range(&self) -> Result<(), tonic::Status> {
2467 for client in self.clients.values() {
2468 let mut client = client.clone();
2469 client
2470 .compact_range(waratah_proto::pb::CompactRangeRequest {})
2471 .await?;
2472 }
2473 Ok(())
2474 }
2475}
2476
2477impl RegistryAdmin for GrpcRegistryClients {
2478 async fn describe(
2479 &self,
2480 node: waratah_router::RegistryNodeId,
2481 ) -> Result<RegistryDescribe, tonic::Status> {
2482 let mut client =
2483 self.clients.get(&node).cloned().ok_or_else(|| {
2484 tonic::Status::not_found(format!("no registry client for {node}"))
2485 })?;
2486 let response = client
2487 .describe(waratah_proto::pb::RegistryDescribeRequest {})
2488 .await?
2489 .into_inner();
2490 Ok(registry_describe_from_proto(response))
2491 }
2492}
2493
2494impl BlobStoreClient for GrpcRegistryClients {
2495 async fn put_blob_chunks(
2496 &self,
2497 blob_id: StrHash,
2498 payload: Arc<[u8]>,
2499 ) -> Result<(), tonic::Status> {
2500 let addr = self
2502 .config
2503 .registry_for_hash(blob_id)
2504 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2505 let mut client = self
2506 .client_for_addr(addr)
2507 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2508 const CHUNK: usize = GRPC_MAX_MESSAGE_SIZE / 2;
2511 let total_chunks = payload.len().div_ceil(CHUNK).max(1) as u64;
2512 let id_bytes = blob_id.to_be_bytes().to_vec();
2513 let frames: Vec<pb::PutBlobRequest> = payload
2514 .chunks(CHUNK)
2515 .enumerate()
2516 .map(|(seq, data)| pb::PutBlobRequest {
2517 chunks: vec![pb::BlobChunk {
2518 blob_id: id_bytes.clone(),
2519 seq: seq as u64,
2520 total_chunks,
2521 data: data.to_vec(),
2522 }],
2523 })
2524 .collect();
2525 let stream = tokio_stream::iter(frames);
2526 client.put_blob_chunks(stream).await?;
2527 Ok(())
2528 }
2529
2530 async fn put_blobs(&self, blobs: &[(StrHash, Arc<[u8]>)]) -> Result<(), tonic::Status> {
2531 if blobs.is_empty() {
2532 return Ok(());
2533 }
2534 let mut by_addr: BTreeMap<SocketAddr, Vec<pb::Blob>> = BTreeMap::new();
2541 for (blob_id, payload) in blobs {
2542 let addr = self
2543 .config
2544 .registry_for_hash(*blob_id)
2545 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2546 by_addr.entry(addr).or_default().push(pb::Blob {
2547 id: blob_id.to_be_bytes().to_vec(),
2548 data: payload.to_vec(),
2549 });
2550 }
2551 for (addr, batch) in by_addr {
2552 let mut client = self
2553 .client_for_addr(addr)
2554 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2555 client
2556 .put_blobs(pb::PutBlobsRequest { blobs: batch })
2557 .await?;
2558 }
2559 Ok(())
2560 }
2561
2562 async fn get_blobs(&self, ids: &[StrHash]) -> Result<Vec<Option<Vec<u8>>>, tonic::Status> {
2563 if ids.is_empty() {
2564 return Ok(Vec::new());
2565 }
2566 let mut per_addr: BTreeMap<SocketAddr, Vec<usize>> = BTreeMap::new();
2570 for (index, hash) in ids.iter().enumerate() {
2571 let addr = self
2572 .config
2573 .registry_for_hash(*hash)
2574 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2575 per_addr.entry(addr).or_default().push(index);
2576 }
2577 let mut out: Vec<Option<Vec<u8>>> = vec![None; ids.len()];
2578 for (addr, indexes) in per_addr {
2579 let mut client = self
2580 .client_for_addr(addr)
2581 .map_err(|e| tonic::Status::failed_precondition(e.to_string()))?;
2582 let mut distinct: BTreeMap<StrHash, Vec<usize>> = BTreeMap::new();
2586 for &index in &indexes {
2587 distinct.entry(ids[index]).or_default().push(index);
2588 }
2589 let request_ids: Vec<Vec<u8>> = distinct
2590 .keys()
2591 .map(|id| id.to_be_bytes().to_vec())
2592 .collect();
2593 let mut stream = client
2594 .get_blobs(pb::GetBlobsRequest {
2595 blob_ids: request_ids,
2596 })
2597 .await?
2598 .into_inner();
2599 let mut pending: BTreeMap<StrHash, (u64, Vec<Vec<u8>>)> = BTreeMap::new();
2607 while let Some(frame) = stream.next().await {
2608 for chunk in frame?.chunks {
2609 let Ok(id_bytes) = <[u8; 16]>::try_from(chunk.blob_id.as_slice()) else {
2610 return Err(tonic::Status::internal("blob id must be 16 bytes"));
2611 };
2612 let id = StrHash::from_be_bytes(id_bytes);
2613 let entry = pending
2614 .entry(id)
2615 .or_insert((chunk.total_chunks, Vec::new()));
2616 if entry.0 != chunk.total_chunks {
2617 return Err(tonic::Status::invalid_argument(
2618 "inconsistent total_chunks across blob chunks",
2619 ));
2620 }
2621 let seq = entry.1.len() as u64;
2622 if chunk.seq != seq {
2623 return Err(tonic::Status::invalid_argument(format!(
2624 "blob {id}: expected chunk seq {seq}, got {}",
2625 chunk.seq
2626 )));
2627 }
2628 entry.1.push(chunk.data);
2629 }
2630 }
2631 for (id, fanout) in distinct {
2632 let Some((total_chunks, parts)) = pending.remove(&id) else {
2633 continue;
2635 };
2636 let mut payload = parts.concat();
2637 if parts.len() as u64 != total_chunks {
2638 return Err(tonic::Status::internal(format!(
2639 "blob {id} declared {total_chunks} chunks but delivered {}",
2640 parts.len()
2641 )));
2642 }
2643 if StrHash::from_bytes(&payload) != id {
2644 return Err(tonic::Status::internal(format!(
2645 "blob {id} failed content-addressing verification"
2646 )));
2647 }
2648 payload.shrink_to_fit();
2649 if let Some((last, rest)) = fanout.split_last() {
2650 for index in rest {
2651 out[*index] = Some(payload.clone());
2652 }
2653 out[*last] = Some(payload);
2654 }
2655 }
2656 if !pending.is_empty() {
2657 let unclaimed: Vec<String> = pending.keys().map(ToString::to_string).collect();
2665 return Err(tonic::Status::internal(format!(
2666 "registry {addr} delivered chunks under unrequested blob ids: {unclaimed:?}"
2667 )));
2668 }
2669 }
2670 Ok(out)
2671 }
2672}
2673
2674pub(crate) fn http_url(addr: SocketAddr) -> String {
2675 format!("http://{addr}")
2676}
2677
2678fn backend_name(value: i32) -> String {
2679 match pb::StorageBackend::try_from(value).unwrap_or(pb::StorageBackend::Unspecified) {
2680 pb::StorageBackend::Memory => "memory".to_owned(),
2681 pb::StorageBackend::Rocksdb => "rocksdb".to_owned(),
2682 pb::StorageBackend::Unspecified => "unspecified".to_owned(),
2683 }
2684}
2685
2686fn lsm_from_proto(metrics: Option<pb::LsmMetrics>) -> crate::cluster::LsmMetricsView {
2687 let Some(m) = metrics else {
2688 return crate::cluster::LsmMetricsView::default();
2689 };
2690 crate::cluster::LsmMetricsView {
2691 estimate_live_data_bytes: m.estimate_live_data_bytes,
2692 estimate_num_keys: m.estimate_num_keys,
2693 total_sst_bytes: m.total_sst_bytes,
2694 memtable_bytes: m.memtable_bytes,
2695 num_running_compactions: m.num_running_compactions,
2696 num_running_flushes: m.num_running_flushes,
2697 open_total_puts: m.open_total_puts,
2698 compaction_event_count: m.compaction_event_count,
2699 named_graph_count: m.named_graph_count,
2700 entry_count: None,
2701 block_cache_capacity_bytes: m.block_cache_capacity_bytes,
2702 block_cache_usage_bytes: m.block_cache_usage_bytes,
2703 }
2704}
2705
2706pub(crate) fn hexastore_describe_from_proto(
2707 response: pb::HexastoreDescribeResponse,
2708) -> Result<HexastoreDescribe, tonic::Status> {
2709 let axis = waratah_proto::axis_from_proto(
2710 pb::PartitionAxis::try_from(response.axis).unwrap_or(pb::PartitionAxis::Unspecified),
2711 )
2712 .ok_or_else(|| tonic::Status::internal("describe returned unspecified axis"))?;
2713 Ok(HexastoreDescribe {
2714 axis,
2715 node_id: response.node_id,
2716 listen: response.listen,
2717 data_dir: response.data_dir,
2718 backend: backend_name(response.backend),
2719 version: response.version,
2720 repository_id: response.repository_id,
2721 serving: response.serving,
2722 metrics: lsm_from_proto(response.metrics),
2723 geo_index_epoch: response.geo_index_epoch,
2724 temporal_index_epoch: response.temporal_index_epoch,
2725 temporal_rebuild_in_progress: response.temporal_rebuild_in_progress,
2726 geo_rebuild_in_progress: response.geo_rebuild_in_progress,
2727 text_index_epoch: response.text_index_epoch,
2728 text_index_fingerprint: response.text_index_fingerprint,
2729 text_index_terms: response.text_index_terms,
2730 text_rebuild_in_progress: response.text_rebuild_in_progress,
2731 })
2732}
2733
2734fn registry_describe_from_proto(response: pb::RegistryDescribeResponse) -> RegistryDescribe {
2735 RegistryDescribe {
2736 node_id: response.node_id,
2737 listen: response.listen,
2738 data_dir: response.data_dir,
2739 backend: backend_name(response.backend),
2740 version: response.version,
2741 repository_id: response.repository_id,
2742 shard_count: response.shard_count,
2743 entry_count: response.entry_count,
2744 serving: response.serving,
2745 metrics: lsm_from_proto(response.metrics),
2746 }
2747}
2748
2749#[cfg(test)]
2750mod wire_frame_tests {
2751 use super::*;
2752 use tokio_stream::StreamExt;
2753 use waratah_storage::{NamedNode, ScanExhaustion};
2754
2755 #[test]
2764 #[should_panic(expected = "oversized scan request")]
2765 fn wire_budget_assert_names_the_road_in_debug() {
2766 let terms: Vec<EncodedTerm> = (0..=PUSHDOWN_TERMS_LIMIT as usize)
2769 .map(|i| EncodedTerm::from(&NamedNode::new(format!("http://ex/t{i}")).unwrap()))
2770 .collect();
2771 assert_wire_budget(&terms);
2772 }
2773
2774 #[test]
2775 fn wire_budget_assert_passes_at_the_threshold() {
2776 let terms: Vec<EncodedTerm> = (0..PUSHDOWN_TERMS_LIMIT as usize)
2777 .map(|i| EncodedTerm::from(&NamedNode::new(format!("http://ex/t{i}")).unwrap()))
2778 .collect();
2779 assert_wire_budget(&terms);
2780 }
2781
2782 fn one_row() -> waratah_storage::EncodedQuad {
2783 waratah_storage::EncodedQuad::new(
2784 waratah_storage::EncodedTerm::DefaultGraph,
2785 waratah_storage::EncodedTerm::DefaultGraph,
2786 waratah_storage::EncodedTerm::DefaultGraph,
2787 waratah_storage::EncodedTerm::DefaultGraph,
2788 )
2789 }
2790
2791 #[tokio::test]
2798 async fn terminal_verdict_moves_to_an_empty_terminal_frame() {
2799 let mut frames = scan_page_as_wire_frames(ScanPage {
2800 rows: vec![one_row()],
2801 exhausted: Some(ScanExhaustion::ExhaustedScan),
2802 });
2803 let data = frames.next().await.unwrap().unwrap();
2804 assert_eq!(data.rows.len(), 1, "the rows ride the data frame");
2805 assert_eq!(
2806 data.exhausted, None,
2807 "a completed walk's data frame carries no verdict"
2808 );
2809 let terminal = frames.next().await.unwrap().unwrap();
2810 assert!(terminal.rows.is_empty(), "the terminal frame is empty");
2811 assert_eq!(terminal.exhausted, Some(ScanExhaustion::ExhaustedScan));
2812 assert!(frames.next().await.is_none(), "exactly two frames");
2813 }
2814
2815 #[tokio::test]
2819 async fn limited_and_unpurchased_verdicts_stay_on_one_frame() {
2820 for exhausted in [Some(ScanExhaustion::Limited), None] {
2821 let mut frames = scan_page_as_wire_frames(ScanPage {
2822 rows: vec![one_row()],
2823 exhausted,
2824 });
2825 let only = frames.next().await.unwrap().unwrap();
2826 assert_eq!(only.rows.len(), 1);
2827 assert_eq!(only.exhausted, exhausted);
2828 assert!(frames.next().await.is_none(), "exactly one frame");
2829 }
2830 }
2831}
2832
2833#[cfg(test)]
2834mod register_chunk_tests {
2835 use super::*;
2836
2837 fn entry(raw_len: usize) -> (StrHash, String) {
2838 (
2839 StrHash::new(&"x".repeat(raw_len.min(64))),
2840 "y".repeat(raw_len),
2841 )
2842 }
2843
2844 #[test]
2845 fn small_batches_stay_whole() {
2846 let batch: Vec<(StrHash, String)> = (0..100).map(|_| entry(10)).collect();
2847 let chunks = register_byte_chunks(&batch);
2848 assert_eq!(chunks, vec![&batch[..]]);
2849 }
2850
2851 #[test]
2852 fn oversized_batches_split_under_the_budget() {
2853 let cap = waratah_registry::MAX_REGISTERED_STRING_BYTES;
2856 let batch: Vec<(StrHash, String)> = (0..3).map(|_| entry(cap - 1024)).collect();
2857 let chunks = register_byte_chunks(&batch);
2858 assert_eq!(
2859 chunks.len(),
2860 2,
2861 "{:?} byte sizes",
2862 chunks.iter().map(|c| c.len()).collect::<Vec<_>>()
2863 );
2864 assert_eq!(chunks[0].len(), 2);
2865 assert_eq!(chunks[1].len(), 1);
2866 for chunk in &chunks {
2868 let bytes: usize = chunk
2869 .iter()
2870 .map(|(_, raw)| 16 + std::mem::size_of::<StrHash>() + raw.len())
2871 .sum();
2872 assert!(bytes <= GRPC_MAX_MESSAGE_SIZE / 2);
2873 }
2874 }
2875
2876 #[test]
2877 fn a_single_max_entry_still_forms_a_chunk() {
2878 let cap = waratah_registry::MAX_REGISTERED_STRING_BYTES;
2879 let batch = vec![entry(cap), entry(cap), entry(cap), entry(8)];
2880 let chunks = register_byte_chunks(&batch);
2881 assert_eq!(
2883 chunks.iter().map(|c| c.len()).collect::<Vec<_>>(),
2884 vec![1, 1, 2]
2885 );
2886 }
2887}
2888
2889#[cfg(test)]
2890mod comparison_transport_tests {
2891 use std::sync::Arc;
2896 use std::sync::atomic::{AtomicUsize, Ordering};
2897
2898 use tokio_stream::StreamExt;
2899 use waratah_storage::{CompareOp, Literal, NamedNode, QuadSlot, ScanExhaustion};
2900
2901 use super::*;
2902
2903 #[derive(Clone, Default)]
2907 struct UnaryOnlyScan {
2908 scans: Arc<AtomicUsize>,
2909 }
2910
2911 impl HexastoreScan for UnaryOnlyScan {
2912 async fn scan_pattern(
2913 &self,
2914 _axis: PartitionAxis,
2915 _pattern: &EncodedTriplePattern,
2916 _snapshot: SnapshotId,
2917 _limit: u64,
2918 _permutation: Option<IndexPermutation>,
2919 _filter: Option<&BroadcastFilter>,
2920 _graph_filter: Option<&GraphFilter>,
2921 _start_after: Option<&EncodedQuad>,
2922 _merge_default_graph: bool,
2923 _iri_only: IriOnlyMask,
2924 _omitted: u8,
2925 _verdict_wanted: bool,
2926 ) -> Result<ScanPage, tonic::Status> {
2927 self.scans.fetch_add(1, Ordering::Relaxed);
2928 Ok(ScanPage {
2929 rows: vec![EncodedQuad::new(
2930 EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
2931 EncodedTerm::from(&NamedNode::new("http://ex/p").unwrap()),
2932 EncodedTerm::from(&Literal::from(1967i64)),
2933 EncodedTerm::DefaultGraph,
2934 )],
2935 exhausted: Some(ScanExhaustion::ExhaustedScan),
2936 })
2937 }
2938
2939 async fn count_pattern(
2940 &self,
2941 _axis: PartitionAxis,
2942 _pattern: &EncodedTriplePattern,
2943 _snapshot: SnapshotId,
2944 _limit: u64,
2945 _permutation: Option<IndexPermutation>,
2946 _filter: Option<&BroadcastFilter>,
2947 _graph_filter: Option<&GraphFilter>,
2948 _merge_default_graph: bool,
2949 ) -> Result<u64, tonic::Status> {
2950 unreachable!("count_pattern is not on a scan path")
2951 }
2952
2953 async fn scan_domain(
2954 &self,
2955 _permutation: IndexPermutation,
2956 _constraints: &[EncodedTerm],
2957 _snapshot: SnapshotId,
2958 _limit: u64,
2959 _start_after_constraint: Option<&EncodedTerm>,
2960 _start_after_term: Option<&EncodedTerm>,
2961 _graph_name: Option<&EncodedTerm>,
2962 _graph_filter: Option<&GraphFilter>,
2963 _iri_only_head: bool,
2964 ) -> Result<Vec<DomainScanHit>, tonic::Status> {
2965 unreachable!("scan_domain is not on a scan path")
2966 }
2967
2968 async fn scan_domain_counts(
2969 &self,
2970 _permutation: IndexPermutation,
2971 _constraints: &[EncodedTerm],
2972 _snapshot: SnapshotId,
2973 _limit: u64,
2974 _start_after_constraint: Option<&EncodedTerm>,
2975 _start_after_term: Option<&EncodedTerm>,
2976 _graph_name: Option<&EncodedTerm>,
2977 _graph_filter: Option<&GraphFilter>,
2978 _iri_only_head: bool,
2979 _merge_default_graph: bool,
2980 _mode: DomainCountMode,
2981 ) -> Result<Vec<DomainScanCountHit>, tonic::Status> {
2982 unreachable!("scan_domain_counts is not on a scan path")
2983 }
2984
2985 async fn scan_axis_head(
2986 &self,
2987 _permutation: IndexPermutation,
2988 _snapshot: SnapshotId,
2989 _limit: u64,
2990 _start_after_term: Option<&EncodedTerm>,
2991 _graph_name: Option<&EncodedTerm>,
2992 _graph_filter: Option<&GraphFilter>,
2993 _iri_only_head: bool,
2994 _head_prefixes: &[Vec<u8>],
2995 ) -> Result<Vec<EncodedTerm>, tonic::Status> {
2996 unreachable!("scan_axis_head is not on a scan path")
2997 }
2998
2999 async fn count_axis_heads(
3000 &self,
3001 _permutation: IndexPermutation,
3002 _snapshot: SnapshotId,
3003 _graph_name: Option<&EncodedTerm>,
3004 _graph_filter: Option<&GraphFilter>,
3005 _iri_only_head: bool,
3006 ) -> Result<u64, tonic::Status> {
3007 unreachable!("count_axis_heads is not on a scan path")
3008 }
3009
3010 async fn scan_axis_head_counts(
3011 &self,
3012 _permutation: IndexPermutation,
3013 _snapshot: SnapshotId,
3014 _limit: u64,
3015 _start_after_term: Option<&EncodedTerm>,
3016 _graph_name: Option<&EncodedTerm>,
3017 _graph_filter: Option<&GraphFilter>,
3018 _iri_only_head: bool,
3019 ) -> Result<Vec<AxisHeadCountHit>, tonic::Status> {
3020 unreachable!("scan_axis_head_counts is not on a scan path")
3021 }
3022 }
3023
3024 fn year_eq_1967() -> SlotComparison {
3025 SlotComparison {
3026 slot: QuadSlot::Object,
3027 op: CompareOp::Eq,
3028 term: EncodedTerm::from(&Literal::from(1967i64)),
3029 }
3030 }
3031
3032 async fn scan_with(
3033 store: &UnaryOnlyScan,
3034 comparisons: &[SlotComparison],
3035 ) -> Result<ScanPage, tonic::Status> {
3036 store
3037 .scan_pattern_with_comparisons(
3038 PartitionAxis::P,
3039 &EncodedTriplePattern::default(),
3040 SnapshotId::default(),
3041 0,
3042 None,
3043 None,
3044 None,
3045 None,
3046 false,
3047 IriOnlyMask::NONE,
3048 comparisons,
3049 0,
3050 false,
3051 )
3052 .await
3053 }
3054
3055 async fn stream_with(
3056 store: &UnaryOnlyScan,
3057 comparisons: &[SlotComparison],
3058 ) -> Result<QuadPageStream, tonic::Status> {
3059 store
3060 .scan_pattern_stream_with_comparisons(
3061 PartitionAxis::P,
3062 &EncodedTriplePattern::default(),
3063 SnapshotId::default(),
3064 0,
3065 None,
3066 None,
3067 None,
3068 None,
3069 false,
3070 IriOnlyMask::NONE,
3071 comparisons,
3072 0,
3073 false,
3074 )
3075 .await
3076 }
3077
3078 #[tokio::test]
3079 async fn empty_list_delegates_to_the_unfiltered_unary_scan() {
3080 let store = UnaryOnlyScan::default();
3081 let page = scan_with(&store, &[]).await.unwrap();
3082 assert_eq!(page.rows.len(), 1);
3083 assert_eq!(store.scans.load(Ordering::Relaxed), 1);
3084 }
3085
3086 #[tokio::test]
3087 async fn a_transport_that_ignores_the_list_still_returns_the_unfiltered_page() {
3088 let store = UnaryOnlyScan::default();
3092 let page = scan_with(&store, &[year_eq_1967()]).await.unwrap();
3093 assert_eq!(page.rows.len(), 1);
3094 assert_eq!(store.scans.load(Ordering::Relaxed), 1);
3095 }
3096
3097 #[tokio::test]
3098 async fn empty_list_stream_keeps_the_streaming_default() {
3099 let store = UnaryOnlyScan::default();
3100 let mut frames = stream_with(&store, &[]).await.unwrap();
3101 let mut rows = 0;
3102 let mut verdict = None;
3103 while let Some(frame) = frames.next().await {
3104 let frame = frame.unwrap();
3105 rows += frame.rows.len();
3106 verdict = frame.exhausted.or(verdict);
3107 }
3108 assert_eq!(rows, 1);
3109 assert_eq!(verdict, Some(ScanExhaustion::ExhaustedScan));
3110 }
3111
3112 #[tokio::test]
3113 async fn the_stream_fallback_keeps_the_unfiltered_rows_and_frames() {
3114 let store = UnaryOnlyScan::default();
3115 let mut frames = stream_with(&store, &[year_eq_1967()]).await.unwrap();
3116 let mut rows = 0;
3117 while let Some(frame) = frames.next().await {
3118 rows += frame.unwrap().rows.len();
3119 }
3120 assert_eq!(rows, 1);
3121 }
3122}
3123
3124#[cfg(test)]
3125mod text_subject_row_tests {
3126 use super::*;
3127 use waratah_storage::NamedNode;
3128
3129 #[test]
3130 fn the_default_graph_survives_the_wire_as_presence_not_a_length() {
3131 let subject = EncodedTerm::from(&NamedNode::new("http://ex/s1").unwrap());
3136 let subject_bytes = waratah_proto::term_to_bytes(&subject);
3137 let default_row = pb::TextSubjectRow {
3138 subject: subject_bytes.clone(),
3139 graph: Some(waratah_proto::term_to_bytes(&EncodedTerm::DefaultGraph)),
3140 };
3141 assert_eq!(
3142 default_row.graph.as_deref(),
3143 Some(&[][..]),
3144 "the default graph's encoded term is zero bytes"
3145 );
3146 let decoded = text_subject_row_from_proto(&default_row).unwrap();
3147 assert_eq!(decoded.subject, subject);
3148 assert!(
3149 matches!(decoded.graph, Some(EncodedTerm::DefaultGraph)),
3150 "an empty but PRESENT graph field is the default graph"
3151 );
3152
3153 let absent = pb::TextSubjectRow {
3154 subject: subject_bytes,
3155 graph: None,
3156 };
3157 let decoded = text_subject_row_from_proto(&absent).unwrap();
3158 assert!(
3159 decoded.graph.is_none(),
3160 "absence means the graph column was not requested"
3161 );
3162 }
3163}