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