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 let mut header = [0; HEADER_BYTES];
52 header[..8].copy_from_slice(MAGIC);
53 header[8..12].copy_from_slice(&crate::codec::ROW_CODEC_VERSION.to_le_bytes());
54 header[12..GENERATION_OFFSET].copy_from_slice(&incarnation);
55 memory.write(0, &header);
56
57 Ok(Self {
58 memory,
59 incarnation,
60 })
61 }
62
63 pub fn open(memory: RuntimeMemory<M>) -> Result<Self, Error> {
67 if memory.size() == 0 {
68 return Err(Error::Corrupt);
69 }
70 let mut prefix = [0; GENERATION_OFFSET];
71 memory.read(0, &mut prefix);
72 if &prefix[..8] != MAGIC || prefix[8..12] != crate::codec::ROW_CODEC_VERSION.to_le_bytes() {
73 return Err(Error::InvalidJob);
74 }
75 let mut incarnation = [0; 16];
76 incarnation.copy_from_slice(&prefix[12..]);
77 if incarnation == [0; 16] {
78 return Err(Error::Corrupt);
79 }
80 let jobs = Self {
81 memory,
82 incarnation,
83 };
84 jobs.lengths()?;
85 Ok(jobs)
86 }
87
88 fn lengths(&self) -> Result<[u16; SLOTS as usize], Error> {
89 let mut directory = [[0; 2]; SLOTS as usize];
90 self.memory
91 .read(HEADER_BYTES as u64, directory.as_flattened_mut());
92 let lengths = directory.map(u16::from_le_bytes);
93 let pages = self.memory.size();
94 for (index, &len) in lengths.iter().enumerate() {
95 if usize::from(len) > MAX_JOB_BYTES
96 || (len != 0
97 && (frame_offset(index as u8 + 1) + u64::from(len)).div_ceil(PAGE_BYTES)
98 > pages)
99 {
100 return Err(Error::Corrupt);
101 }
102 }
103 Ok(lengths)
104 }
105
106 fn read_frame(&self, slot: u8, len: u16) -> Vec<u8> {
107 let mut bytes = vec![0; usize::from(len)];
108 self.memory.read(frame_offset(slot), &mut bytes);
109 bytes
110 }
111
112 fn write_frame(&self, slot: u8, bytes: &[u8]) {
113 let offset = frame_offset(slot);
114 let pages = (offset + bytes.len() as u64).div_ceil(PAGE_BYTES);
115 let current = self.memory.size();
116 if pages > current {
117 self.memory
118 .grow(pages - current)
119 .expect("job allocation growth failed");
120 }
121 self.memory.write(offset, bytes);
122 self.memory
123 .write(length_offset(slot), &(bytes.len() as u16).to_le_bytes());
124 }
125
126 pub fn cancel(&mut self, handle: &JobHandle) -> Result<(), Error> {
134 self.with_record(handle, |_| ())?;
135 self.memory.write(length_offset(handle.slot), &[0; 2]);
136
137 Ok(())
138 }
139
140 pub fn cleanup_expired(&mut self, now: Timestamp, limit: usize) -> Result<usize, Error> {
148 if !(1..=usize::from(SLOTS)).contains(&limit) {
149 return Err(Error::Limit);
150 }
151 let mut lengths = self.lengths()?;
152 let mut removed = 0;
153 for (index, len) in lengths.iter_mut().enumerate() {
154 if *len != 0 {
155 let bytes = self.read_frame(index as u8 + 1, *len);
156 let record = Record::decode(&bytes)?;
157 if record.meta.expires <= now && removed < limit {
158 *len = 0;
159 removed += 1;
160 }
161 }
162 }
163 if removed > 0 {
164 let directory = lengths.map(u16::to_le_bytes);
165 self.memory
166 .write(HEADER_BYTES as u64, directory.as_flattened());
167 }
168 Ok(removed)
169 }
170
171 pub(super) fn insert(&mut self, mut record: Record) -> Result<JobHandle, Error> {
172 let slot = self
173 .lengths()?
174 .iter()
175 .position(|len| *len == 0)
176 .ok_or(Error::JobCapacity)? as u8
177 + 1;
178 let mut counter = [0; 8];
180 self.memory.read(GENERATION_OFFSET as u64, &mut counter);
181 let generation = u64::from_le_bytes(counter)
182 .checked_add(1)
183 .ok_or(Error::Limit)?;
184 record.meta.generation = generation;
185 let bytes = record.encode()?;
186 self.memory
188 .write(GENERATION_OFFSET as u64, &generation.to_le_bytes());
189 self.write_frame(slot, &bytes);
190
191 Ok(JobHandle {
192 incarnation: self.incarnation,
193 slot,
194 generation,
195 })
196 }
197
198 pub(super) fn load(&self, handle: &JobHandle) -> Result<Record, Error> {
199 self.with_record(handle, |record| record.into_owned())
200 }
201
202 fn with_record<R>(
205 &self,
206 handle: &JobHandle,
207 inspect: impl FnOnce(Record<&[u8]>) -> R,
208 ) -> Result<R, Error> {
209 if handle.incarnation != self.incarnation {
210 return Err(Error::InvalidJob);
211 }
212 let len = self.lengths()?[usize::from(handle.slot - 1)];
213 if len == 0 {
214 return Err(Error::InvalidJob);
215 }
216 let bytes = self.read_frame(handle.slot, len);
217 let record = Record::decode(&bytes)?;
218 if record.meta.generation != handle.generation {
219 return Err(Error::InvalidJob);
220 }
221
222 Ok(inspect(record))
223 }
224
225 pub(super) fn save_if_changed(
226 &mut self,
227 handle: &JobHandle,
228 record: &Record,
229 changed: bool,
230 ) -> Result<(), Error> {
231 if changed {
232 self.write_frame(handle.slot, &record.encode()?);
233 }
234
235 Ok(())
236 }
237}
238
239pub(super) struct Record<Bytes = Vec<u8>> {
242 pub meta: RecordMeta,
243 pub cursor: Bytes,
244 pub count: u64,
245 pub state: Bytes,
247}
248pub(super) struct RecordMeta {
249 pub generation: u64,
250 pub binding: [u8; 32],
251 pub revision: u64,
252 pub expires: Timestamp,
253 pub observed: Timestamp,
254 pub sequence: u64,
255 pub examined: u64,
256 pub input_bytes: u64,
257 pub phase: JobOutcome<()>,
258}
259
260impl Record {
261 fn encode(&self) -> Result<Vec<u8>, Error> {
262 let mut e = Encoder::with_byte_limit(MAX_JOB_BYTES);
263 e.nat64(self.meta.generation)?;
264 e.bytes(&self.meta.binding)?;
265 e.nat64(self.meta.revision)?;
266 e.timestamp(self.meta.expires)?;
267 e.timestamp(self.meta.observed)?;
268 e.nat64(self.meta.sequence)?;
269 e.nat64(self.meta.examined)?;
270 e.nat64(self.meta.input_bytes)?;
271 e.nat8(match self.meta.phase {
272 JobOutcome::Running => 0,
273 JobOutcome::Complete(()) => 1,
274 JobOutcome::Invalidated => 2,
275 JobOutcome::Expired => 3,
276 })?;
277 e.bytes(&self.cursor)?;
278 e.nat64(self.count)?;
279 e.bytes(&self.state)?;
280
281 Ok(e.finish())
282 }
283}
284impl<'a> Record<&'a [u8]> {
285 fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
286 let mut d = Decoder::with_byte_limit(bytes, MAX_JOB_BYTES)?;
287 let record = Self {
288 meta: RecordMeta {
289 generation: d.nat64()?,
290 binding: d.blob_ref(32)?.try_into().map_err(|_| Error::Corrupt)?,
291 revision: d.nat64()?,
292 expires: d.timestamp()?,
293 observed: d.timestamp()?,
294 sequence: d.nat64()?,
295 examined: d.nat64()?,
296 input_bytes: d.nat64()?,
297 phase: match d.nat8()? {
298 0 => JobOutcome::Running,
299 1 => JobOutcome::Complete(()),
300 2 => JobOutcome::Invalidated,
301 3 => JobOutcome::Expired,
302 _ => return Err(Error::Corrupt),
303 },
304 },
305 cursor: d.blob_ref(QueryCursor::MAX_ENCODED_BYTES)?,
306 count: d.nat64()?,
307 state: d.blob_ref(MAX_JOB_BYTES)?,
308 };
309 d.finish()?;
310 if record.meta.generation == 0
311 || record.meta.examined > MAX_CANDIDATES
312 || record.count > record.meta.examined
313 || record.meta.sequence > record.meta.examined + 2
314 || record.meta.input_bytes
315 > record.meta.examined
316 * super::super::super::candidate_byte_limit(crate::codec::MAX_ROW_BYTES) as u64
317 || (matches!(record.meta.phase, JobOutcome::Complete(())) && !record.cursor.is_empty())
318 || (matches!(record.meta.phase, JobOutcome::Running)
319 && (record.meta.observed >= record.meta.expires
320 || (record.meta.examined > 0 && record.cursor.is_empty())))
321 {
322 return Err(Error::Corrupt);
323 }
324
325 Ok(record)
326 }
327
328 fn into_owned(self) -> Record {
329 Record {
330 meta: self.meta,
331 cursor: self.cursor.to_vec(),
332 count: self.count,
333 state: self.state.to_vec(),
334 }
335 }
336}