Skip to main content

ic_db/store/query/
cursor.rs

1//! Query continuation frames, binding to an admitted traversal, and position validation.
2
3use super::{
4    ENTITY_PREFIX_BYTES, INDEX_PREFIX_BYTES, MemberNeedle, Plan, Projection, Request, TermOperand,
5    consume_index_component, distinct,
6};
7use crate::{EntitySchema, Error, key, primary::RowKey};
8use sha2::{Digest, Sha256};
9
10/// A bounded logical position, bound to database, schema, query and direction.
11/// It is not an authorization token or a snapshot. Callers may choose positions;
12/// the database revalidates all claims and retains no trusted progress counters.
13/// A new deployment may invalidate a previously issued cursor.
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct QueryCursor {
16    binding: [u8; 32],
17    pub(super) position: Vec<u8>,
18    pub(super) resume: Resume,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub(super) enum Resume {
23    After = 0,
24    Retry = 1,
25    AfterUnemittedClass = 2,
26}
27impl QueryCursor {
28    /// Maximum length of a serialized query cursor, in bytes.
29    pub const MAX_ENCODED_BYTES: usize = 34 + crate::MAX_INDEX_KEY_BYTES;
30
31    /// Encode the bounded continuation for an application's transport.
32    #[must_use]
33    pub fn to_bytes(&self) -> Vec<u8> {
34        let mut bytes = vec![1, self.resume as u8];
35        bytes.extend(self.binding);
36        bytes.extend(&self.position);
37
38        bytes
39    }
40
41    /// Decode framing; execution additionally checks query identity and key shape.
42    /// # Errors
43    /// Refuses unsupported versions, flags and oversized or incomplete frames.
44    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
45        if !(35..=Self::MAX_ENCODED_BYTES).contains(&bytes.len()) || bytes[0] != 1 {
46            return Err(Error::InvalidCursor);
47        }
48
49        Ok(Self {
50            binding: bytes[2..34].try_into().map_err(|_| Error::InvalidCursor)?,
51            position: bytes[34..].to_vec(),
52            resume: match bytes[1] {
53                0 => Resume::After,
54                1 => Resume::Retry,
55                2 => Resume::AfterUnemittedClass,
56                _ => return Err(Error::InvalidCursor),
57            },
58        })
59    }
60}
61
62impl serde::Serialize for QueryCursor {
63    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
64        serializer.serialize_bytes(&self.to_bytes())
65    }
66}
67
68impl<'de> serde::Deserialize<'de> for QueryCursor {
69    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
70        struct Frame;
71
72        impl<'de> serde::de::Visitor<'de> for Frame {
73            type Value = QueryCursor;
74
75            fn expecting(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
76                fmt.write_str("a bounded IC DB query cursor frame")
77            }
78
79            fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<QueryCursor, E> {
80                QueryCursor::from_bytes(bytes).map_err(E::custom)
81            }
82
83            fn visit_seq<A: serde::de::SeqAccess<'de>>(
84                self,
85                mut seq: A,
86            ) -> Result<QueryCursor, A::Error> {
87                let size = seq.size_hint().unwrap_or(0);
88                if size > QueryCursor::MAX_ENCODED_BYTES {
89                    return Err(serde::de::Error::custom(Error::InvalidCursor));
90                }
91                let mut frame = Vec::with_capacity(size);
92                while let Some(byte) = seq.next_element()? {
93                    if frame.len() == QueryCursor::MAX_ENCODED_BYTES {
94                        return Err(serde::de::Error::custom(Error::InvalidCursor));
95                    }
96                    frame.push(byte);
97                }
98                QueryCursor::from_bytes(&frame).map_err(serde::de::Error::custom)
99            }
100        }
101
102        deserializer.deserialize_bytes(Frame)
103    }
104}
105
106impl Plan<'_> {
107    pub(super) fn bind_cursor(
108        &mut self,
109        entity: &EntitySchema,
110        request: &Request<'_>,
111        schema: [u8; 32],
112        incarnation: [u8; 16],
113        projection: Option<Projection<'_>>,
114    ) -> Result<(), Error> {
115        let mut hash = Sha256::new();
116        hash.update(b"ic-db:query:v1\0");
117        hash.update(schema);
118        hash.update(incarnation);
119        hash.update([u8::from(request.descending)]);
120        hash.update((self.prefix.len() as u32).to_le_bytes());
121        hash.update(&self.prefix);
122        for term in &self.terms {
123            hash.update([term.position as u8, term.comparison as u8]);
124
125            match &term.operand {
126                TermOperand::Nested {
127                    member,
128                    literal,
129                    absent,
130                } => {
131                    hash.update((u32::MAX - 2).to_le_bytes());
132                    hash.update([member.position() as u8, u8::from(*absent)]);
133                    // The binding already records absence separately from the scalar payload.
134                    let literal = &literal[usize::from(
135                        entity.fields[term.position].optional || member.field().optional,
136                    )..];
137                    hash.update((literal.len() as u32).to_le_bytes());
138                    hash.update(literal);
139                }
140                TermOperand::Literal { bytes, .. }
141                | TermOperand::Member {
142                    needle: MemberNeedle::Literal(bytes),
143                    ..
144                } => {
145                    hash.update((bytes.len() as u32).to_le_bytes());
146                    hash.update(bytes);
147                }
148                TermOperand::Length { member, threshold } => {
149                    if let Some(member) = member {
150                        hash.update((u32::MAX - 3).to_le_bytes());
151                        hash.update([member.position() as u8]);
152                    } else {
153                        hash.update((u32::MAX - 1).to_le_bytes());
154                    }
155                    hash.update(threshold.to_le_bytes());
156                }
157                TermOperand::Field {
158                    right,
159                    left_member: None,
160                    right_member: None,
161                }
162                | TermOperand::Member {
163                    needle: MemberNeedle::Field(right, None),
164                    ..
165                } => {
166                    // Outside the bounded literal length domain.
167                    hash.update(u32::MAX.to_le_bytes());
168                    hash.update([*right as u8]);
169                }
170                TermOperand::Member {
171                    needle: MemberNeedle::Field(right, Some(member)),
172                    ..
173                } => {
174                    hash.update((u32::MAX - 4).to_le_bytes());
175                    hash.update([u8::MAX, *right as u8, member.position() as u8]);
176                }
177                TermOperand::Field {
178                    right,
179                    left_member,
180                    right_member,
181                } => {
182                    hash.update((u32::MAX - 4).to_le_bytes());
183                    let slot = |member: &Option<crate::member::RecordMember>| {
184                        member.map_or(u8::MAX, |m| m.position() as u8)
185                    };
186                    hash.update([slot(left_member), *right as u8, slot(right_member)]);
187                }
188            }
189        }
190        // The clause mask records which adjacent terms are joined by OR.
191        let clauses = self
192            .terms
193            .iter()
194            .enumerate()
195            .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
196        if clauses != 0 {
197            hash.update(b"or-clauses\0");
198            hash.update([clauses]);
199        }
200        if let Some(order) = &request.order {
201            hash.update(b"order\0");
202            hash.update([order.len() as u8]);
203            for name in order {
204                // Field names were admitted by order selection above.
205                if let Some(position) = entity.field_position(name) {
206                    hash.update([position as u8]);
207                } else {
208                    // A top-level position is at most 31. Frame each admitted nested path.
209                    hash.update([u8::MAX, name.len() as u8]);
210                    hash.update(name.as_bytes());
211                }
212            }
213        }
214        if request.order_descending != 0 {
215            hash.update(b"order-directions\0");
216            hash.update([request.order_descending]);
217        }
218        // Projected shapes bind their field selection and column order.
219        if let Some(mask) = self.projection {
220            hash.update(b"projection\0");
221            hash.update(mask.to_le_bytes());
222            if let Some(Projection::Columns(columns)) = projection {
223                hash.update(b"columns\0");
224                hash.update(columns);
225            }
226        }
227        if request.distinct {
228            hash.update(b"distinct\0");
229        }
230        self.binding = hash.finalize().into();
231        if let Some(cursor) = request.cursor {
232            self.validate_cursor(entity, cursor)
233                .map_err(|_| Error::InvalidCursor)?;
234        }
235
236        Ok(())
237    }
238
239    pub(super) fn validate_cursor(
240        &self,
241        entity: &EntitySchema,
242        cursor: &QueryCursor,
243    ) -> Result<(), Error> {
244        // A mismatched persisted job cursor is corrupt. Caller-supplied cursors
245        // map every validation failure to InvalidCursor at admission.
246        if cursor.binding != self.binding {
247            return Err(Error::Corrupt);
248        }
249        if cursor.resume == Resume::AfterUnemittedClass
250            && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
251        {
252            return Err(Error::InvalidCursor);
253        }
254        let bytes = cursor.position.as_slice();
255        if bytes.len() > crate::MAX_INDEX_KEY_BYTES || !bytes.starts_with(&self.prefix) {
256            return Err(Error::InvalidCursor);
257        }
258        if let Some(index) = self.index {
259            let mut remaining = bytes
260                .get(INDEX_PREFIX_BYTES..)
261                .ok_or(Error::InvalidCursor)?;
262            for name in index.fields {
263                consume_index_component(entity, index, name, &mut remaining)?;
264            }
265            if !index.unique {
266                key::consume(&mut remaining, entity.key_type()?)?;
267            }
268            if !remaining.is_empty() {
269                return Err(Error::InvalidCursor);
270            }
271        } else {
272            RowKey::decode(
273                bytes
274                    .get(ENTITY_PREFIX_BYTES..)
275                    .ok_or(Error::InvalidCursor)?,
276                entity.key_type()?,
277            )?;
278        }
279
280        Ok(())
281    }
282
283    pub(super) fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
284        QueryCursor {
285            binding: self.binding,
286            position: position.to_vec(),
287            resume,
288        }
289    }
290}