Skip to main content

ic_db/store/query/aggregate/jobs/
pages.rs

1//! Bounded pages over immutable completed groups; no additional durable state.
2
3use super::{
4    super::{Completed, GroupOrder, Groups, MAX_GROUPS, Reducer, admit_output},
5    JobHandle, JobOutcome,
6    storage::Record,
7};
8use crate::Error;
9
10/// One page of completed retained groups. Keep `next` when mapping `rows`.
11#[derive(Debug)]
12pub struct GroupPage<T> {
13    /// Completed groups in the bound query's selected total order.
14    pub rows: Vec<T>,
15    /// None marks the end of the selected result, including the query's total limit.
16    pub next: Option<GroupCursor>,
17}
18
19/// Logical position in one completed retained job, not an authorization token.
20/// Positions are revalidated against the selected result; caller edits can skip
21/// rows intentionally but cannot change the result or advance input progress.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub struct GroupCursor {
24    handle: JobHandle,
25    position: u8,
26}
27impl GroupCursor {
28    fn version(position: u8) -> u8 {
29        if usize::from(position) > MAX_GROUPS {
30            2
31        } else {
32            1
33        }
34    }
35
36    /// Encode a fixed 28-byte transport cursor.
37    #[must_use]
38    pub fn to_bytes(&self) -> Vec<u8> {
39        let mut bytes = vec![Self::version(self.position)];
40        bytes.extend(self.handle.to_bytes());
41        bytes.push(self.position);
42
43        bytes
44    }
45
46    /// Decode bounded framing; resume also checks the live job and result bounds.
47    /// # Errors
48    /// Refuses unsupported versions, malformed handles or zero positions. Resume checks the position against the completed result.
49    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
50        let [version, handle @ .., position] = bytes else {
51            return Err(Error::InvalidCursor);
52        };
53        if *position == 0 || *version != Self::version(*position) {
54            return Err(Error::InvalidCursor);
55        }
56
57        Ok(Self {
58            handle: JobHandle::from_bytes(handle).map_err(|_| Error::InvalidCursor)?,
59            position: *position,
60        })
61    }
62}
63
64#[derive(Clone, Copy)]
65pub(in crate::store::query::aggregate) struct PageRequest<'a> {
66    pub size: usize,
67    pub after: Option<&'a GroupCursor>,
68}
69
70pub(super) fn admit(
71    page: Option<PageRequest<'_>>,
72    handle: &JobHandle,
73    record: &Record,
74) -> Result<(), Error> {
75    if let Some(cursor) = page.and_then(|page| page.after)
76        && (cursor.handle != *handle
77            || !matches!(record.phase, JobOutcome::Complete(()) | JobOutcome::Expired))
78    {
79        return Err(Error::InvalidCursor);
80    }
81
82    Ok(())
83}
84
85pub(super) fn group_page<T>(
86    groups: Groups,
87    limit: usize,
88    bytes: usize,
89    page: Option<PageRequest<'_>>,
90    handle: &JobHandle,
91    decode: fn(&[u8], Completed) -> Result<T, Error>,
92) -> Result<(GroupPage<T>, usize), Error> {
93    if groups.selection.order == GroupOrder::FirstOccurrence {
94        let keys = groups.first_occurrences()?;
95        let (selected, used) = select(keys.into_iter(), |key| key.len(), bytes, page, handle)?;
96        let rows = selected
97            .rows
98            .into_iter()
99            .map(|key| decode(key, Completed::Key))
100            .collect::<Result<_, _>>()?;
101        return Ok((
102            GroupPage {
103                rows,
104                next: selected.next,
105            },
106            used,
107        ));
108    }
109    let (page, used) = select_rows(groups, limit, bytes, page, handle)?;
110    let rows = page
111        .rows
112        .into_iter()
113        .map(|(key, value)| decode(&key, value))
114        .collect::<Result<_, _>>()?;
115
116    Ok((
117        GroupPage {
118            rows,
119            next: page.next,
120        },
121        used,
122    ))
123}
124
125type EncodedPage = GroupPage<(Vec<u8>, Completed)>;
126
127// Keep traversal and ownership of the result buffers outside the typed conversion.
128#[inline(never)]
129fn select_rows(
130    groups: Groups,
131    limit: usize,
132    bytes: usize,
133    page: Option<PageRequest<'_>>,
134    handle: &JobHandle,
135) -> Result<(EncodedPage, usize), Error> {
136    if matches!(groups.initial, Reducer::Keys(_)) {
137        let mut keys = groups
138            .rows
139            .into_values()
140            .map(|(key, _)| (key, Completed::Key));
141        let mut reversed;
142        let ordered: &mut dyn ExactSizeIterator<Item = _> =
143            if groups.selection.order == GroupOrder::KeyDescending {
144                reversed = keys.rev();
145                &mut reversed
146            } else {
147                &mut keys
148            };
149
150        return select(ordered, |(key, _)| key.len(), bytes, page, handle);
151    }
152    // Finalize every group before selection; even an excluded overflow must refuse.
153    let rows = groups.into_output(limit)?;
154    select(
155        rows.into_iter(),
156        |(key, value)| key.len() + value.encoded_len(),
157        bytes,
158        page,
159        handle,
160    )
161}
162
163fn select<T>(
164    rows: impl ExactSizeIterator<Item = T>,
165    size: impl Fn(&T) -> usize,
166    bytes: usize,
167    page: Option<PageRequest<'_>>,
168    handle: &JobHandle,
169) -> Result<(GroupPage<T>, usize), Error> {
170    let start = page
171        .and_then(|page| page.after)
172        .map_or(0, |cursor| usize::from(cursor.position));
173    let total = rows.len();
174    if start > total {
175        return Err(Error::InvalidCursor);
176    }
177    let capacity = page.map_or(total, |page| page.size);
178    let mut selected = Vec::with_capacity(capacity.min(total - start));
179    let mut used = 0;
180    for row in rows.skip(start).take(capacity) {
181        match admit_output(size(&row), bytes, &mut used) {
182            Ok(()) => selected.push(row),
183            // The cursor stays before the uncharged row so the next page retries it.
184            Err(Error::Limit | Error::RowTooLarge) if page.is_some() && !selected.is_empty() => {
185                break;
186            }
187            Err(error) => return Err(error),
188        }
189    }
190    let end = start + selected.len();
191    let next = (end < total).then(|| GroupCursor {
192        handle: handle.clone(),
193        position: end as u8,
194    });
195
196    Ok((
197        GroupPage {
198            rows: selected,
199            next,
200        },
201        used,
202    ))
203}