Skip to main content

waratah_proto/
convert.rs

1//! Conversions between `waratah.v1` messages and `waratah_storage` types.
2//!
3//! Only encoded forms cross the wire: term slots carry the Oxigraph-compatible
4//! byte encoding, so long strings travel as [`StrHash`] references and are
5//! resolved through the string registry at final binding time.
6
7use waratah_storage::encode::{TermReader, encode_term_bytes};
8use waratah_storage::{
9    CommitTs, CompareOp, DomainCountMode, EncodedQuad, EncodedTerm, EncodedTriplePattern,
10    IndexPermutation, IriOnlyMask, PartitionAxis, QuadSlot, ReplacePair, SlotComparison,
11    SnapshotId, StorageOp, StrHash, TextIndexDoc, VisibilityLabel,
12};
13
14use crate::error::ProtoError;
15use crate::pb;
16
17/// One decoded hexastore record: quad plus its Phase 2b version metadata.
18#[derive(Debug, Clone, PartialEq)]
19pub struct QuadVersion {
20    /// Encoded quad terms.
21    pub quad: EncodedQuad,
22    /// Cluster commit timestamp of this version.
23    pub commit_ts: CommitTs,
24    /// `Put` or `Delete`.
25    pub op: StorageOp,
26    /// Cell-level visibility label (`0` = unrestricted).
27    pub visibility: VisibilityLabel,
28}
29
30/// Serialize one encoded term. The default graph serializes to zero bytes.
31pub fn term_to_bytes(term: &EncodedTerm) -> Vec<u8> {
32    encode_term_bytes(term)
33}
34
35/// Decode exactly one encoded term; empty input is the default graph.
36pub fn term_from_bytes(bytes: &[u8]) -> Result<EncodedTerm, ProtoError> {
37    if bytes.is_empty() {
38        return Ok(EncodedTerm::DefaultGraph);
39    }
40    let mut cursor = bytes;
41    let term = cursor.read_term()?;
42    if !cursor.is_empty() {
43        return Err(ProtoError::TrailingTermBytes(cursor.len()));
44    }
45    Ok(term)
46}
47
48/// Serialize a `StrHash` as 16 big-endian bytes.
49pub fn str_hash_to_bytes(hash: StrHash) -> Vec<u8> {
50    hash.to_be_bytes().to_vec()
51}
52
53/// Decode a 16-byte big-endian `StrHash`.
54pub fn str_hash_from_bytes(bytes: &[u8]) -> Result<StrHash, ProtoError> {
55    let bytes: [u8; 16] = bytes
56        .try_into()
57        .map_err(|_| ProtoError::StrHashLength(bytes.len()))?;
58    Ok(StrHash::from_be_bytes(bytes))
59}
60
61/// Encode a quad for the wire.
62///
63/// Field types are `bytes::Bytes` (see `build.rs`), so each term `Vec` is
64/// converted by ownership; the scan side hands out refcounted slices instead.
65pub fn quad_to_proto(quad: &EncodedQuad) -> pb::EncodedQuad {
66    pb::EncodedQuad {
67        subject: term_to_bytes(&quad.subject).into(),
68        predicate: term_to_bytes(&quad.predicate).into(),
69        object: term_to_bytes(&quad.object).into(),
70        graph_name: term_to_bytes(&quad.graph_name).into(),
71    }
72}
73
74/// Decode a quad from the wire.
75pub fn quad_from_proto(quad: &pb::EncodedQuad) -> Result<EncodedQuad, ProtoError> {
76    Ok(EncodedQuad::new(
77        term_from_bytes(&quad.subject)?,
78        term_from_bytes(&quad.predicate)?,
79        term_from_bytes(&quad.object)?,
80        term_from_bytes(&quad.graph_name)?,
81    ))
82}
83
84// === Scan-response slot omission ==========================================
85//
86// A scan response may leave slots empty because the receiver already knows
87// them (see `ScanPatternRequest.omitted_slots`). An empty slot field is
88// indistinguishable on the wire from the default graph's zero-length encoding,
89// so a receiver must consult the mask and never decode an omitted slot.
90
91// The slot bits and the restore rule live in `waratah_storage` beside the slot
92// types, shared with the in-process decoder so the two transports apply one
93// rule.
94pub use waratah_storage::{
95    OMIT_GRAPH, OMIT_NONE, OMIT_OBJECT, OMIT_PREDICATE, OMIT_SUBJECT, omitted_slot_term,
96};
97
98/// Validate an `omitted_slots` field: only the four slot bits may be set.
99pub fn slot_mask_from_wire(value: u32) -> Result<u8, ProtoError> {
100    if value & !0x0F != 0 {
101        return Err(ProtoError::SlotMask(value));
102    }
103    Ok(value as u8)
104}
105
106/// Decode a quad whose slots may have been omitted, reassembling them exactly.
107///
108/// An omitted slot is never guessed:
109///
110/// - a slot the request binds falls back to that bound term, so a bind-join
111///   probe that pins the subject, or a scan with a constant predicate, gets
112///   the real term back without any bytes on the wire;
113/// - an omitted free slot has no consumer, and reads as the counted-presence
114///   sentinel ([`waratah_storage::ENCODED_TERM_TRUE`]). That term is already
115///   reserved in every query dictionary (`TermId::COUNTED_PRESENCE`), so
116///   interning it cannot invent a data value, and it avoids
117///   [`EncodedTerm::Placeholder`], which is neither encodable to nor decodable
118///   from the store.
119///
120/// `pattern` must be the request's own effective pattern, not the plan-time
121/// one: broadcast grounding binds a slot at execution time and the partition
122/// omits the slot it was told to.
123///
124/// In debug builds an omitted field is asserted to be empty, so a packer bug
125/// surfaces as an assertion rather than as a silently wrong term.
126pub fn quad_from_proto_omitting(
127    quad: &pb::EncodedQuad,
128    pattern: &EncodedTriplePattern,
129    omitted: u8,
130) -> Result<EncodedQuad, ProtoError> {
131    Ok(EncodedQuad::new(
132        slot_from_proto(
133            &quad.subject,
134            pattern.subject.as_ref(),
135            omitted & OMIT_SUBJECT,
136        )?,
137        slot_from_proto(
138            &quad.predicate,
139            pattern.predicate.as_ref(),
140            omitted & OMIT_PREDICATE,
141        )?,
142        slot_from_proto(&quad.object, pattern.object.as_ref(), omitted & OMIT_OBJECT)?,
143        slot_from_proto(
144            &quad.graph_name,
145            pattern.graph_name.as_ref(),
146            omitted & OMIT_GRAPH,
147        )?,
148    ))
149}
150
151fn slot_from_proto(
152    raw: &[u8],
153    bound: Option<&EncodedTerm>,
154    omit: u8,
155) -> Result<EncodedTerm, ProtoError> {
156    if omit == 0 {
157        return term_from_bytes(raw);
158    }
159    debug_assert!(
160        raw.is_empty(),
161        "omitted slot carries {} byte(s); the partition must leave it empty",
162        raw.len()
163    );
164    Ok(omitted_slot_term(bound))
165}
166
167/// Encode a partially-bound pattern for the wire.
168pub fn pattern_to_proto(pattern: &EncodedTriplePattern) -> pb::EncodedTriplePattern {
169    pb::EncodedTriplePattern {
170        subject: pattern.subject.as_ref().map(term_to_bytes),
171        predicate: pattern.predicate.as_ref().map(term_to_bytes),
172        object: pattern.object.as_ref().map(term_to_bytes),
173        graph_name: pattern.graph_name.as_ref().map(term_to_bytes),
174    }
175}
176
177/// Decode a partially-bound pattern from the wire.
178pub fn pattern_from_proto(
179    pattern: &pb::EncodedTriplePattern,
180) -> Result<EncodedTriplePattern, ProtoError> {
181    Ok(EncodedTriplePattern {
182        subject: optional_term(pattern.subject.as_deref())?,
183        predicate: optional_term(pattern.predicate.as_deref())?,
184        object: optional_term(pattern.object.as_deref())?,
185        graph_name: optional_term(pattern.graph_name.as_deref())?,
186    })
187}
188
189fn optional_term(bytes: Option<&[u8]>) -> Result<Option<EncodedTerm>, ProtoError> {
190    bytes.map(term_from_bytes).transpose()
191}
192
193/// Encode a versioned record for the wire.
194pub fn quad_version_to_proto(version: &QuadVersion) -> pb::QuadVersion {
195    pb::QuadVersion {
196        quad: Some(quad_to_proto(&version.quad)),
197        commit_ts: version.commit_ts.0,
198        op: op_to_proto(version.op) as i32,
199        visibility: version.visibility.0,
200    }
201}
202
203/// Decode a versioned record from the wire.
204/// Encode one replace pair for the wire.
205pub fn replace_pair_to_proto(pair: &ReplacePair) -> pb::replace_quads_request::Pair {
206    pb::replace_quads_request::Pair {
207        subject: term_to_bytes(&pair.subject),
208        predicate: term_to_bytes(&pair.predicate),
209        graph_name: term_to_bytes(&pair.graph_name),
210        old_object: term_to_bytes(&pair.old_object),
211        new_object: term_to_bytes(&pair.new_object),
212    }
213}
214
215/// Decode one replace pair from the wire.
216pub fn replace_pair_from_proto(
217    pair: &pb::replace_quads_request::Pair,
218) -> Result<ReplacePair, ProtoError> {
219    Ok(ReplacePair {
220        subject: term_from_bytes(&pair.subject)?,
221        predicate: term_from_bytes(&pair.predicate)?,
222        graph_name: term_from_bytes(&pair.graph_name)?,
223        old_object: term_from_bytes(&pair.old_object)?,
224        new_object: term_from_bytes(&pair.new_object)?,
225    })
226}
227
228/// Encode one text-index document for the wire.
229pub fn text_index_doc_to_proto(doc: &TextIndexDoc) -> pb::TextIndexDoc {
230    pb::TextIndexDoc {
231        term: doc.term.clone(),
232        lexical: doc.lexical.clone(),
233        language: doc.language.clone(),
234        predicate: doc.predicate.clone(),
235    }
236}
237
238/// Decode one text-index document from the wire.
239pub fn text_index_doc_from_proto(doc: &pb::TextIndexDoc) -> TextIndexDoc {
240    TextIndexDoc {
241        term: doc.term.clone(),
242        lexical: doc.lexical.clone(),
243        language: doc.language.clone(),
244        predicate: doc.predicate.clone(),
245    }
246}
247
248/// Decode a quad version from the wire.
249pub fn quad_version_from_proto(version: &pb::QuadVersion) -> Result<QuadVersion, ProtoError> {
250    let quad = version
251        .quad
252        .as_ref()
253        .ok_or(ProtoError::MissingField("QuadVersion.quad"))?;
254    Ok(QuadVersion {
255        quad: quad_from_proto(quad)?,
256        commit_ts: CommitTs(version.commit_ts),
257        op: op_from_proto(version.op())?,
258        visibility: VisibilityLabel(version.visibility),
259    })
260}
261
262/// Map a partition axis onto its wire enum value.
263pub fn axis_to_proto(axis: PartitionAxis) -> pb::PartitionAxis {
264    match axis {
265        PartitionAxis::S => pb::PartitionAxis::S,
266        PartitionAxis::P => pb::PartitionAxis::P,
267        PartitionAxis::O => pb::PartitionAxis::O,
268    }
269}
270
271/// Map a wire axis value; `UNSPECIFIED` means "caller did not assert an axis".
272pub fn axis_from_proto(axis: pb::PartitionAxis) -> Option<PartitionAxis> {
273    match axis {
274        pb::PartitionAxis::Unspecified => None,
275        pb::PartitionAxis::S => Some(PartitionAxis::S),
276        pb::PartitionAxis::P => Some(PartitionAxis::P),
277        pb::PartitionAxis::O => Some(PartitionAxis::O),
278    }
279}
280
281/// Map an index permutation onto its wire enum value.
282pub fn permutation_to_proto(permutation: IndexPermutation) -> pb::IndexPermutation {
283    match permutation {
284        IndexPermutation::Spog => pb::IndexPermutation::Spog,
285        IndexPermutation::Sopg => pb::IndexPermutation::Sopg,
286        IndexPermutation::Psog => pb::IndexPermutation::Psog,
287        IndexPermutation::Posg => pb::IndexPermutation::Posg,
288        IndexPermutation::Opsg => pb::IndexPermutation::Opsg,
289        IndexPermutation::Tsg => pb::IndexPermutation::Tsg,
290    }
291}
292
293/// Map a wire permutation value; `UNSPECIFIED` lets the partition choose.
294pub fn permutation_from_proto(permutation: pb::IndexPermutation) -> Option<IndexPermutation> {
295    match permutation {
296        pb::IndexPermutation::Unspecified => None,
297        pb::IndexPermutation::Spog => Some(IndexPermutation::Spog),
298        pb::IndexPermutation::Sopg => Some(IndexPermutation::Sopg),
299        pb::IndexPermutation::Psog => Some(IndexPermutation::Psog),
300        pb::IndexPermutation::Posg => Some(IndexPermutation::Posg),
301        pb::IndexPermutation::Opsg => Some(IndexPermutation::Opsg),
302        pb::IndexPermutation::Tsg => Some(IndexPermutation::Tsg),
303    }
304}
305
306/// Map a wire domain-count mode; `ROWS` is the zero default.
307pub fn count_mode_from_proto(mode: pb::DomainCountMode) -> DomainCountMode {
308    match mode {
309        pb::DomainCountMode::Rows => DomainCountMode::Rows,
310        pb::DomainCountMode::DistinctTerms => DomainCountMode::DistinctTerms,
311        pb::DomainCountMode::DistinctGraphs => DomainCountMode::DistinctGraphs,
312    }
313}
314
315/// Map a storage domain-count mode onto its wire enum value.
316pub fn count_mode_to_proto(mode: DomainCountMode) -> pb::DomainCountMode {
317    match mode {
318        DomainCountMode::Rows => pb::DomainCountMode::Rows,
319        DomainCountMode::DistinctTerms => pb::DomainCountMode::DistinctTerms,
320        DomainCountMode::DistinctGraphs => pb::DomainCountMode::DistinctGraphs,
321    }
322}
323
324/// Map a present wire scan-exhaustion verdict. Unknown NON-ZERO values
325/// (a future enum addition this client does not know) read as `Limited`
326/// — the safe "stopped at a demand boundary; resume or infer" reading,
327/// never a terminal claim. The zero placeholder is handled one layer up
328/// by [`scan_exhaustion_from_proto_opt`], which maps it to absence per
329/// the wire contract.
330pub fn scan_exhaustion_from_proto(verdict: i32) -> waratah_storage::ScanExhaustion {
331    match pb::ScanExhaustion::try_from(verdict) {
332        Ok(pb::ScanExhaustion::Limited) => waratah_storage::ScanExhaustion::Limited,
333        Ok(pb::ScanExhaustion::ExhaustedFilterTerms) => {
334            waratah_storage::ScanExhaustion::ExhaustedFilterTerms
335        }
336        Ok(pb::ScanExhaustion::ExhaustedScan) => waratah_storage::ScanExhaustion::ExhaustedScan,
337        // UNSPECIFIED or an unknown value: the safe reading is "the walk
338        // stopped at a demand boundary" — the consumer resumes or infers.
339        _ => waratah_storage::ScanExhaustion::Limited,
340    }
341}
342
343/// Map an optional wire verdict: unset — or an explicit `UNSPECIFIED`
344/// zero, the placeholder the wire contract says "reads as no verdict" —
345/// means no verdict was purchased and nothing is claimed. Without this
346/// filter, a zero from a future peer would collapse through the safe
347/// fallback into `Some(Limited)`, contradicting the contract and making
348/// "a purchased `Limited`" indistinguishable from "nothing claimed".
349pub fn scan_exhaustion_from_proto_opt(
350    verdict: Option<i32>,
351) -> Option<waratah_storage::ScanExhaustion> {
352    verdict
353        .filter(|verdict| *verdict != 0)
354        .map(scan_exhaustion_from_proto)
355}
356
357/// Map a storage scan-exhaustion verdict onto its wire enum value.
358pub fn scan_exhaustion_to_proto(verdict: waratah_storage::ScanExhaustion) -> pb::ScanExhaustion {
359    match verdict {
360        waratah_storage::ScanExhaustion::Limited => pb::ScanExhaustion::Limited,
361        waratah_storage::ScanExhaustion::ExhaustedFilterTerms => {
362            pb::ScanExhaustion::ExhaustedFilterTerms
363        }
364        waratah_storage::ScanExhaustion::ExhaustedScan => pb::ScanExhaustion::ExhaustedScan,
365    }
366}
367
368/// Map a storage operation onto its wire enum value.
369pub fn op_to_proto(op: StorageOp) -> pb::StorageOp {
370    match op {
371        StorageOp::Put => pb::StorageOp::Put,
372        StorageOp::Delete => pb::StorageOp::Delete,
373    }
374}
375
376/// Map a wire operation value; `UNSPECIFIED` is rejected.
377pub fn op_from_proto(op: pb::StorageOp) -> Result<StorageOp, ProtoError> {
378    match op {
379        pb::StorageOp::Unspecified => Err(ProtoError::UnspecifiedEnum("QuadVersion.op")),
380        pb::StorageOp::Put => Ok(StorageOp::Put),
381        pb::StorageOp::Delete => Ok(StorageOp::Delete),
382    }
383}
384
385/// Which pattern slot a broadcast filter applies to.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub enum PatternSlot {
388    /// Subject position.
389    Subject,
390    /// Predicate position.
391    Predicate,
392    /// Object position.
393    Object,
394}
395
396/// Build a `ScanPattern` / `CountPattern` request.
397///
398/// `permutation` of `None` lets the partition pick its longest-prefix
399/// axis-local index; `limit` of `0` is unlimited. `CountPattern` uses the
400/// same message and returns a `uint64` instead of encoded quads.
401pub fn scan_request(
402    pattern: &EncodedTriplePattern,
403    snapshot: SnapshotId,
404    limit: u64,
405    permutation: Option<IndexPermutation>,
406) -> pb::ScanPatternRequest {
407    scan_request_filtered(pattern, snapshot, limit, permutation, None, &[])
408}
409
410/// Build a `ScanPattern` request with an optional broadcast filter set.
411pub fn scan_request_filtered(
412    pattern: &EncodedTriplePattern,
413    snapshot: SnapshotId,
414    limit: u64,
415    permutation: Option<IndexPermutation>,
416    filter_slot: Option<PatternSlot>,
417    filter_terms: &[EncodedTerm],
418) -> pb::ScanPatternRequest {
419    scan_request_page(
420        pattern,
421        snapshot,
422        limit,
423        permutation,
424        filter_slot,
425        filter_terms,
426        None,
427        &[],
428        false,
429        false,
430        IriOnlyMask::NONE,
431    )
432}
433
434/// Build a `ScanPattern` request with an exclusive `start_after` cursor.
435///
436/// `graph_filter_allow` is `false` for a block-list (the proto3 default;
437/// empty terms block nothing) and `true` for an allow-list (empty terms
438/// allow nothing). `pattern.graph_name` still applies either way.
439#[allow(clippy::too_many_arguments)]
440pub fn scan_request_page(
441    pattern: &EncodedTriplePattern,
442    snapshot: SnapshotId,
443    limit: u64,
444    permutation: Option<IndexPermutation>,
445    filter_slot: Option<PatternSlot>,
446    filter_terms: &[EncodedTerm],
447    start_after: Option<&EncodedQuad>,
448    graph_filter_terms: &[EncodedTerm],
449    graph_filter_allow: bool,
450    merge_default_graph: bool,
451    iri_only: IriOnlyMask,
452) -> pb::ScanPatternRequest {
453    pb::ScanPatternRequest {
454        pattern: Some(pattern_to_proto(pattern)),
455        snapshot_id: snapshot.0,
456        limit,
457        permutation: permutation
458            .map(permutation_to_proto)
459            .unwrap_or(pb::IndexPermutation::Unspecified) as i32,
460        filter_slot: filter_slot
461            .map(pattern_slot_to_proto)
462            .unwrap_or(pb::PatternSlot::Unspecified) as i32,
463        filter_terms: filter_terms.iter().map(term_to_bytes).collect(),
464        start_after: start_after.map(quad_to_proto),
465        graph_filter_terms: graph_filter_terms.iter().map(term_to_bytes).collect(),
466        graph_filter_allow,
467        merge_default_graph,
468        iri_only_subject: iri_only.subject,
469        iri_only_object: iri_only.object,
470        // Full payload by default. Only a caller that knows how the receiver
471        // reassembles a slot (a bound pattern term, or the counted-presence
472        // sentinel) may set a mask, via [`with_omitted_slots`].
473        omitted_slots: 0,
474        // Level-triggered page limit by default (stop at the limit'th row);
475        // a consumer that will issue another request after a full page opts
476        // in to the honest terminal verdict via [`with_verdict_wanted`].
477        verdict_wanted: false,
478        // No slot comparisons by default; a caller attaches them with
479        // [`with_comparisons`].
480        comparisons: Vec::new(),
481    }
482}
483
484/// Mark response slots the partition should leave empty.
485///
486/// The receiver reassembles each omitted slot from the request's own bound
487/// pattern term, or from its counted-presence sentinel when no consumer reads
488/// it. Cursors must never be built from a request that omits a slot: compute
489/// only sets this on requests whose rows never become `start_after`.
490pub fn with_omitted_slots(
491    mut request: pb::ScanPatternRequest,
492    omitted: u8,
493) -> pb::ScanPatternRequest {
494    request.omitted_slots = u32::from(omitted);
495    request
496}
497
498/// Set the consumer's exhaustion-verdict declaration (see the
499/// `verdict_wanted` field on `ScanPatternRequest`): `true` only when a
500/// full page would be followed by another request, so the walk should
501/// keep scanning past a full page to report an honest terminal verdict at
502/// exact limit boundaries. The proto default (`false`) stops the walk at
503/// the limit'th row.
504pub fn with_verdict_wanted(
505    mut request: pb::ScanPatternRequest,
506    verdict_wanted: bool,
507) -> pb::ScanPatternRequest {
508    request.verdict_wanted = verdict_wanted;
509    request
510}
511
512/// Attach slot comparisons to a scan request (ANDed in list order).
513///
514/// The partition evaluates them inside the walk and drops only rows that
515/// provably fail; undecidable rows are kept and the compute-side FILTER
516/// conjunct stays authoritative. `ScanPattern` and `ScanPatternStream` honor
517/// the field; `CountPattern` rejects it. A graph-slot comparison is an error:
518/// the wire carries S/P/O only, and graph constraints belong in the
519/// graph-filter fields.
520pub fn with_comparisons(
521    mut request: pb::ScanPatternRequest,
522    comparisons: &[SlotComparison],
523) -> Result<pb::ScanPatternRequest, ProtoError> {
524    request.comparisons = slot_comparisons_to_proto(comparisons)?;
525    Ok(request)
526}
527
528/// Encode one slot comparison for the wire.
529pub fn slot_comparison_to_proto(
530    comparison: &SlotComparison,
531) -> Result<pb::SlotComparison, ProtoError> {
532    let slot = quad_slot_to_proto(comparison.slot).ok_or(ProtoError::GraphComparisonSlot)?;
533    Ok(pb::SlotComparison {
534        slot: slot as i32,
535        op: compare_op_to_proto(comparison.op) as i32,
536        term: term_to_bytes(&comparison.term),
537    })
538}
539
540/// Encode a comparison list for the wire.
541pub fn slot_comparisons_to_proto(
542    comparisons: &[SlotComparison],
543) -> Result<Vec<pb::SlotComparison>, ProtoError> {
544    comparisons.iter().map(slot_comparison_to_proto).collect()
545}
546
547/// Decode one slot comparison.
548///
549/// Graph-slot and unknown enum values are rejected: the wire carries S/P/O
550/// only, and a silent fallback would let a comparison filter the wrong slot.
551/// An empty `term` is rejected too: the generic term decoder would read it as
552/// the default graph, which is never an S/P/O term, so a half-filled request
553/// would silently wipe the result. Graph constraints belong in the
554/// graph-filter fields, not in a slot comparison.
555pub fn slot_comparison_from_proto(
556    comparison: &pb::SlotComparison,
557) -> Result<SlotComparison, ProtoError> {
558    if comparison.term.is_empty() {
559        return Err(ProtoError::EmptyTerm("SlotComparison.term"));
560    }
561    let slot = match pb::PatternSlot::try_from(comparison.slot) {
562        Ok(pb::PatternSlot::Subject) => QuadSlot::Subject,
563        Ok(pb::PatternSlot::Predicate) => QuadSlot::Predicate,
564        Ok(pb::PatternSlot::Object) => QuadSlot::Object,
565        Ok(pb::PatternSlot::Unspecified) => {
566            return Err(ProtoError::UnspecifiedEnum("SlotComparison.slot"));
567        }
568        Err(_) => {
569            return Err(ProtoError::UnknownEnum(
570                "SlotComparison.slot",
571                comparison.slot,
572            ));
573        }
574    };
575    let op = match pb::CompareOp::try_from(comparison.op) {
576        Ok(pb::CompareOp::Eq) => CompareOp::Eq,
577        Ok(pb::CompareOp::Ne) => CompareOp::Ne,
578        Ok(pb::CompareOp::Lt) => CompareOp::Lt,
579        Ok(pb::CompareOp::Le) => CompareOp::Le,
580        Ok(pb::CompareOp::Gt) => CompareOp::Gt,
581        Ok(pb::CompareOp::Ge) => CompareOp::Ge,
582        Err(_) => return Err(ProtoError::UnknownEnum("SlotComparison.op", comparison.op)),
583    };
584    Ok(SlotComparison {
585        slot,
586        op,
587        term: term_from_bytes(&comparison.term)?,
588    })
589}
590
591/// Decode a comparison list.
592pub fn slot_comparisons_from_proto(
593    comparisons: &[pb::SlotComparison],
594) -> Result<Vec<SlotComparison>, ProtoError> {
595    comparisons.iter().map(slot_comparison_from_proto).collect()
596}
597
598fn quad_slot_to_proto(slot: QuadSlot) -> Option<pb::PatternSlot> {
599    match slot {
600        QuadSlot::Subject => Some(pb::PatternSlot::Subject),
601        QuadSlot::Predicate => Some(pb::PatternSlot::Predicate),
602        QuadSlot::Object => Some(pb::PatternSlot::Object),
603        // The graph slot is never pushed: a merge-default scan rewrites G
604        // after the matcher runs, so the comparison would see the wrong term.
605        QuadSlot::Graph => None,
606    }
607}
608
609fn compare_op_to_proto(op: CompareOp) -> pb::CompareOp {
610    match op {
611        CompareOp::Eq => pb::CompareOp::Eq,
612        CompareOp::Ne => pb::CompareOp::Ne,
613        CompareOp::Lt => pb::CompareOp::Lt,
614        CompareOp::Le => pb::CompareOp::Le,
615        CompareOp::Gt => pb::CompareOp::Gt,
616        CompareOp::Ge => pb::CompareOp::Ge,
617    }
618}
619
620/// Map a wire pattern slot; `UNSPECIFIED` is `None`.
621pub fn pattern_slot_from_proto(slot: pb::PatternSlot) -> Option<PatternSlot> {
622    match slot {
623        pb::PatternSlot::Unspecified => None,
624        pb::PatternSlot::Subject => Some(PatternSlot::Subject),
625        pb::PatternSlot::Predicate => Some(PatternSlot::Predicate),
626        pb::PatternSlot::Object => Some(PatternSlot::Object),
627    }
628}
629
630/// Encode a pattern slot for the wire.
631pub fn pattern_slot_to_proto(slot: PatternSlot) -> pb::PatternSlot {
632    match slot {
633        PatternSlot::Subject => pb::PatternSlot::Subject,
634        PatternSlot::Predicate => pb::PatternSlot::Predicate,
635        PatternSlot::Object => pb::PatternSlot::Object,
636    }
637}
638
639/// Build an `InsertQuads` request asserting the target `axis`.
640pub fn insert_request(axis: PartitionAxis, versions: &[QuadVersion]) -> pb::InsertQuadsRequest {
641    pb::InsertQuadsRequest {
642        axis: axis_to_proto(axis) as i32,
643        quads: versions.iter().map(quad_version_to_proto).collect(),
644    }
645}
646
647/// Build a `RegisterStrings` request from `(hash, raw)` pairs.
648pub fn register_request<'a>(
649    entries: impl IntoIterator<Item = (StrHash, &'a str)>,
650) -> pb::RegisterStringsRequest {
651    pb::RegisterStringsRequest {
652        entries: entries
653            .into_iter()
654            .map(|(hash, raw)| pb::StringEntry {
655                hash: str_hash_to_bytes(hash),
656                raw: raw.to_owned(),
657            })
658            .collect(),
659    }
660}
661
662/// Build a `ResolveStrings` request.
663pub fn resolve_request(hashes: impl IntoIterator<Item = StrHash>) -> pb::ResolveStringsRequest {
664    pb::ResolveStringsRequest {
665        hashes: hashes.into_iter().map(str_hash_to_bytes).collect(),
666    }
667}
668
669/// Build a `ListNamedGraphs` request (S-axis catalog; includes empty graphs).
670pub fn list_named_graphs_request(snapshot: SnapshotId) -> pb::ListNamedGraphsRequest {
671    pb::ListNamedGraphsRequest {
672        snapshot_id: snapshot.0,
673    }
674}
675
676/// Build an `AddNamedGraph` request (S-axis catalog; NamedNode only).
677pub fn add_named_graph_request(
678    graph: &EncodedTerm,
679    commit_ts: CommitTs,
680) -> pb::AddNamedGraphRequest {
681    pb::AddNamedGraphRequest {
682        graph_name: term_to_bytes(graph),
683        commit_ts: commit_ts.0,
684    }
685}
686
687#[cfg(test)]
688mod tests {
689    use super::*;
690    use pretty_assertions::assert_eq;
691    use waratah_storage::{GraphName, Literal, NamedNode, Quad, encode_quad};
692
693    fn sample() -> EncodedQuad {
694        encode_quad(&Quad::new(
695            NamedNode::new("http://ex/brisbane").unwrap(),
696            NamedNode::new("http://ex/hasWeather").unwrap(),
697            Literal::from("Sunny"),
698            GraphName::DefaultGraph,
699        ))
700        .unwrap()
701    }
702
703    /// Build the wire quad a masked request receives: masked slots carry no
704    /// bytes, unmasked slots carry the term's encoding. This is what the
705    /// partition's `FramePacker` emits; the tests below exercise the client
706    /// reassembly against that shape directly.
707    fn wire_quad_with_mask(quad: &EncodedQuad, omitted: u8) -> pb::EncodedQuad {
708        let slot = |term: &EncodedTerm, omit: u8| -> Vec<u8> {
709            if omit != 0 {
710                Vec::new()
711            } else {
712                term_to_bytes(term)
713            }
714        };
715        pb::EncodedQuad {
716            subject: slot(&quad.subject, omitted & OMIT_SUBJECT).into(),
717            predicate: slot(&quad.predicate, omitted & OMIT_PREDICATE).into(),
718            object: slot(&quad.object, omitted & OMIT_OBJECT).into(),
719            graph_name: slot(&quad.graph_name, omitted & OMIT_GRAPH).into(),
720        }
721    }
722
723    /// A bound slot the request omits comes back as that exact term, so an
724    /// omitted response row is indistinguishable from a full one.
725    #[test]
726    fn omitted_bound_slots_reassemble_to_the_request_terms() {
727        let quad = sample();
728        let pattern = EncodedTriplePattern {
729            subject: Some(quad.subject.clone()),
730            predicate: Some(quad.predicate.clone()),
731            object: None,
732            graph_name: Some(quad.graph_name.clone()),
733        };
734        let omitted = OMIT_SUBJECT | OMIT_PREDICATE | OMIT_GRAPH;
735        let wire = wire_quad_with_mask(&quad, omitted);
736        assert!(wire.subject.is_empty(), "omitted subject carries no bytes");
737        assert!(
738            wire.predicate.is_empty(),
739            "omitted predicate carries no bytes"
740        );
741        assert!(wire.graph_name.is_empty(), "omitted graph carries no bytes");
742        assert_eq!(
743            wire.object.as_ref(),
744            encode_term_bytes(&quad.object).as_slice(),
745            "an unmasked slot keeps its bytes"
746        );
747        let decoded = quad_from_proto_omitting(&wire, &pattern, omitted).unwrap();
748        assert_eq!(decoded, quad, "bound slots reassemble exactly");
749    }
750
751    /// An omitted slot the request does not bind has no consumer, and reads as
752    /// the counted-presence sentinel rather than as the default graph (which is
753    /// what empty bytes would otherwise decode to).
754    #[test]
755    fn omitted_free_slot_reads_as_counted_presence() {
756        let quad = sample();
757        let pattern = EncodedTriplePattern::default();
758        let wire = wire_quad_with_mask(&quad, OMIT_OBJECT);
759        assert!(wire.object.is_empty());
760        let decoded = quad_from_proto_omitting(&wire, &pattern, OMIT_OBJECT).unwrap();
761        assert_eq!(decoded.object, waratah_storage::ENCODED_TERM_TRUE);
762        assert_eq!(decoded.subject, quad.subject);
763        assert_eq!(decoded.predicate, quad.predicate);
764        assert_eq!(decoded.graph_name, quad.graph_name);
765    }
766
767    #[test]
768    fn slot_comparisons_round_trip_and_reject_bad_enums() {
769        let comparisons = vec![
770            SlotComparison {
771                slot: QuadSlot::Object,
772                op: CompareOp::Ge,
773                term: EncodedTerm::from(&Literal::from(1967i64)),
774            },
775            SlotComparison {
776                slot: QuadSlot::Subject,
777                op: CompareOp::Eq,
778                term: EncodedTerm::from(&NamedNode::new("http://ex/s").unwrap()),
779            },
780        ];
781        let wire = slot_comparisons_to_proto(&comparisons).unwrap();
782        assert_eq!(slot_comparisons_from_proto(&wire).unwrap(), comparisons);
783        let request = with_comparisons(
784            scan_request(
785                &EncodedTriplePattern::default(),
786                SnapshotId::default(),
787                0,
788                None,
789            ),
790            &comparisons,
791        )
792        .unwrap();
793        assert_eq!(request.comparisons.len(), 2);
794        assert!(matches!(
795            pb::CompareOp::try_from(request.comparisons[0].op),
796            Ok(pb::CompareOp::Ge)
797        ));
798
799        let mut unspecified = wire[0].clone();
800        unspecified.slot = pb::PatternSlot::Unspecified as i32;
801        assert!(matches!(
802            slot_comparison_from_proto(&unspecified),
803            Err(ProtoError::UnspecifiedEnum("SlotComparison.slot"))
804        ));
805        let mut unknown = wire[0].clone();
806        unknown.op = 99;
807        assert!(matches!(
808            slot_comparison_from_proto(&unknown),
809            Err(ProtoError::UnknownEnum("SlotComparison.op", 99))
810        ));
811        // An empty term would decode as the default graph and silently wipe
812        // the scan; reject it instead.
813        let mut empty_term = wire[0].clone();
814        empty_term.term = Vec::new();
815        assert!(matches!(
816            slot_comparison_from_proto(&empty_term),
817            Err(ProtoError::EmptyTerm("SlotComparison.term"))
818        ));
819
820        // The graph slot cannot be encoded: graph constraints use the
821        // graph-filter fields, not a slot comparison.
822        let graph = SlotComparison {
823            slot: QuadSlot::Graph,
824            op: CompareOp::Eq,
825            term: EncodedTerm::from(&NamedNode::new("http://ex/g").unwrap()),
826        };
827        assert!(matches!(
828            slot_comparison_to_proto(&graph),
829            Err(ProtoError::GraphComparisonSlot)
830        ));
831    }
832
833    /// The mask is the only thing that distinguishes "not sent" from the
834    /// default graph's zero-length encoding, so unknown bits are rejected
835    /// rather than ignored.
836    #[test]
837    fn slot_mask_rejects_bits_outside_the_four_slots() {
838        assert_eq!(slot_mask_from_wire(0).unwrap(), OMIT_NONE);
839        assert_eq!(slot_mask_from_wire(0x0F).unwrap(), 0x0F);
840        assert!(matches!(
841            slot_mask_from_wire(0x10),
842            Err(ProtoError::SlotMask(0x10))
843        ));
844        assert!(matches!(
845            slot_mask_from_wire(0xFFFF_FFFF),
846            Err(ProtoError::SlotMask(_))
847        ));
848    }
849
850    /// With no mask the masked helpers are exactly the plain ones, so a
851    /// request that omits nothing is byte-identical to today's wire form.
852    #[test]
853    fn omit_none_matches_the_plain_encoders() {
854        let quad = sample();
855        let pattern = EncodedTriplePattern {
856            subject: Some(quad.subject.clone()),
857            predicate: Some(quad.predicate.clone()),
858            object: Some(quad.object.clone()),
859            graph_name: Some(quad.graph_name.clone()),
860        };
861        assert_eq!(wire_quad_with_mask(&quad, OMIT_NONE), quad_to_proto(&quad));
862        assert_eq!(
863            quad_from_proto_omitting(&quad_to_proto(&quad), &pattern, OMIT_NONE).unwrap(),
864            quad
865        );
866    }
867
868    #[test]
869    fn quad_round_trips_through_proto() {
870        let quad = sample();
871        assert_eq!(quad_from_proto(&quad_to_proto(&quad)).unwrap(), quad);
872    }
873
874    #[test]
875    fn default_graph_is_zero_bytes() {
876        let wire = quad_to_proto(&sample());
877        assert!(wire.graph_name.is_empty());
878        assert_eq!(
879            term_from_bytes(&wire.graph_name).unwrap(),
880            EncodedTerm::DefaultGraph
881        );
882    }
883
884    #[test]
885    fn pattern_distinguishes_variable_from_default_graph() {
886        let quad = sample();
887        let pattern = EncodedTriplePattern {
888            subject: None,
889            predicate: None,
890            object: Some(quad.object.clone()),
891            graph_name: Some(EncodedTerm::DefaultGraph),
892        };
893        let wire = pattern_to_proto(&pattern);
894        assert_eq!(wire.subject, None);
895        assert_eq!(wire.graph_name.as_deref(), Some(&[][..]));
896        assert_eq!(pattern_from_proto(&wire).unwrap(), pattern);
897    }
898
899    #[test]
900    fn quad_version_round_trips() {
901        let version = QuadVersion {
902            quad: sample(),
903            commit_ts: CommitTs(42),
904            op: StorageOp::Delete,
905            visibility: VisibilityLabel(7),
906        };
907        assert_eq!(
908            quad_version_from_proto(&quad_version_to_proto(&version)).unwrap(),
909            version
910        );
911    }
912
913    #[test]
914    fn missing_quad_field_is_typed_error() {
915        let error = quad_version_from_proto(&pb::QuadVersion::default()).unwrap_err();
916        assert!(matches!(
917            error,
918            ProtoError::MissingField("QuadVersion.quad")
919        ));
920    }
921
922    #[test]
923    fn unspecified_op_is_rejected() {
924        let wire = pb::QuadVersion {
925            quad: Some(quad_to_proto(&sample())),
926            ..Default::default()
927        };
928        assert!(matches!(
929            quad_version_from_proto(&wire).unwrap_err(),
930            ProtoError::UnspecifiedEnum("QuadVersion.op")
931        ));
932    }
933
934    #[test]
935    fn trailing_bytes_after_term_are_rejected() {
936        let mut bytes = term_to_bytes(&sample().subject);
937        bytes.push(0xff);
938        assert!(matches!(
939            term_from_bytes(&bytes).unwrap_err(),
940            ProtoError::TrailingTermBytes(1)
941        ));
942    }
943
944    #[test]
945    fn str_hash_round_trips_and_rejects_short_input() {
946        let hash = StrHash::new("http://ex/hasWeather");
947        assert_eq!(str_hash_from_bytes(&str_hash_to_bytes(hash)).unwrap(), hash);
948        assert!(matches!(
949            str_hash_from_bytes(&[0; 4]).unwrap_err(),
950            ProtoError::StrHashLength(4)
951        ));
952    }
953
954    #[test]
955    fn axis_and_permutation_enums_round_trip() {
956        for axis in PartitionAxis::ALL {
957            assert_eq!(axis_from_proto(axis_to_proto(axis)), Some(axis));
958        }
959        assert_eq!(axis_from_proto(pb::PartitionAxis::Unspecified), None);
960
961        for permutation in IndexPermutation::ALL {
962            assert_eq!(
963                permutation_from_proto(permutation_to_proto(permutation)),
964                Some(permutation)
965            );
966        }
967        assert_eq!(
968            permutation_from_proto(pb::IndexPermutation::Unspecified),
969            None
970        );
971    }
972}