Skip to main content

dash_platform_queries/documents/
composite_document_query.rs

1//! Composite document queries — the client half of "a page plus the
2//! sub-queries derived from it", answered as ONE merged proof.
3//!
4//! Attach sub-queries directly to [`DocumentQuery`] with an explicit
5//! page limit, then fetch the result as [`CompositeDocuments`].
6//! Each [`CompositeSubQuery`] is a by-id join, an indexed lookup, a
7//! grouped count, or an independent sibling, whose `IN` clause the
8//! server derives from the proven page (or an earlier documents
9//! sub-query) — the request never names the derived values, so the
10//! responding node cannot steer them. The verifier bootstraps the page
11//! from the merged proof and re-derives every sub-query with the same
12//! builders, so a substituted, omitted or injected sub-result fails
13//! verification. See `drive::query::composite_document_query`
14//! for the shape rules and the trust model.
15
16use crate::documents::document_query::{
17    order_clause_to_proto, where_clause_to_proto, DocumentQuery,
18};
19use crate::error::Error;
20use dapi_grpc::platform::v0::get_documents_request::get_documents_request_v1::{
21    sub_query, SubQuery as ProtoSubQuery,
22};
23use dapi_grpc::platform::v0::{GetDocumentsResponse, Proof, ResponseMetadata};
24use dapi_grpc::platform::VersionedGrpcResponse;
25use dash_context_provider::ContextProvider;
26use dpp::dashcore::Network;
27use dpp::data_contract::accessors::v0::DataContractV0Getters;
28use dpp::data_contract::DataContract;
29use dpp::version::PlatformVersion;
30use dpp::ProtocolError;
31use drive::config::DEFAULT_QUERY_LIMIT;
32use drive::error::query::QuerySyntaxError;
33use drive::query::{
34    BindingSource, DriveDocumentQuery, DriveSubQuery, OrderClause, SelectProjection,
35    SubQueryBinding, SubQueryKind, WhereClause, MAX_SUB_QUERIES,
36};
37use drive_proof_verifier::{
38    verify_composite_documents_tenderdash_proof, CompositeDocuments, FromProof,
39};
40use std::sync::Arc;
41
42/// Whose proven documents a sub-query's values are read from.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44#[cfg_attr(feature = "mocks", derive(serde::Serialize, serde::Deserialize))]
45pub enum CompositeBindingSource {
46    /// The page.
47    Page,
48    /// An earlier documents sub-query, by its position in
49    /// [`DocumentQuery::sub_queries`].
50    SubQuery(usize),
51}
52
53/// The derived clause of a sub-query: `<field> IN <values>`, where the
54/// values are read off the source's proven documents.
55#[derive(Debug, Clone, PartialEq, Eq)]
56#[cfg_attr(feature = "mocks", derive(serde::Serialize, serde::Deserialize))]
57pub struct CompositeBinding {
58    /// Whose documents supply the values.
59    pub source: CompositeBindingSource,
60    /// The source property read off each document: `$id`, `$ownerId`,
61    /// or an identifier-typed property (dotted paths reach nested
62    /// properties). Documents without it contribute nothing.
63    pub source_property: String,
64    /// The sub-query field receiving the `IN` clause. `$id` makes the
65    /// sub-query a by-id JOIN (the source property must then declare
66    /// `refersTo: permanentDocument`, `refersTo: moderatedDocument` or
67    /// `refersTo: deletableDocument` targeting the sub-query's type; with
68    /// a moderated one a derived id whose document a moderator removed is
69    /// left out of the documents and reported with its proven removal
70    /// record among that sub-result's removals, with a deletable one a
71    /// derived id whose document was deleted since is left out of the
72    /// documents and reported among that sub-result's missing ids);
73    /// otherwise `$ownerId` or an indexed property (a LOOKUP).
74    pub field: String,
75}
76
77/// What a sub-query returns.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79#[cfg_attr(feature = "mocks", derive(serde::Serialize, serde::Deserialize))]
80pub enum CompositeSubQueryKind {
81    /// The matching documents.
82    Documents,
83    /// One count per derived value, read from the countable index
84    /// covering the fixed clauses plus the bound field.
85    Count,
86}
87
88/// One sub-query of a composite request.
89#[derive(Debug, Clone, PartialEq)]
90#[cfg_attr(feature = "mocks", derive(serde::Serialize, serde::Deserialize))]
91pub struct CompositeSubQuery {
92    /// The contract the sub-query targets — the page's, or any other
93    /// (profiles keyed by owner, names keyed by identity).
94    pub data_contract: Arc<DataContract>,
95    /// The document type queried.
96    pub document_type_name: String,
97    /// Documents or counts.
98    pub kind: CompositeSubQueryKind,
99    /// The FIXED clauses — everything but the derived `IN`, which must
100    /// not be named here.
101    pub where_clauses: Vec<WhereClause>,
102    /// Ordering (documents only). Every component of the merged proof
103    /// walks in the page's direction: a bound field missing from here is
104    /// appended in that direction by the node and the verifier alike, and
105    /// an ordering that disagrees with the page's direction is refused
106    /// (turning a limited lookup around would change the rows it returns).
107    pub order_by_clauses: Vec<OrderClause>,
108    /// Required for a documents lookup on a non-unique index: it caps the
109    /// rows the lookup returns in total, in walk order, like an ordinary
110    /// `IN` query's limit. Forbidden for a lookup already bounded by its
111    /// values, a by-id join and a count.
112    pub limit: Option<u32>,
113    /// The derived clause, or `None` for a sibling: an independent
114    /// documents query proven under the same root.
115    pub binding: Option<CompositeBinding>,
116}
117
118impl CompositeSubQuery {
119    fn new(
120        data_contract: Arc<DataContract>,
121        document_type_name: &str,
122        kind: CompositeSubQueryKind,
123    ) -> Result<Self, Error> {
124        data_contract
125            .document_type_for_name(document_type_name)
126            .map_err(|e| Error::Protocol(ProtocolError::DataContractError(e)))?;
127        Ok(Self {
128            data_contract,
129            document_type_name: document_type_name.to_string(),
130            kind,
131            where_clauses: Vec::new(),
132            order_by_clauses: Vec::new(),
133            limit: None,
134            binding: None,
135        })
136    }
137
138    /// A documents sub-query against `document_type_name` of
139    /// `data_contract`. Unbound until [`Self::bound_to`] (a sibling
140    /// otherwise).
141    pub fn documents<C: Into<Arc<DataContract>>>(
142        data_contract: C,
143        document_type_name: &str,
144    ) -> Result<Self, Error> {
145        Self::new(
146            data_contract.into(),
147            document_type_name,
148            CompositeSubQueryKind::Documents,
149        )
150    }
151
152    /// A count sub-query against `document_type_name` of
153    /// `data_contract`. Must be bound.
154    pub fn count<C: Into<Arc<DataContract>>>(
155        data_contract: C,
156        document_type_name: &str,
157    ) -> Result<Self, Error> {
158        Self::new(
159            data_contract.into(),
160            document_type_name,
161            CompositeSubQueryKind::Count,
162        )
163    }
164
165    /// Bind `field` to the `source_property` values of `source`'s
166    /// proven documents.
167    pub fn bound_to(
168        mut self,
169        source: CompositeBindingSource,
170        source_property: impl Into<String>,
171        field: impl Into<String>,
172    ) -> Self {
173        self.binding = Some(CompositeBinding {
174            source,
175            source_property: source_property.into(),
176            field: field.into(),
177        });
178        self
179    }
180
181    /// Bind `field` to the `source_property` values of the page's
182    /// proven documents.
183    pub fn bound_to_page(
184        self,
185        source_property: impl Into<String>,
186        field: impl Into<String>,
187    ) -> Self {
188        self.bound_to(CompositeBindingSource::Page, source_property, field)
189    }
190
191    /// Add a fixed `where` clause.
192    pub fn with_where(mut self, clause: WhereClause) -> Self {
193        self.where_clauses.push(clause);
194        self
195    }
196
197    /// Add an `order_by` clause (documents only).
198    pub fn with_order_by(mut self, clause: OrderClause) -> Self {
199        self.order_by_clauses.push(clause);
200        self
201    }
202
203    /// Set the total row limit of a documents lookup.
204    pub fn with_limit(mut self, limit: u32) -> Self {
205        self.limit = Some(limit);
206        self
207    }
208}
209
210impl From<&DriveSubQuery<'_>> for CompositeSubQuery {
211    fn from(sub: &DriveSubQuery<'_>) -> Self {
212        use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters;
213        Self {
214            data_contract: Arc::new(sub.contract.clone()),
215            document_type_name: sub.document_type.name().to_string(),
216            kind: match sub.kind {
217                SubQueryKind::Documents => CompositeSubQueryKind::Documents,
218                SubQueryKind::Count => CompositeSubQueryKind::Count,
219            },
220            where_clauses: sub.where_clauses.clone(),
221            order_by_clauses: sub.order_by.clone(),
222            limit: sub.limit.map(u32::from),
223            binding: sub.binding.as_ref().map(|binding| CompositeBinding {
224                source: match binding.source {
225                    BindingSource::Page => CompositeBindingSource::Page,
226                    BindingSource::SubQuery(index) => CompositeBindingSource::SubQuery(index),
227                },
228                source_property: binding.source_property.clone(),
229                field: binding.field.clone(),
230            }),
231        }
232    }
233}
234
235impl DocumentQuery {
236    /// Append a sub-query derived from this page or an earlier sub-query.
237    /// Fetch the result as [`CompositeDocuments`].
238    pub fn with_sub_query(mut self, sub_query: CompositeSubQuery) -> Self {
239        self.sub_queries.push(sub_query);
240        self
241    }
242
243    /// Replace the sub-queries. An empty list makes this an ordinary query.
244    pub fn with_sub_queries(mut self, sub_queries: Vec<CompositeSubQuery>) -> Self {
245        self.sub_queries = sub_queries;
246        self
247    }
248
249    /// Check the composite-only shape before encoding or building Drive queries.
250    pub(super) fn check_composite_shape(&self) -> Result<(), Error> {
251        if self.sub_queries.is_empty() || self.sub_queries.len() > MAX_SUB_QUERIES {
252            return Err(Error::Config(format!(
253                "a composite document query requires between 1 and {MAX_SUB_QUERIES} sub-queries"
254            )));
255        }
256        check_page_shape(self)?;
257        for (index, sub) in self.sub_queries.iter().enumerate() {
258            if let Some(limit) = sub.limit {
259                if limit == 0 || limit > u32::from(DEFAULT_QUERY_LIMIT) {
260                    return Err(Error::Drive(drive::error::Error::Query(
261                        QuerySyntaxError::InvalidLimit(format!(
262                            "sub-query {index}: limit must be in [1, {DEFAULT_QUERY_LIMIT}], got {limit}"
263                        )),
264                    )));
265                }
266            }
267            if let Some(CompositeBinding {
268                source: CompositeBindingSource::SubQuery(source),
269                ..
270            }) = &sub.binding
271            {
272                if *source >= index
273                    || self.sub_queries[*source].kind != CompositeSubQueryKind::Documents
274                {
275                    return Err(Error::Config(format!(
276                        "sub-query {index}: a binding must name an earlier documents sub-query"
277                    )));
278                }
279            }
280        }
281        Ok(())
282    }
283}
284
285/// The page-side shape rules shared by the wire encoder and the drive
286/// conversion: an explicit limit, a documents projection, and nothing
287/// the composite surface cannot express.
288fn check_page_shape(page: &DocumentQuery) -> Result<(), Error> {
289    if page.limit == 0 || page.limit > u32::from(DEFAULT_QUERY_LIMIT) {
290        return Err(Error::Config(format!(
291            "a composite document query requires an explicit page limit between 1 and {DEFAULT_QUERY_LIMIT}: it \
292             bounds every derived sub-query clause, so there is no server-default sentinel"
293        )));
294    }
295    if page.select != SelectProjection::documents() {
296        return Err(Error::Config(
297            "a composite page supports the DOCUMENTS projection only".to_string(),
298        ));
299    }
300    if !page.time_range_clauses.is_empty()
301        || !page.integer_range_clauses.is_empty()
302        || page.start.is_some()
303        || page.offset.is_some()
304        || !page.group_by.is_empty()
305        || !page.having.is_empty()
306    {
307        return Err(Error::Config(
308            "a composite page supports where/order_by/limit only: no window \
309             selections, cursors, offsets, group_by, or having (paginate with a range \
310             clause on the page's ordering property)"
311                .to_string(),
312        ));
313    }
314    Ok(())
315}
316
317/// Encode sub-queries after [`DocumentQuery::check_composite_shape`] has
318/// bounded their count, binding indices, and limits.
319pub(super) fn sub_queries_to_proto(
320    sub_queries: Vec<CompositeSubQuery>,
321) -> Result<Vec<ProtoSubQuery>, Error> {
322    sub_queries
323        .into_iter()
324        .map(|sub_query| {
325            let CompositeSubQuery {
326                data_contract,
327                document_type_name,
328                kind,
329                where_clauses,
330                order_by_clauses,
331                limit,
332                binding,
333            } = sub_query;
334            let kind = match kind {
335                CompositeSubQueryKind::Documents => sub_query::Kind::Documents,
336                CompositeSubQueryKind::Count => sub_query::Kind::Count,
337            };
338            Ok(ProtoSubQuery {
339                // Always explicit: the server treats an empty id as
340                // "the page's contract", but naming it costs 32
341                // bytes and removes a shape the verifier would
342                // otherwise have to mirror.
343                data_contract_id: data_contract.id().to_vec(),
344                document_type: document_type_name,
345                where_clauses: where_clauses
346                    .into_iter()
347                    .map(where_clause_to_proto)
348                    .collect::<Result<Vec<_>, _>>()?,
349                order_by: order_by_clauses
350                    .into_iter()
351                    .map(order_clause_to_proto)
352                    .collect(),
353                limit,
354                kind: kind as i32,
355                bind: binding.map(|binding| sub_query::Binding {
356                    source: match binding.source {
357                        CompositeBindingSource::Page => 0,
358                        CompositeBindingSource::SubQuery(index) => index as u32 + 1,
359                    },
360                    source_property: binding.source_property,
361                    field: binding.field,
362                }),
363            })
364        })
365        .collect::<Result<Vec<_>, Error>>()
366}
367
368/// Borrow sub-queries after [`DocumentQuery::check_composite_shape`] has
369/// validated limits before narrowing them to Drive's `u16`.
370pub(super) fn drive_sub_queries<'a>(
371    request: &'a DocumentQuery,
372) -> Result<Vec<DriveSubQuery<'a>>, Error> {
373    request
374        .sub_queries
375        .iter()
376        .map(|sub_query| {
377            let contract: &'a DataContract = &sub_query.data_contract;
378            let document_type = contract
379                .document_type_for_name(&sub_query.document_type_name)
380                .map_err(|e| Error::Protocol(ProtocolError::DataContractError(e)))?;
381            Ok(DriveSubQuery {
382                contract,
383                document_type,
384                kind: match sub_query.kind {
385                    CompositeSubQueryKind::Documents => SubQueryKind::Documents,
386                    CompositeSubQueryKind::Count => SubQueryKind::Count,
387                },
388                where_clauses: sub_query.where_clauses.clone(),
389                order_by: sub_query.order_by_clauses.clone(),
390                limit: sub_query.limit.map(|limit| limit as u16),
391                binding: sub_query.binding.as_ref().map(|binding| SubQueryBinding {
392                    source: match binding.source {
393                        CompositeBindingSource::Page => BindingSource::Page,
394                        CompositeBindingSource::SubQuery(index) => BindingSource::SubQuery(index),
395                    },
396                    source_property: binding.source_property.clone(),
397                    field: binding.field.clone(),
398                }),
399            })
400        })
401        .collect::<Result<Vec<_>, Error>>()
402}
403
404impl FromProof<DocumentQuery> for CompositeDocuments {
405    type Request = DocumentQuery;
406    type Response = GetDocumentsResponse;
407
408    fn maybe_from_proof_with_metadata<'a, I: Into<Self::Request>, O: Into<Self::Response>>(
409        request: I,
410        response: O,
411        _network: Network,
412        platform_version: &PlatformVersion,
413        provider: &'a dyn ContextProvider,
414    ) -> Result<(Option<Self>, ResponseMetadata, Proof), drive_proof_verifier::Error>
415    where
416        Self: 'a,
417    {
418        let request: Self::Request = request.into();
419        request
420            .check_composite_shape()
421            .map_err(|e| drive_proof_verifier::Error::RequestError {
422                error: e.to_string(),
423            })?;
424        let response: Self::Response = response.into();
425
426        let query: DriveDocumentQuery = (&request).try_into().map_err(|e: Error| {
427            drive_proof_verifier::Error::RequestError {
428                error: e.to_string(),
429            }
430        })?;
431
432        // The standard envelope carries the single MERGED proof, and
433        // the proof alone is enough: the verifier bootstraps the page
434        // from it via a subset pass and re-derives the rest.
435        let proof = response
436            .proof()
437            .or(Err(drive_proof_verifier::Error::NoProofInResult))?;
438        let mtd = response
439            .metadata()
440            .or(Err(drive_proof_verifier::Error::EmptyResponseMetadata))?;
441
442        let (_root_hash, composite) = verify_composite_documents_tenderdash_proof(
443            &query,
444            proof,
445            mtd,
446            platform_version,
447            provider,
448        )?;
449
450        // An empty page is a valid, proven "nothing here" — surface it
451        // as Some(empty) rather than None so callers can tell it apart
452        // from a missing object.
453        Ok((Some(composite), mtd.clone(), proof.clone()))
454    }
455}
456
457#[cfg(test)]
458mod tests {
459    //! Offline tests for the composite client surface: the V1
460    //! request-wire encoding, the page-shape rejections, and the
461    //! rich→drive conversion + shared shape validation against the
462    //! yappr-feed fixture. Proof verification is exercised end to end
463    //! in rs-drive's `composite_query_e2e_tests` and rs-drive-abci's
464    //! composite dispatch and trust-boundary tests, where a populated
465    //! Drive exists.
466
467    use super::*;
468    use dapi_grpc::platform::v0::get_documents_request::Version as RequestVersion;
469    use dapi_grpc::platform::v0::GetDocumentsRequest;
470    use dpp::platform_value::Value;
471    use dpp::tests::json_document::json_document_to_contract;
472    use dpp::version::TryFromPlatformVersioned;
473    use drive::query::WhereOperator;
474
475    const FEED_CONTRACT_PATH: &str =
476        "../rs-drive/tests/supporting_files/contract/yappr-feed/yappr-feed-contract.json";
477    const DASHPAY_CONTRACT_PATH: &str =
478        "../rs-drive/tests/supporting_files/contract/dashpay/dashpay-contract.json";
479
480    fn platform_version() -> &'static PlatformVersion {
481        PlatformVersion::latest()
482    }
483
484    fn contract(path: &str) -> Arc<DataContract> {
485        Arc::new(
486            json_document_to_contract(path, false, platform_version())
487                .expect("expected to parse the fixture contract"),
488        )
489    }
490
491    /// The feed card composition: `dash` posts, their like counts, the
492    /// posts they quote, and their authors' dashpay profiles.
493    fn feed_page(limit: u32) -> DocumentQuery {
494        let feed = contract(FEED_CONTRACT_PATH);
495        let dashpay = contract(DASHPAY_CONTRACT_PATH);
496        let page = DocumentQuery::new(feed.clone(), "post")
497            .expect("post doctype exists")
498            .with_where(WhereClause {
499                field: "hashtag".to_string(),
500                operator: WhereOperator::Equal,
501                value: Value::Text("dash".to_string()),
502            })
503            .with_limit(limit);
504        page.with_sub_query(
505            CompositeSubQuery::count(feed.clone(), "like")
506                .expect("like doctype exists")
507                .bound_to_page("$id", "postId"),
508        )
509        .with_sub_query(
510            CompositeSubQuery::documents(feed, "post")
511                .expect("post doctype exists")
512                .bound_to_page("quotedPostId", "$id"),
513        )
514        .with_sub_query(
515            CompositeSubQuery::documents(dashpay, "profile")
516                .expect("profile doctype exists")
517                .bound_to_page("$ownerId", "$ownerId"),
518        )
519    }
520
521    #[test]
522    fn encodes_the_v1_wire_shape() {
523        let query = feed_page(10);
524        let dashpay_id = query.sub_queries[2].data_contract.id().to_vec();
525        let request = GetDocumentsRequest::try_from_platform_versioned(query, platform_version())
526            .expect("encodes");
527        let Some(RequestVersion::V1(v1)) = request.version else {
528            panic!("expected a V1 request");
529        };
530        assert_eq!(v1.document_type, "post");
531        assert_eq!(v1.limit, Some(10));
532        assert!(v1.prove, "composite fetch always proves");
533        assert!(v1.chained.is_none(), "composite and chained are exclusive");
534        assert_eq!(v1.where_clauses.len(), 1);
535        assert_eq!(v1.sub_queries.len(), 3);
536
537        let counts = &v1.sub_queries[0];
538        assert_eq!(counts.document_type, "like");
539        assert_eq!(counts.kind, sub_query::Kind::Count as i32);
540        assert_eq!(counts.limit, None);
541        let bind = counts.bind.as_ref().expect("bound");
542        assert_eq!(bind.source, 0, "the page is source 0");
543        assert_eq!(bind.source_property, "$id");
544        assert_eq!(bind.field, "postId");
545
546        let quoted = &v1.sub_queries[1];
547        assert_eq!(quoted.kind, sub_query::Kind::Documents as i32);
548        assert_eq!(quoted.bind.as_ref().expect("bound").field, "$id");
549
550        let profiles = &v1.sub_queries[2];
551        assert_eq!(profiles.data_contract_id, dashpay_id);
552        assert_eq!(profiles.document_type, "profile");
553    }
554
555    #[test]
556    fn numbers_sub_query_sources_from_one() {
557        let feed = contract(FEED_CONTRACT_PATH);
558        let query = feed_page(10).with_sub_query(
559            CompositeSubQuery::count(feed, "like")
560                .expect("like doctype exists")
561                .bound_to(CompositeBindingSource::SubQuery(1), "$id", "postId"),
562        );
563        let request = GetDocumentsRequest::try_from_platform_versioned(query, platform_version())
564            .expect("encodes");
565        let Some(RequestVersion::V1(v1)) = request.version else {
566            panic!("expected a V1 request");
567        };
568        assert_eq!(
569            v1.sub_queries[3].bind.as_ref().expect("bound").source,
570            2,
571            "sub-query 1 is wire source 2"
572        );
573    }
574
575    #[test]
576    fn should_preserve_the_full_composition_through_drive_conversion() {
577        let feed = contract(FEED_CONTRACT_PATH);
578        let query = feed_page(10).with_sub_query(
579            CompositeSubQuery::documents(feed, "repost")
580                .expect("repost doctype exists")
581                .bound_to(CompositeBindingSource::SubQuery(1), "$id", "postId")
582                .with_where(WhereClause {
583                    field: "hashtag".to_string(),
584                    operator: WhereOperator::Equal,
585                    value: Value::Text("dash".to_string()),
586                })
587                .with_order_by(OrderClause {
588                    field: "postId".to_string(),
589                    ascending: true,
590                })
591                .with_limit(7),
592        );
593        let drive_query: DriveDocumentQuery = (&query).try_into().expect("converts");
594        for restored in [
595            DocumentQuery::try_from(&drive_query),
596            DocumentQuery::try_from(drive_query.clone()),
597            DocumentQuery::new_with_drive_query(&drive_query),
598        ] {
599            assert_eq!(restored.expect("preserves the composition"), query);
600        }
601    }
602
603    #[test]
604    fn should_refuse_a_window_selection_on_a_composite_page_before_sending() {
605        // The node refuses window selections on composite requests; the
606        // local shape check refuses both kinds first, without a round trip.
607        let integer_page = feed_page(10).with_integer_range("likeCount", 100u64);
608        let refused =
609            GetDocumentsRequest::try_from_platform_versioned(integer_page, platform_version());
610        assert!(
611            matches!(&refused, Err(Error::Config(message)) if message.contains("no window")),
612            "{refused:?}"
613        );
614    }
615
616    #[test]
617    fn should_reject_compositions_on_v0_without_affecting_ordinary_queries() {
618        let mut v0 = platform_version().clone();
619        v0.drive_abci.query.document_query.default_current_version = 0;
620        let query = feed_page(10);
621        let refused = GetDocumentsRequest::try_from_platform_versioned(query.clone(), &v0);
622        assert!(matches!(refused, Err(Error::Config(message)) if message.contains("V1")));
623
624        let ordinary = query.with_sub_queries(vec![]);
625        let request = GetDocumentsRequest::try_from_platform_versioned(ordinary.clone(), &v0)
626            .expect("ordinary queries still encode as V0");
627        assert!(matches!(request.version, Some(RequestVersion::V0(_))));
628        let request =
629            GetDocumentsRequest::try_from_platform_versioned(ordinary, platform_version())
630                .expect("ordinary queries still encode as V1");
631        let Some(RequestVersion::V1(v1)) = request.version else {
632            panic!("expected V1");
633        };
634        assert!(v1.sub_queries.is_empty());
635    }
636
637    #[test]
638    fn should_enforce_sub_query_limits_before_encoding_or_conversion() {
639        let query = feed_page(10);
640        let sub = query.sub_queries[0].clone();
641        let maximum = query
642            .clone()
643            .with_sub_queries(vec![sub.clone(); MAX_SUB_QUERIES]);
644        GetDocumentsRequest::try_from_platform_versioned(maximum.clone(), platform_version())
645            .expect("the maximum sub-query count encodes");
646        DriveDocumentQuery::try_from(&maximum).expect("the maximum sub-query count converts");
647
648        let excessive = query.with_sub_queries(vec![sub; MAX_SUB_QUERIES + 1]);
649        assert!(GetDocumentsRequest::try_from_platform_versioned(
650            excessive.clone(),
651            platform_version()
652        )
653        .is_err());
654        assert!(DriveDocumentQuery::try_from(&excessive).is_err());
655
656        for limit in [0, 101, u32::MAX] {
657            let mut query = feed_page(10);
658            query.sub_queries[2].limit = Some(limit);
659            assert!(GetDocumentsRequest::try_from_platform_versioned(
660                query.clone(),
661                platform_version()
662            )
663            .is_err());
664            assert!(DriveDocumentQuery::try_from(&query).is_err());
665        }
666    }
667
668    #[test]
669    fn should_reject_invalid_binding_sources_before_encoding_or_conversion() {
670        // Source 0 is a count, source 2 is the sub-query itself, and a
671        // maximal index must not wrap when mapped to the wire's u32.
672        for source in [0, 2, 3, usize::MAX] {
673            let mut query = feed_page(10);
674            query.sub_queries[2].binding.as_mut().expect("bound").source =
675                CompositeBindingSource::SubQuery(source);
676            assert!(GetDocumentsRequest::try_from_platform_versioned(
677                query.clone(),
678                platform_version()
679            )
680            .is_err());
681            assert!(DriveDocumentQuery::try_from(&query).is_err());
682        }
683    }
684
685    #[cfg(feature = "mocks")]
686    #[test]
687    fn should_preserve_mock_compositions_and_read_older_ordinary_queries() {
688        let query = feed_page(10);
689        let encoded = serde_json::to_value(&query).expect("serializes");
690        let restored: DocumentQuery =
691            serde_json::from_value(encoded.clone()).expect("deserializes");
692        assert_eq!(restored, query);
693
694        let mut legacy = encoded;
695        legacy
696            .as_object_mut()
697            .expect("query object")
698            .remove("sub_queries");
699        let restored: DocumentQuery = serde_json::from_value(legacy).expect("reads older vectors");
700        assert_eq!(restored, query.with_sub_queries(vec![]));
701    }
702
703    #[test]
704    fn should_reject_invalid_page_limits() {
705        for limit in [0, 101, u32::MAX] {
706            let query = feed_page(limit);
707            let refused =
708                GetDocumentsRequest::try_from_platform_versioned(query.clone(), platform_version());
709            assert!(
710                matches!(refused, Err(Error::Config(_))),
711                "an invalid page limit must be refused, got {refused:?}"
712            );
713            assert!(DriveDocumentQuery::try_from(&query).is_err());
714        }
715    }
716
717    #[test]
718    fn refuses_unsupported_page_features() {
719        let mut query = feed_page(10);
720        query.offset = Some(4);
721        let refused = GetDocumentsRequest::try_from_platform_versioned(query, platform_version());
722        assert!(
723            matches!(refused, Err(Error::Config(_))),
724            "a page offset must be refused, got {refused:?}"
725        );
726    }
727
728    #[test]
729    fn converts_to_a_valid_drive_query() {
730        let query = feed_page(10);
731        let drive_query: DriveDocumentQuery =
732            (&query).try_into().expect("converts to a drive query");
733        drive_query
734            .validate_composite(platform_version())
735            .expect("the feed card shape validates");
736        assert_eq!(drive_query.limit, Some(10));
737        assert_eq!(drive_query.sub_queries.len(), 3);
738        assert_eq!(drive_query.sub_queries[0].kind, SubQueryKind::Count);
739        assert_eq!(
740            drive_query.sub_queries[2]
741                .binding
742                .as_ref()
743                .expect("bound")
744                .source,
745            BindingSource::Page
746        );
747    }
748
749    #[test]
750    fn conversion_refuses_an_out_of_range_sub_query_limit() {
751        let feed = contract(FEED_CONTRACT_PATH);
752        let query = feed_page(10).with_sub_query(
753            CompositeSubQuery::documents(feed, "repost")
754                .expect("repost doctype exists")
755                .bound_to_page("$id", "postId")
756                .with_limit(101),
757        );
758        let refused: Result<DriveDocumentQuery, _> = (&query).try_into();
759        assert!(
760            matches!(refused, Err(Error::Drive(_))),
761            "a sub-query limit above the server maximum must be refused, got {refused:?}"
762        );
763    }
764
765    #[test]
766    fn conversion_surfaces_shape_errors() {
767        let feed = contract(FEED_CONTRACT_PATH);
768        let query = feed_page(10).with_sub_query(
769            CompositeSubQuery::documents(feed, "post")
770                .expect("post doctype exists")
771                .bound_to_page("hashtag", "$id"),
772        );
773        let drive_query: DriveDocumentQuery =
774            (&query).try_into().expect("conversion itself succeeds");
775        assert!(
776            drive_query.validate_composite(platform_version()).is_err(),
777            "a by-id join off a non-refersTo property must fail validation"
778        );
779    }
780}