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