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, adapter::StableBTreeMap};
9
10pub(super) const SLOTS: u8 = 16;
11pub(super) const MAX_JOB_BYTES: usize = 16 * 1024;
12const LEGACY_MAX_JOB_BYTES: usize = 4096;
13const MAGIC: &[u8; 8] = b"ICDBAJ02";
14const LEGACY_MAGIC: &[u8; 8] = b"ICDBAJ01";
15
16pub struct AggregateJobs<M: Memory> {
22 map: StableBTreeMap<u8, Vec<u8>, M>,
23 incarnation: [u8; 16],
24 legacy: bool,
25}
26impl<M: Memory> AggregateJobs<M> {
27 pub fn create(memory: RuntimeMemory<M>, incarnation: [u8; 16]) -> Result<Self, Error> {
33 if incarnation == [0; 16] {
34 return Err(Error::InvalidJob);
35 }
36 if memory.size() != 0 {
37 return Err(Error::Exists);
38 }
39 let mut map = StableBTreeMap::create(memory);
40 map.insert(0, header(incarnation, 0));
41
42 Ok(Self {
43 map,
44 incarnation,
45 legacy: false,
46 })
47 }
48
49 pub fn open(memory: RuntimeMemory<M>) -> Result<Self, Error> {
57 if memory.size() == 0 {
58 return Err(Error::Corrupt);
59 }
60 let map: StableBTreeMap<u8, Vec<u8>, M> = StableBTreeMap::load(memory);
61 let bytes = map.get(&0).ok_or(Error::Corrupt)?;
62 let (incarnation, _, legacy) = read_header(&bytes)?;
63 if map.len() > u64::from(SLOTS) + 1
64 || map
65 .range(..)
66 .next_back()
67 .is_some_and(|entry| *entry.key() > SLOTS)
68 {
69 return Err(Error::Corrupt);
70 }
71
72 Ok(Self {
73 map,
74 incarnation,
75 legacy,
76 })
77 }
78
79 pub fn cancel(&mut self, handle: &JobHandle) -> Result<(), Error> {
87 self.with_record(handle, |_| ())?;
88 self.map.remove(&handle.slot);
89
90 Ok(())
91 }
92
93 pub fn cleanup_expired(&mut self, now: Timestamp, limit: usize) -> Result<usize, Error> {
101 if !(1..=usize::from(SLOTS)).contains(&limit) {
102 return Err(Error::Limit);
103 }
104 let mut expired = Vec::new();
105 for slot in 1..=SLOTS {
106 if let Some(bytes) = self.map.get(&slot) {
107 let record = self.decode(&bytes)?;
108 if record.expires <= now && expired.len() < limit {
109 expired.push(slot);
110 }
111 }
112 }
113 for slot in &expired {
114 self.map.remove(slot);
115 }
116
117 Ok(expired.len())
118 }
119
120 pub(super) fn insert(&mut self, mut record: Record) -> Result<JobHandle, Error> {
121 let slot = (1..=SLOTS)
122 .find(|slot| !self.map.contains_key(slot))
123 .ok_or(Error::JobCapacity)?;
124 let (incarnation, generation, _) = read_header(&self.map.get(&0).ok_or(Error::Corrupt)?)?;
125 if incarnation != self.incarnation {
126 return Err(Error::Corrupt);
127 }
128 let generation = generation.checked_add(1).ok_or(Error::Limit)?;
129 record.generation = generation;
130 let bytes = record.encode()?;
131 self.map.insert(0, header(incarnation, generation));
133 self.map.insert(slot, bytes);
134 self.legacy = false;
135
136 Ok(JobHandle {
137 incarnation,
138 slot,
139 generation,
140 })
141 }
142
143 pub(super) fn load(&self, handle: &JobHandle) -> Result<Record, Error> {
144 self.with_record(handle, |record| record.into_owned())
145 }
146
147 fn with_record<R>(
150 &self,
151 handle: &JobHandle,
152 inspect: impl FnOnce(Record<&[u8]>) -> R,
153 ) -> Result<R, Error> {
154 if handle.incarnation != self.incarnation {
155 return Err(Error::InvalidJob);
156 }
157 let bytes = self.map.get(&handle.slot).ok_or(Error::InvalidJob)?;
158 let record = self.decode(&bytes)?;
159 if record.generation != handle.generation {
160 return Err(Error::InvalidJob);
161 }
162
163 Ok(inspect(record))
164 }
165
166 pub(super) fn save_if_changed(
167 &mut self,
168 handle: &JobHandle,
169 record: &Record,
170 changed: bool,
171 ) -> Result<(), Error> {
172 if !changed && !self.legacy {
173 return Ok(());
174 }
175
176 let bytes = record.encode()?;
177 if self.legacy {
180 let (incarnation, generation, _) =
181 read_header(&self.map.get(&0).ok_or(Error::Corrupt)?)?;
182 self.map.insert(0, header(incarnation, generation));
183 }
184 self.map.insert(handle.slot, bytes);
185 self.legacy = false;
186
187 Ok(())
188 }
189
190 fn decode<'a>(&self, bytes: &'a [u8]) -> Result<Record<&'a [u8]>, Error> {
191 if self.legacy && bytes.len() > LEGACY_MAX_JOB_BYTES {
192 return Err(Error::Corrupt);
193 }
194
195 Record::decode(bytes)
196 }
197}
198fn header(incarnation: [u8; 16], generation: u64) -> Vec<u8> {
199 let mut bytes = MAGIC.to_vec();
200 bytes.extend(crate::codec::ROW_CODEC_VERSION.to_le_bytes());
201 bytes.extend(incarnation);
202 bytes.extend(generation.to_le_bytes());
203
204 bytes
205}
206
207fn read_header(bytes: &[u8]) -> Result<([u8; 16], u64, bool), Error> {
208 if bytes.len() != 36 {
209 return Err(Error::Corrupt);
210 }
211 if (&bytes[..8] != MAGIC && &bytes[..8] != LEGACY_MAGIC)
212 || bytes[8..12] != crate::codec::ROW_CODEC_VERSION.to_le_bytes()
213 {
214 return Err(Error::InvalidJob);
215 }
216 let incarnation = bytes[12..28].try_into().map_err(|_| Error::Corrupt)?;
217 if incarnation == [0; 16] {
218 return Err(Error::Corrupt);
219 }
220
221 Ok((
222 incarnation,
223 u64::from_le_bytes(bytes[28..].try_into().map_err(|_| Error::Corrupt)?),
224 &bytes[..8] == LEGACY_MAGIC,
225 ))
226}
227
228pub(super) struct Record<Bytes = Vec<u8>> {
231 pub generation: u64,
232 pub binding: [u8; 32],
233 pub revision: u64,
234 pub expires: Timestamp,
235 pub observed: Timestamp,
236 pub sequence: u64,
237 pub examined: u64,
238 pub input_bytes: u64,
239 pub phase: JobOutcome<()>,
240 pub cursor: Bytes,
241 pub count: u64,
242 pub state: Bytes,
244}
245impl Record {
246 fn encode(&self) -> Result<Vec<u8>, Error> {
247 let mut e = Encoder::with_byte_limit(MAX_JOB_BYTES);
248 e.nat64(self.generation)?;
249 e.bytes(&self.binding)?;
250 e.nat64(self.revision)?;
251 e.timestamp(self.expires)?;
252 e.timestamp(self.observed)?;
253 e.nat64(self.sequence)?;
254 e.nat64(self.examined)?;
255 e.nat64(self.input_bytes)?;
256 e.nat8(match self.phase {
257 JobOutcome::Running => 0,
258 JobOutcome::Complete(()) => 1,
259 JobOutcome::Invalidated => 2,
260 JobOutcome::Expired => 3,
261 })?;
262 e.bytes(&self.cursor)?;
263 e.nat64(self.count)?;
264 e.bytes(&self.state)?;
265
266 Ok(e.finish())
267 }
268}
269impl<'a> Record<&'a [u8]> {
270 fn decode(bytes: &'a [u8]) -> Result<Self, Error> {
271 let mut d = Decoder::with_byte_limit(bytes, MAX_JOB_BYTES)?;
272 let record = Self {
273 generation: d.nat64()?,
274 binding: d.blob_ref(32)?.try_into().map_err(|_| Error::Corrupt)?,
275 revision: d.nat64()?,
276 expires: d.timestamp()?,
277 observed: d.timestamp()?,
278 sequence: d.nat64()?,
279 examined: d.nat64()?,
280 input_bytes: d.nat64()?,
281 phase: match d.nat8()? {
282 0 => JobOutcome::Running,
283 1 => JobOutcome::Complete(()),
284 2 => JobOutcome::Invalidated,
285 3 => JobOutcome::Expired,
286 _ => return Err(Error::Corrupt),
287 },
288 cursor: d.blob_ref(QueryCursor::MAX_ENCODED_BYTES)?,
289 count: d.nat64()?,
290 state: d.blob_ref(MAX_JOB_BYTES)?,
291 };
292 d.finish()?;
293 if record.generation == 0
294 || record.examined > MAX_CANDIDATES
295 || record.count > record.examined
296 || record.sequence > record.examined + 2
297 || record.input_bytes > record.examined * super::super::super::CANDIDATE_BYTES as u64
298 || (matches!(record.phase, JobOutcome::Complete(())) && !record.cursor.is_empty())
299 || (matches!(record.phase, JobOutcome::Running)
300 && (record.observed >= record.expires
301 || (record.examined > 0 && record.cursor.is_empty())))
302 {
303 return Err(Error::Corrupt);
304 }
305
306 Ok(record)
307 }
308
309 fn into_owned(self) -> Record {
310 Record {
311 generation: self.generation,
312 binding: self.binding,
313 revision: self.revision,
314 expires: self.expires,
315 observed: self.observed,
316 sequence: self.sequence,
317 examined: self.examined,
318 input_bytes: self.input_bytes,
319 phase: self.phase,
320 cursor: self.cursor.to_vec(),
321 count: self.count,
322 state: self.state.to_vec(),
323 }
324 }
325}