waratah_proto/lib.rs
1//! Waratah wire contract (`waratah.v1`).
2//!
3//! Three services, owned by different processes of the local-dev cluster:
4//!
5//! | Service | RPCs | Served by |
6//! | ---------------- | --------------------------------------------------------------------- | ------------------------ |
7//! | `Hexastore` | data-plane plus `Health` / `Describe` | S / P / O partitions (`ListNamedGraphs` / `AddNamedGraph` are S-axis only; `DomainScan` / `AxisHeadScan` accept only permutations owned by the serving axis; others return `UNIMPLEMENTED`) |
8//! | `StringRegistry` | `RegisterStrings`, `ResolveStrings`, `FlushMemtables`, `CompactRange`, `Health`, `Describe` | string-registry process |
9//! | `Compute` | `Health`, `Describe` (identity + advertised HTTP URLs + routing table; no storage probes) | compute coordinator |
10//!
11//! Hexastore payloads carry encoded terms only ([`waratah_storage::StrHash`]
12//! references and inline small terms); raw strings appear solely on the registry
13//! service, which compute calls for final output bindings.
14
15#![deny(unused_must_use)]
16#![warn(missing_docs)]
17
18mod convert;
19mod error;
20
21/// Generated `waratah.v1` messages, clients, and server traits.
22#[allow(missing_docs, clippy::all, clippy::pedantic)]
23pub mod pb {
24 include!(concat!(env!("OUT_DIR"), "/waratah.v1.rs"));
25}
26
27pub use convert::{
28 OMIT_GRAPH, OMIT_NONE, OMIT_OBJECT, OMIT_PREDICATE, OMIT_SUBJECT, PatternSlot, QuadVersion,
29 add_named_graph_request, axis_from_proto, axis_to_proto, count_mode_from_proto,
30 count_mode_to_proto, insert_request, list_named_graphs_request, op_from_proto, op_to_proto,
31 pattern_from_proto, pattern_slot_from_proto, pattern_slot_to_proto, pattern_to_proto,
32 permutation_from_proto, permutation_to_proto, quad_from_proto, quad_from_proto_omitting,
33 quad_to_proto, quad_version_from_proto, quad_version_to_proto, register_request,
34 replace_pair_from_proto, replace_pair_to_proto, resolve_request, scan_exhaustion_from_proto,
35 scan_exhaustion_from_proto_opt, scan_exhaustion_to_proto, scan_request, scan_request_filtered,
36 scan_request_page, slot_comparison_from_proto, slot_comparison_to_proto,
37 slot_comparisons_from_proto, slot_comparisons_to_proto, slot_mask_from_wire,
38 str_hash_from_bytes, str_hash_to_bytes, term_from_bytes, term_to_bytes,
39 text_index_doc_from_proto, text_index_doc_to_proto, with_comparisons, with_omitted_slots,
40 with_verdict_wanted,
41};
42pub use error::ProtoError;
43
44pub use pb::compute_client::ComputeClient;
45pub use pb::compute_server::{Compute, ComputeServer};
46pub use pb::hexastore_client::HexastoreClient;
47pub use pb::hexastore_server::{Hexastore, HexastoreServer};
48pub use pb::string_registry_client::StringRegistryClient;
49pub use pb::string_registry_server::{StringRegistry, StringRegistryServer};
50
51/// Map a `spawn_blocking` join failure (handler panic or runtime shutdown) to
52/// a `tonic::Status`.
53///
54/// Storage and registry handlers run their synchronous RocksDB walks on the
55/// blocking pool so one long scan never pins an async runtime worker; a
56/// failed join means that task panicked or the runtime is shutting down.
57/// `worker` names the failing role for the message (`"storage"` /
58/// `"registry"`). `join` is the `tokio::task::JoinError` (taken by
59/// `Display` so this crate needs no tokio dependency). `tonic::Status` is
60/// the error type both deployments share: the gRPC status in the cluster,
61/// the client-trait error in-process.
62pub fn blocking_join_error(worker: &str, join: impl std::fmt::Display) -> tonic::Status {
63 tonic::Status::internal(format!("{worker} worker failed: {join}"))
64}
65
66/// Maximum size of one gRPC message, pinned explicitly on every client
67/// endpoint and server service in the cluster (tonic's default is the same
68/// 4 MiB today; setting it keeps the ceiling deterministic across tonic
69/// upgrades). Unary responses that could exceed it — an unlimited
70/// `ScanPattern` over a large prefix — must use `ScanPatternStream`
71/// instead; every streaming batch stays comfortably below it.
72pub const GRPC_MAX_MESSAGE_SIZE: usize = 4 * 1024 * 1024;
73
74/// Rows per streaming frame of a `ScanPatternStream` response. This is the
75/// wire-chunking unit of a scan (the partition packs a walk into frames of
76/// this many rows and pauses on channel backpressure) — it is *not* a
77/// compute-side demand: clients request a row count per RPC and the
78/// response arrives as `ceil(n / SCAN_STREAM_FRAME_ROWS)` frames, reassembled
79/// by the client-side drainer. Compute consumers therefore never see frame
80/// boundaries; the constant matters here on the wire and as the transport
81/// floor for compute-side page demands.
82pub const SCAN_STREAM_FRAME_ROWS: usize = 8_192;
83
84/// Worst-case serialized bytes one row contributes to a
85/// `ScanPatternResponse`, dividing [`GRPC_MAX_MESSAGE_SIZE`] into the
86/// maximum row count a unary scan response may carry. Worked from the
87/// term-encoding invariant and proto framing, per row:
88///
89/// ```text
90/// per term field 1 tag byte + 1 length varint + WRITTEN_TERM_MAX_SIZE
91/// = 1 + 1 + 33 = 35 bytes
92/// quad payload 4 term fields = 140 bytes
93/// outer framing 1 field tag + 2 length varints (payload ≥ 128)
94/// = 3 bytes
95/// total = 143 bytes
96/// ```
97///
98/// Inputs and their validity bounds (each is load-bearing; the pinning
99/// test below fails if any moves):
100/// * `WRITTEN_TERM_MAX_SIZE` (33) — the largest encoded term, a type
101/// byte plus two 16-byte halves (the hashed typed/lang literal
102/// families). The per-term length varint is one byte only while this
103/// stays under 128; the outer quad length varint is two bytes only
104/// while the quad payload stays under 16,384.
105/// * four `bytes` slots on `waratah.v1.EncodedQuad` and no fifth field;
106/// DefaultGraph and omitted slots only ever shrink a slot below the
107/// bound, never grow it.
108///
109/// This is the wire WORST case — every slot of every row carrying a
110/// max-width literal simultaneously. Real pages are dominated by 17-byte
111/// node terms (~79 B/row), but the unary ceiling must hold for the data
112/// the encoder can produce, not the data we expect.
113pub const WORST_CASE_QUAD_WIRE: usize =
114 3 + 4 * (2 + waratah_storage::encode::WRITTEN_TERM_MAX_SIZE);
115
116#[cfg(test)]
117mod wire_budget_tests {
118 use prost::Message;
119
120 /// Pin the wire-budget divisor from both ends: the max-width term is
121 /// REACHABLE (a hashed typed literal encodes to exactly
122 /// `WRITTEN_TERM_MAX_SIZE` — the bound is tight, not vacuous), and the
123 /// serialized per-row contribution of a quad carrying four of them
124 /// equals [`super::WORST_CASE_QUAD_WIRE`] exactly. A future term
125 /// variant above 33 bytes, a fifth slot on `EncodedQuad`, or a proto
126 /// framing change moves the serialized size away from the constant
127 /// and fails here — before any unary response silently exceeds
128 /// [`super::GRPC_MAX_MESSAGE_SIZE`].
129 #[test]
130 fn worst_case_quad_wire_matches_serialized_max_width_quad() {
131 let max_width_term = waratah_storage::EncodedTerm::BigTypedLiteral {
132 value_id: waratah_storage::StrHash::new("a lexical form long enough to hash"),
133 datatype_id: waratah_storage::StrHash::new("http://www.w3.org/2001/XMLSchema#decimal"),
134 };
135 let term_bytes = waratah_storage::encode_term_bytes(&max_width_term);
136 assert_eq!(
137 term_bytes.len(),
138 waratah_storage::encode::WRITTEN_TERM_MAX_SIZE,
139 "the hashed typed literal family must still be the max-width term"
140 );
141
142 let quad = crate::pb::EncodedQuad {
143 subject: term_bytes.clone().into(),
144 predicate: term_bytes.clone().into(),
145 object: term_bytes.clone().into(),
146 graph_name: term_bytes.clone().into(),
147 };
148 let one_row = crate::pb::ScanPatternResponse {
149 quads: vec![quad],
150 exhausted: None,
151 };
152 let zero_rows = crate::pb::ScanPatternResponse {
153 quads: Vec::new(),
154 exhausted: None,
155 };
156 let per_row = one_row.encoded_len() - zero_rows.encoded_len();
157 assert_eq!(
158 per_row,
159 super::WORST_CASE_QUAD_WIRE,
160 "the serialized per-row wire cost must equal the budget divisor"
161 );
162 }
163}