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, 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    /// Encode a fixed 28-byte transport cursor.
29    #[must_use]
30    pub fn to_bytes(&self) -> Vec<u8> {
31        let mut bytes = vec![1];
32        bytes.extend(self.handle.to_bytes());
33        bytes.push(self.position);
34
35        bytes
36    }
37
38    /// Decode bounded framing; resume also checks the live job and result bounds.
39    /// # Errors
40    /// Refuses unsupported versions, malformed handles or positions outside 1..=32.
41    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
42        let [1, handle @ .., position] = bytes else {
43            return Err(Error::InvalidCursor);
44        };
45        if !(1..=MAX_GROUPS as u8).contains(position) {
46            return Err(Error::InvalidCursor);
47        }
48
49        Ok(Self {
50            handle: JobHandle::from_bytes(handle).map_err(|_| Error::InvalidCursor)?,
51            position: *position,
52        })
53    }
54}
55
56#[derive(Clone, Copy)]
57pub(in crate::store::query::aggregate) struct PageRequest<'a> {
58    pub size: usize,
59    pub after: Option<&'a GroupCursor>,
60}
61
62pub(super) fn admit(
63    page: Option<PageRequest<'_>>,
64    handle: &JobHandle,
65    record: &Record,
66) -> Result<(), Error> {
67    if let Some(cursor) = page.and_then(|page| page.after)
68        && (cursor.handle != *handle
69            || !matches!(record.phase, JobOutcome::Complete(()) | JobOutcome::Expired))
70    {
71        return Err(Error::InvalidCursor);
72    }
73
74    Ok(())
75}
76
77pub(super) fn group_page<T>(
78    groups: Groups,
79    limit: usize,
80    bytes: usize,
81    page: Option<PageRequest<'_>>,
82    handle: &JobHandle,
83    decode: fn(&[u8], Completed) -> Result<T, Error>,
84) -> Result<(GroupPage<T>, usize), Error> {
85    // Finalize every group before selection; even an excluded overflow must refuse.
86    let mut rows = groups.into_output()?;
87    rows.truncate(limit);
88    let (range, next, used) = select(&rows, bytes, page, handle)?;
89    let rows = rows
90        .drain(range)
91        .map(|(key, value)| decode(&key, value))
92        .collect::<Result<_, _>>()?;
93
94    Ok((GroupPage { rows, next }, used))
95}
96
97fn select(
98    rows: &[(Vec<u8>, Completed)],
99    bytes: usize,
100    page: Option<PageRequest<'_>>,
101    handle: &JobHandle,
102) -> Result<(std::ops::Range<usize>, Option<GroupCursor>, usize), Error> {
103    let start = page
104        .and_then(|page| page.after)
105        .map_or(0, |cursor| usize::from(cursor.position));
106    if start > rows.len() {
107        return Err(Error::InvalidCursor);
108    }
109    let capacity = page.map_or(rows.len(), |page| page.size);
110    let mut end = start;
111    let mut used = 0;
112    for (key, value) in rows.iter().skip(start).take(capacity) {
113        let size = key.len() + value.encoded_len();
114        if page.is_some() && size > bytes - used {
115            if end == start {
116                return Err(Error::RowTooLarge);
117            }
118            break; // Retry the unreturned group on the next page.
119        }
120        admit_output(size, bytes, &mut used)?;
121        end += 1;
122    }
123    let next = (end < rows.len()).then(|| GroupCursor {
124        handle: handle.clone(),
125        position: end as u8,
126    });
127
128    Ok((start..end, next, used))
129}