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.field.position as u8, term.comparison as u8]);
125
126            match &term.operand {
127                TermOperand::Literal { bytes, value } => {
128                    let mut literal = bytes.as_slice();
129                    if let Some(member) = term.field.member {
130                        hash.update((u32::MAX - 2).to_le_bytes());
131                        hash.update([
132                            member.position() as u8,
133                            u8::from(*value == crate::IndexValue::Absent),
134                        ]);
135                        literal = &literal[usize::from(term.field.optional(entity))..];
136                    }
137                    hash.update((literal.len() as u32).to_le_bytes());
138                    hash.update(literal);
139                }
140                TermOperand::Member {
141                    needle: MemberNeedle::Literal(value),
142                    ..
143                } => {
144                    let bytes = value.component(false);
145                    hash.update((bytes.len() as u32).to_le_bytes());
146                    hash.update(bytes);
147                }
148                TermOperand::Length(threshold) => {
149                    if let Some(member) = term.field.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(right)
158                | TermOperand::Member {
159                    needle: MemberNeedle::Field(right),
160                    ..
161                } => {
162                    if term.field.member.is_none() && right.member.is_none() {
163                        hash.update(u32::MAX.to_le_bytes());
164                        hash.update([right.position as u8]);
165                    } else {
166                        hash.update((u32::MAX - 4).to_le_bytes());
167                        let slot = |field: super::ResolvedField| {
168                            field.member.map_or(u8::MAX, |m| m.position() as u8)
169                        };
170                        hash.update([slot(term.field), right.position as u8, slot(*right)]);
171                    }
172                }
173            }
174        }
175        // The clause mask records which adjacent terms are joined by OR.
176        let clauses = self
177            .terms
178            .iter()
179            .enumerate()
180            .fold(0_u8, |mask, (i, term)| mask | (u8::from(term.or_next) << i));
181        if clauses != 0 {
182            hash.update(b"or-clauses\0");
183            hash.update([clauses]);
184        }
185        if let Some(order) = &request.order {
186            hash.update(b"order\0");
187            hash.update([order.len() as u8]);
188            let mut directions = 0u8;
189            for (
190                i,
191                &super::OrderTerm {
192                    field: name,
193                    direction,
194                },
195            ) in order.iter().enumerate()
196            {
197                if direction == super::SortDirection::Descending {
198                    directions |= 1 << i;
199                }
200                // Field names were admitted by order selection above.
201                if let Some(position) = entity.field_position(name) {
202                    hash.update([position as u8]);
203                } else {
204                    // A top-level position is at most 31. Frame each admitted nested path.
205                    hash.update([u8::MAX, name.len() as u8]);
206                    hash.update(name.as_bytes());
207                }
208            }
209            if directions != 0 {
210                hash.update(b"order-directions\0");
211                hash.update([directions]);
212            }
213        }
214        // Projected shapes bind their field selection and column order.
215        if let Some(mask) = self.projection {
216            hash.update(b"projection\0");
217            hash.update(mask.to_le_bytes());
218            if let Some(Projection::Columns(columns)) = projection {
219                hash.update(b"columns\0");
220                hash.update(columns);
221            }
222        }
223        if request.distinct {
224            hash.update(b"distinct\0");
225        }
226        self.binding = hash.finalize().into();
227        if let Some(cursor) = request.cursor {
228            self.validate_cursor(entity, cursor)
229                .map_err(|_| Error::InvalidCursor)?;
230        }
231
232        Ok(())
233    }
234
235    pub(super) fn validate_cursor(
236        &self,
237        entity: &EntitySchema,
238        cursor: &QueryCursor,
239    ) -> Result<(), Error> {
240        // A mismatched persisted job cursor is corrupt. Caller-supplied cursors
241        // map every validation failure to InvalidCursor at admission.
242        if cursor.binding != self.binding {
243            return Err(Error::Corrupt);
244        }
245        if cursor.resume == Resume::AfterUnemittedClass
246            && !matches!(self.distinct, distinct::Strategy::Adjacent(_))
247        {
248            return Err(Error::InvalidCursor);
249        }
250        let bytes = cursor.position.as_slice();
251        if bytes.len() > crate::MAX_INDEX_KEY_BYTES
252            || !bytes.starts_with(&self.prefix[..self.cursor_prefix_len])
253        {
254            return Err(Error::InvalidCursor);
255        }
256        if let Some(index) = self.index {
257            let mut remaining = bytes
258                .get(INDEX_PREFIX_BYTES..)
259                .ok_or(Error::InvalidCursor)?;
260            for name in index.fields {
261                consume_index_component(entity, index, name, &mut remaining)?;
262            }
263            if !index.unique {
264                key::consume(&mut remaining, entity.key_type()?)?;
265            }
266            if !remaining.is_empty() {
267                return Err(Error::InvalidCursor);
268            }
269        } else {
270            RowKey::decode(
271                bytes
272                    .get(ENTITY_PREFIX_BYTES..)
273                    .ok_or(Error::InvalidCursor)?,
274                entity.key_type()?,
275            )?;
276        }
277
278        Ok(())
279    }
280
281    pub(super) fn cursor(&self, position: &[u8], resume: Resume) -> QueryCursor {
282        QueryCursor {
283            binding: self.binding,
284            position: position.to_vec(),
285            resume,
286        }
287    }
288}