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 (range, next, used) = select(keys.iter().map(|key| key.len()), bytes, page, handle)?;
96        let rows = keys[range]
97            .iter()
98            .map(|key| decode(key, Completed::Key))
99            .collect::<Result<_, _>>()?;
100        return Ok((GroupPage { rows, next }, used));
101    }
102    let (page, used) = select_rows(groups, limit, bytes, page, handle)?;
103    let rows = page
104        .rows
105        .into_iter()
106        .map(|(key, value)| decode(&key, value))
107        .collect::<Result<_, _>>()?;
108
109    Ok((
110        GroupPage {
111            rows,
112            next: page.next,
113        },
114        used,
115    ))
116}
117
118type EncodedPage = GroupPage<(Vec<u8>, Completed)>;
119
120// Keep traversal and ownership of the result buffers outside the typed conversion.
121#[inline(never)]
122fn select_rows(
123    groups: Groups,
124    limit: usize,
125    bytes: usize,
126    page: Option<PageRequest<'_>>,
127    handle: &JobHandle,
128) -> Result<(EncodedPage, usize), Error> {
129    if matches!(groups.initial, Reducer::Keys(_)) {
130        // Charge in output order, then move just the selected records out of the map.
131        let sizes = groups.rows.values().map(|(key, _)| key.len());
132        let descending = groups.selection.order == GroupOrder::KeyDescending;
133        let (range, next, used) = if descending {
134            select(sizes.rev(), bytes, page, handle)?
135        } else {
136            select(sizes, bytes, page, handle)?
137        };
138        let mut keys = groups.rows.into_values();
139        let rows: &mut dyn Iterator<Item = _> = if descending {
140            &mut keys.by_ref().rev()
141        } else {
142            &mut keys
143        };
144        let rows = rows
145            .skip(range.start)
146            .take(range.len())
147            .map(|(key, _)| (key, Completed::Key))
148            .collect();
149
150        return Ok((GroupPage { rows, next }, used));
151    }
152    // Finalize every group before selection; even an excluded overflow must refuse.
153    let mut rows = groups.into_output()?;
154    rows.truncate(limit);
155    let sizes = rows
156        .iter()
157        .map(|(key, value)| key.len() + value.encoded_len());
158    let (range, next, used) = select(sizes, bytes, page, handle)?;
159    rows.truncate(range.end);
160    rows.drain(..range.start);
161
162    Ok((GroupPage { rows, next }, used))
163}
164
165fn select(
166    sizes: impl ExactSizeIterator<Item = usize>,
167    bytes: usize,
168    page: Option<PageRequest<'_>>,
169    handle: &JobHandle,
170) -> Result<(std::ops::Range<usize>, Option<GroupCursor>, usize), Error> {
171    let start = page
172        .and_then(|page| page.after)
173        .map_or(0, |cursor| usize::from(cursor.position));
174    let total = sizes.len();
175    if start > total {
176        return Err(Error::InvalidCursor);
177    }
178    let capacity = page.map_or(total, |page| page.size);
179    let mut end = start;
180    let mut used = 0;
181    for size in sizes.skip(start).take(capacity) {
182        if page.is_some() && size > bytes - used {
183            if end == start {
184                return Err(Error::RowTooLarge);
185            }
186            break; // Retry the unreturned group on the next page.
187        }
188        admit_output(size, bytes, &mut used)?;
189        end += 1;
190    }
191    let next = (end < total).then(|| GroupCursor {
192        handle: handle.clone(),
193        position: end as u8,
194    });
195
196    Ok((start..end, next, used))
197}