ic_db/store/maintenance/
mod.rs1mod copy;
4
5use super::{Database, Map, live_manifest, manifest_key, query, read_revision};
6use crate::{
7 Entity, Error, QueryCursor, QueryPage, Schema,
8 codec::{Decoder, Encoder},
9};
10pub use copy::{CopyStatus, CopyStep, RetiredSource, SchemaCopy};
11use ic_storage::{Memory, RuntimeMemory};
12use sha2::{Digest, Sha256};
13
14pub(super) const MAGIC: &[u8; 8] = b"ICDBMT02";
15const MAX_NAME: usize = 64;
16const MAX_INPUTS: usize = 256;
17const MAX_FRAME: usize = 421;
18
19pub(super) fn admits_gate(bytes: &[u8]) -> Result<bool, Error> {
20 if bytes.starts_with(MAGIC) {
21 decode(bytes)?;
22 } else if bytes.starts_with(copy::MAGIC) {
23 copy::decode(bytes)?;
24 } else {
25 return Ok(false);
26 }
27
28 Ok(true)
29}
30
31#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct SchemaTransition {
36 source: [u8; 32],
37 target: [u8; 32],
38 name: String,
39 version: u32,
40 inputs: Vec<u8>,
41}
42
43impl SchemaTransition {
44 pub fn new(
49 source: &Schema,
50 target: &Schema,
51 name: &str,
52 version: u32,
53 inputs: &[u8],
54 ) -> Result<Self, Error> {
55 if source.fingerprint() == target.fingerprint()
56 || name.is_empty()
57 || name.len() > MAX_NAME
58 || version == 0
59 || inputs.len() > MAX_INPUTS
60 {
61 return Err(Error::InvalidTransition);
62 }
63
64 Ok(Self {
65 source: source.fingerprint(),
66 target: target.fingerprint(),
67 name: name.into(),
68 version,
69 inputs: inputs.into(),
70 })
71 }
72
73 #[must_use]
75 pub const fn source(&self) -> [u8; 32] {
76 self.source
77 }
78
79 #[must_use]
81 pub const fn target(&self) -> [u8; 32] {
82 self.target
83 }
84
85 #[must_use]
87 pub fn name(&self) -> &str {
88 &self.name
89 }
90
91 #[must_use]
93 pub const fn version(&self) -> u32 {
94 self.version
95 }
96
97 #[must_use]
99 pub fn inputs(&self) -> &[u8] {
100 &self.inputs
101 }
102
103 fn freeze(&self, incarnation: [u8; 16]) -> Result<Vec<u8>, Error> {
104 let mut payload = Encoder::new();
105 payload.nat8(0)?; payload.nat32(self.version)?;
107 payload.bytes(self.name.as_bytes())?;
108 payload.bytes(&self.inputs)?;
109 let mut bytes = MAGIC.to_vec();
110 bytes.extend(self.source);
111 bytes.extend(self.target);
112 bytes.extend(incarnation);
113 bytes.extend(payload.finish());
114
115 Ok(bytes)
116 }
117}
118
119pub struct Maintenance<M: Memory> {
123 map: Map<M>,
124 transition: SchemaTransition,
125 incarnation: [u8; 16],
126}
127
128impl<M: Memory> Database<M> {
129 pub fn begin_maintenance(
137 mut self,
138 transition: &SchemaTransition,
139 ) -> Result<Maintenance<M>, Error> {
140 if transition.source != self.schema.fingerprint() {
141 return Err(Error::InvalidTransition);
142 }
143 let bytes = transition.freeze(self.incarnation)?;
144 let transition = transition.clone();
145 self.map.insert(manifest_key(), bytes);
146
147 Ok(Maintenance {
148 map: self.map,
149 transition,
150 incarnation: self.incarnation,
151 })
152 }
153}
154
155impl<M: Memory> Maintenance<M> {
156 pub fn resume(memory: RuntimeMemory<M>, expected: &SchemaTransition) -> Result<Self, Error> {
162 if memory.size() == 0 {
163 return Err(Error::Corrupt);
164 }
165 let map = Map::load(memory);
166 let bytes = map.get(&manifest_key()).ok_or(Error::Corrupt)?;
167 let (transition, incarnation) = decode(&bytes)?;
168 if transition != *expected {
169 return Err(Error::InvalidTransition);
170 }
171
172 Ok(Self {
173 map,
174 transition,
175 incarnation,
176 })
177 }
178
179 #[must_use]
181 pub const fn transition(&self) -> &SchemaTransition {
182 &self.transition
183 }
184
185 #[must_use]
187 pub const fn incarnation(&self) -> [u8; 16] {
188 self.incarnation
189 }
190
191 pub fn source_page<E: Entity>(
204 &self,
205 source: &Schema,
206 after: Option<&QueryCursor>,
207 limit: usize,
208 bytes: usize,
209 ) -> Result<QueryPage<E>, Error> {
210 if source.fingerprint() != self.transition.source {
211 return Err(Error::IncompatibleSchema);
212 }
213 source.admits(E::SCHEMA)?;
214 let revision = read_revision(&self.map, E::SCHEMA.id)?;
215 let mut hash = Sha256::new();
216 hash.update(b"ic-db:maintenance-source:v1\0");
217 hash.update(self.transition.freeze(self.incarnation)?);
218 hash.update(revision.to_le_bytes());
219
220 query::source_page(
221 &self.map,
222 E::SCHEMA,
223 hash.finalize().into(),
224 self.incarnation,
225 after,
226 limit,
227 bytes,
228 )?
229 .decode_entities()
230 }
231
232 pub fn cancel(mut self) {
238 let bytes = live_manifest(self.transition.source, self.incarnation);
239 self.map.insert(manifest_key(), bytes);
240 }
241}
242
243pub(super) fn decode(bytes: &[u8]) -> Result<(SchemaTransition, [u8; 16]), Error> {
246 if !bytes.starts_with(MAGIC) {
247 return Err(Error::InvalidTransition);
248 }
249 if !(102..=MAX_FRAME).contains(&bytes.len()) {
250 return Err(Error::Corrupt);
251 }
252 let source = bytes[8..40].try_into().map_err(|_| Error::Corrupt)?;
253 let target = bytes[40..72].try_into().map_err(|_| Error::Corrupt)?;
254 let incarnation = bytes[72..88].try_into().map_err(|_| Error::Corrupt)?;
255 let mut reader = Decoder::new(&bytes[88..])?;
256 if reader.nat8()? != 0 {
257 return Err(Error::IncompatibleSchema);
258 }
259 let version = reader.nat32()?;
260 let name = reader.text(MAX_NAME)?;
261 let inputs = reader.blob(MAX_INPUTS)?;
262 reader.finish()?;
263 if source == target || incarnation == [0; 16] || version == 0 || name.is_empty() {
264 return Err(Error::Corrupt);
265 }
266
267 Ok((
268 SchemaTransition {
269 source,
270 target,
271 name,
272 version,
273 inputs,
274 },
275 incarnation,
276 ))
277}