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