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.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.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.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 generation: u64,
243 pub binding: [u8; 32],
244 pub revision: u64,
245 pub expires: Timestamp,
246 pub observed: Timestamp,
247 pub sequence: u64,
248 pub examined: u64,
249 pub input_bytes: u64,
250 pub phase: JobOutcome<()>,
251 pub cursor: Bytes,
252 pub count: u64,
253 pub state: Bytes,
255}
256impl Record {
257 fn encode(&self) -> Result<Vec<u8>, Error> {
258 let mut e = Encoder::with_byte_limit(MAX_JOB_BYTES);
259 e.nat64(self.generation)?;
260 e.bytes(&self.binding)?;
261 e.nat64(self.revision)?;
262 e.timestamp(self.expires)?;
263 e.timestamp(self.observed)?;
264 e.nat64(self.sequence)?;
265 e.nat64(self.examined)?;
266 e.nat64(self.input_bytes)?;
267 e.nat8(match self.phase {
268 JobOutcome::Running => 0,
269 JobOutcome::Complete(()) => 1,
270 JobOutcome::Invalidated => 2,
271 JobOutcome::Expired => 3,
272 })?;
273 e.bytes(&self.cursor)?;
274 e.nat64(self.count)?;
275 e.bytes(&self.state)?;
276
277 Ok(e.finish())
278 }
279}
280impl<'a> Record<&'a [u8]> {
281 fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
282 let mut d = Decoder::with_byte_limit(bytes, MAX_JOB_BYTES)?;
283 let record = Self {
284 generation: d.nat64()?,
285 binding: d.blob_ref(32)?.try_into().map_err(|_| Error::Corrupt)?,
286 revision: d.nat64()?,
287 expires: d.timestamp()?,
288 observed: d.timestamp()?,
289 sequence: d.nat64()?,
290 examined: d.nat64()?,
291 input_bytes: d.nat64()?,
292 phase: match d.nat8()? {
293 0 => JobOutcome::Running,
294 1 => JobOutcome::Complete(()),
295 2 => JobOutcome::Invalidated,
296 3 => JobOutcome::Expired,
297 _ => return Err(Error::Corrupt),
298 },
299 cursor: d.blob_ref(QueryCursor::MAX_ENCODED_BYTES)?,
300 count: d.nat64()?,
301 state: d.blob_ref(MAX_JOB_BYTES)?,
302 };
303 d.finish()?;
304 if record.generation == 0
305 || record.examined > MAX_CANDIDATES
306 || record.count > record.examined
307 || record.sequence > record.examined + 2
308 || record.input_bytes
309 > record.examined
310 * super::super::super::candidate_byte_limit(crate::codec::MAX_ROW_BYTES) as u64
311 || (matches!(record.phase, JobOutcome::Complete(())) && !record.cursor.is_empty())
312 || (matches!(record.phase, JobOutcome::Running)
313 && (record.observed >= record.expires
314 || (record.examined > 0 && record.cursor.is_empty())))
315 {
316 return Err(Error::Corrupt);
317 }
318
319 Ok(record)
320 }
321
322 fn into_owned(self) -> Record {
323 Record {
324 generation: self.generation,
325 binding: self.binding,
326 revision: self.revision,
327 expires: self.expires,
328 observed: self.observed,
329 sequence: self.sequence,
330 examined: self.examined,
331 input_bytes: self.input_bytes,
332 phase: self.phase,
333 cursor: self.cursor.to_vec(),
334 count: self.count,
335 state: self.state.to_vec(),
336 }
337 }
338}