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