ic_db/store/query/aggregate/jobs/
storage.rs1use super::{JobHandle, JobOutcome, MAX_CANDIDATES};
4use crate::{
5 Error, QueryCursor, Timestamp,
6 codec::{Decoder, Encoder},
7};
8use ic_storage::{Memory, RuntimeMemory, WASM_PAGE_SIZE_BYTES as PAGE_BYTES};
9
10pub(super) const SLOTS: u8 = 16;
11pub(super) const MAX_JOB_BYTES: usize = 16 * 1024;
12const MAGIC: &[u8; 8] = b"ICDBAJ03";
13
14const HEADER_BYTES: usize = 36;
15const DIRECTORY_BYTES: usize = SLOTS as usize * 2;
16const GENERATION_OFFSET: usize = HEADER_BYTES - 8;
17
18fn frame_offset(slot: u8) -> u64 {
21 (HEADER_BYTES + DIRECTORY_BYTES) as u64 + u64::from(slot - 1) * MAX_JOB_BYTES as u64
22}
23
24fn length_offset(slot: u8) -> u64 {
25 HEADER_BYTES as u64 + 2 * u64::from(slot - 1)
26}
27
28pub struct AggregateJobs<M: Memory> {
34 memory: RuntimeMemory<M>,
35 incarnation: [u8; 16],
36}
37impl<M: Memory> AggregateJobs<M> {
38 pub fn create(memory: RuntimeMemory<M>, incarnation: [u8; 16]) -> Result<Self, Error> {
44 if incarnation == [0; 16] {
45 return Err(Error::InvalidJob);
46 }
47 if memory.size() != 0 {
48 return Err(Error::Exists);
49 }
50 memory.grow(1).expect("job allocation growth failed");
51 memory.write(0, &header(incarnation, 0));
52
53 Ok(Self {
54 memory,
55 incarnation,
56 })
57 }
58
59 pub fn open(memory: RuntimeMemory<M>) -> Result<Self, Error> {
63 if memory.size() == 0 {
64 return Err(Error::Corrupt);
65 }
66 let mut bytes = [0; HEADER_BYTES];
67 memory.read(0, &mut bytes);
68 let (incarnation, _) = read_header(&bytes)?;
69 let jobs = Self {
70 memory,
71 incarnation,
72 };
73 jobs.lengths()?;
74 Ok(jobs)
75 }
76
77 fn lengths(&self) -> Result<[u16; SLOTS as usize], Error> {
78 let mut directory = [[0; 2]; SLOTS as usize];
79 self.memory
80 .read(HEADER_BYTES as u64, directory.as_flattened_mut());
81 let lengths = directory.map(u16::from_le_bytes);
82 let pages = self.memory.size();
83 for (index, &len) in lengths.iter().enumerate() {
84 if usize::from(len) > MAX_JOB_BYTES
85 || (len != 0
86 && (frame_offset(index as u8 + 1) + u64::from(len)).div_ceil(PAGE_BYTES)
87 > pages)
88 {
89 return Err(Error::Corrupt);
90 }
91 }
92 Ok(lengths)
93 }
94
95 fn read_frame(&self, slot: u8, len: u16) -> Vec<u8> {
96 let mut bytes = vec![0; usize::from(len)];
97 self.memory.read(frame_offset(slot), &mut bytes);
98 bytes
99 }
100
101 fn write_frame(&self, slot: u8, bytes: &[u8]) {
102 let offset = frame_offset(slot);
103 let pages = (offset + bytes.len() as u64).div_ceil(PAGE_BYTES);
104 let current = self.memory.size();
105 if pages > current {
106 self.memory
107 .grow(pages - current)
108 .expect("job allocation growth failed");
109 }
110 self.memory.write(offset, bytes);
111 self.memory
112 .write(length_offset(slot), &(bytes.len() as u16).to_le_bytes());
113 }
114
115 pub fn cancel(&mut self, handle: &JobHandle) -> Result<(), Error> {
123 self.with_record(handle, |_| ())?;
124 self.memory.write(length_offset(handle.slot), &[0; 2]);
125
126 Ok(())
127 }
128
129 pub fn cleanup_expired(&mut self, now: Timestamp, limit: usize) -> Result<usize, Error> {
137 if !(1..=usize::from(SLOTS)).contains(&limit) {
138 return Err(Error::Limit);
139 }
140 let mut lengths = self.lengths()?;
141 let mut removed = 0;
142 for (index, len) in lengths.iter_mut().enumerate() {
143 if *len != 0 {
144 let bytes = self.read_frame(index as u8 + 1, *len);
145 let record = Record::decode(&bytes)?;
146 if record.expires <= now && removed < limit {
147 *len = 0;
148 removed += 1;
149 }
150 }
151 }
152 if removed > 0 {
153 let directory = lengths.map(u16::to_le_bytes);
154 self.memory
155 .write(HEADER_BYTES as u64, directory.as_flattened());
156 }
157 Ok(removed)
158 }
159
160 pub(super) fn insert(&mut self, mut record: Record) -> Result<JobHandle, Error> {
161 let slot = self
162 .lengths()?
163 .iter()
164 .position(|len| *len == 0)
165 .ok_or(Error::JobCapacity)? as u8
166 + 1;
167 let mut bytes = [0; HEADER_BYTES];
168 self.memory.read(0, &mut bytes);
169 let (incarnation, generation) = read_header(&bytes)?;
170 if incarnation != self.incarnation {
171 return Err(Error::Corrupt);
172 }
173 let generation = generation.checked_add(1).ok_or(Error::Limit)?;
174 record.generation = generation;
175 let bytes = record.encode()?;
176 self.memory
178 .write(GENERATION_OFFSET as u64, &generation.to_le_bytes());
179 self.write_frame(slot, &bytes);
180
181 Ok(JobHandle {
182 incarnation,
183 slot,
184 generation,
185 })
186 }
187
188 pub(super) fn load(&self, handle: &JobHandle) -> Result<Record, Error> {
189 self.with_record(handle, |record| record.into_owned())
190 }
191
192 fn with_record<R>(
195 &self,
196 handle: &JobHandle,
197 inspect: impl FnOnce(Record<&[u8]>) -> R,
198 ) -> Result<R, Error> {
199 if handle.incarnation != self.incarnation {
200 return Err(Error::InvalidJob);
201 }
202 let len = self.lengths()?[usize::from(handle.slot - 1)];
203 if len == 0 {
204 return Err(Error::InvalidJob);
205 }
206 let bytes = self.read_frame(handle.slot, len);
207 let record = Record::decode(&bytes)?;
208 if record.generation != handle.generation {
209 return Err(Error::InvalidJob);
210 }
211
212 Ok(inspect(record))
213 }
214
215 pub(super) fn save_if_changed(
216 &mut self,
217 handle: &JobHandle,
218 record: &Record,
219 changed: bool,
220 ) -> Result<(), Error> {
221 if changed {
222 self.write_frame(handle.slot, &record.encode()?);
223 }
224
225 Ok(())
226 }
227}
228fn header(incarnation: [u8; 16], generation: u64) -> Vec<u8> {
229 let mut bytes = MAGIC.to_vec();
230 bytes.extend(crate::codec::ROW_CODEC_VERSION.to_le_bytes());
231 bytes.extend(incarnation);
232 bytes.extend(generation.to_le_bytes());
233
234 bytes
235}
236
237fn read_header(bytes: &[u8]) -> Result<([u8; 16], u64), Error> {
238 if bytes.len() != HEADER_BYTES {
239 return Err(Error::Corrupt);
240 }
241 if &bytes[..8] != MAGIC || bytes[8..12] != crate::codec::ROW_CODEC_VERSION.to_le_bytes() {
242 return Err(Error::InvalidJob);
243 }
244 let incarnation = bytes[12..28].try_into().map_err(|_| Error::Corrupt)?;
245 if incarnation == [0; 16] {
246 return Err(Error::Corrupt);
247 }
248
249 Ok((
250 incarnation,
251 u64::from_le_bytes(
252 bytes[GENERATION_OFFSET..]
253 .try_into()
254 .map_err(|_| Error::Corrupt)?,
255 ),
256 ))
257}
258
259pub(super) struct Record<Bytes = Vec<u8>> {
262 pub generation: u64,
263 pub binding: [u8; 32],
264 pub revision: u64,
265 pub expires: Timestamp,
266 pub observed: Timestamp,
267 pub sequence: u64,
268 pub examined: u64,
269 pub input_bytes: u64,
270 pub phase: JobOutcome<()>,
271 pub cursor: Bytes,
272 pub count: u64,
273 pub state: Bytes,
275}
276impl Record {
277 fn encode(&self) -> Result<Vec<u8>, Error> {
278 let mut e = Encoder::with_byte_limit(MAX_JOB_BYTES);
279 e.nat64(self.generation)?;
280 e.bytes(&self.binding)?;
281 e.nat64(self.revision)?;
282 e.timestamp(self.expires)?;
283 e.timestamp(self.observed)?;
284 e.nat64(self.sequence)?;
285 e.nat64(self.examined)?;
286 e.nat64(self.input_bytes)?;
287 e.nat8(match self.phase {
288 JobOutcome::Running => 0,
289 JobOutcome::Complete(()) => 1,
290 JobOutcome::Invalidated => 2,
291 JobOutcome::Expired => 3,
292 })?;
293 e.bytes(&self.cursor)?;
294 e.nat64(self.count)?;
295 e.bytes(&self.state)?;
296
297 Ok(e.finish())
298 }
299}
300impl<'a> Record<&'a [u8]> {
301 fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
302 let mut d = Decoder::with_byte_limit(bytes, MAX_JOB_BYTES)?;
303 let record = Self {
304 generation: d.nat64()?,
305 binding: d.blob_ref(32)?.try_into().map_err(|_| Error::Corrupt)?,
306 revision: d.nat64()?,
307 expires: d.timestamp()?,
308 observed: d.timestamp()?,
309 sequence: d.nat64()?,
310 examined: d.nat64()?,
311 input_bytes: d.nat64()?,
312 phase: match d.nat8()? {
313 0 => JobOutcome::Running,
314 1 => JobOutcome::Complete(()),
315 2 => JobOutcome::Invalidated,
316 3 => JobOutcome::Expired,
317 _ => return Err(Error::Corrupt),
318 },
319 cursor: d.blob_ref(QueryCursor::MAX_ENCODED_BYTES)?,
320 count: d.nat64()?,
321 state: d.blob_ref(MAX_JOB_BYTES)?,
322 };
323 d.finish()?;
324 if record.generation == 0
325 || record.examined > MAX_CANDIDATES
326 || record.count > record.examined
327 || record.sequence > record.examined + 2
328 || record.input_bytes
329 > record.examined
330 * super::super::super::candidate_byte_limit(crate::codec::MAX_ROW_BYTES) as u64
331 || (matches!(record.phase, JobOutcome::Complete(())) && !record.cursor.is_empty())
332 || (matches!(record.phase, JobOutcome::Running)
333 && (record.observed >= record.expires
334 || (record.examined > 0 && record.cursor.is_empty())))
335 {
336 return Err(Error::Corrupt);
337 }
338
339 Ok(record)
340 }
341
342 fn into_owned(self) -> Record {
343 Record {
344 generation: self.generation,
345 binding: self.binding,
346 revision: self.revision,
347 expires: self.expires,
348 observed: self.observed,
349 sequence: self.sequence,
350 examined: self.examined,
351 input_bytes: self.input_bytes,
352 phase: self.phase,
353 cursor: self.cursor.to_vec(),
354 count: self.count,
355 state: self.state.to_vec(),
356 }
357 }
358}