1mod 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 let (map, bytes) = super::load_manifest(memory)?;
163 let (transition, incarnation) = decode(&bytes)?;
164 if transition != *expected {
165 return Err(Error::InvalidTransition);
166 }
167
168 Ok(Self {
169 map,
170 transition,
171 incarnation,
172 })
173 }
174
175 #[must_use]
177 pub const fn transition(&self) -> &SchemaTransition {
178 &self.transition
179 }
180
181 #[must_use]
183 pub const fn incarnation(&self) -> [u8; 16] {
184 self.incarnation
185 }
186
187 pub fn source_page<E: Entity>(
200 &self,
201 source: &Schema,
202 after: Option<&QueryCursor>,
203 limit: usize,
204 bytes: usize,
205 ) -> Result<QueryPage<E>, Error> {
206 if source.fingerprint() != self.transition.source {
207 return Err(Error::IncompatibleSchema);
208 }
209 source.admits(E::SCHEMA)?;
210 self.transition
211 .read_page(&self.map, self.incarnation, after, limit, bytes)
212 }
213
214 pub fn cancel(mut self) {
220 let bytes = live_manifest(self.transition.source, self.incarnation);
221 self.map.insert(manifest_key(), bytes);
222 }
223}
224
225impl SchemaTransition {
226 fn read_page<E: Entity, M: Memory>(
227 &self,
228 map: &Map<M>,
229 incarnation: [u8; 16],
230 after: Option<&QueryCursor>,
231 limit: usize,
232 bytes: usize,
233 ) -> Result<QueryPage<E>, Error> {
234 let revision = read_revision(map, E::SCHEMA.id)?;
235 let mut hash = Sha256::new();
236 hash.update(b"ic-db:maintenance-source:v1\0");
237 hash.update(self.freeze(incarnation)?);
238 hash.update(revision.to_le_bytes());
239
240 query::source_page(
241 map,
242 E::SCHEMA,
243 hash.finalize().into(),
244 incarnation,
245 after,
246 limit,
247 bytes,
248 )?
249 .decode_entities()
250 }
251}
252
253pub(super) fn decode(bytes: &[u8]) -> Result<(SchemaTransition, [u8; 16]), Error> {
256 if !bytes.starts_with(MAGIC) {
257 return Err(Error::InvalidTransition);
258 }
259 if !(102..=MAX_FRAME).contains(&bytes.len()) {
260 return Err(Error::Corrupt);
261 }
262 let source = bytes[8..40].try_into().map_err(|_| Error::Corrupt)?;
263 let target = bytes[40..72].try_into().map_err(|_| Error::Corrupt)?;
264 let incarnation = bytes[72..88].try_into().map_err(|_| Error::Corrupt)?;
265 let mut reader = Decoder::new(&bytes[88..])?;
266 if reader.nat8()? != 0 {
267 return Err(Error::IncompatibleSchema);
268 }
269 let version = reader.nat32()?;
270 let name = reader.text(MAX_NAME)?;
271 let inputs = reader.blob(MAX_INPUTS)?;
272 reader.finish()?;
273 if source == target || incarnation == [0; 16] || version == 0 || name.is_empty() {
274 return Err(Error::Corrupt);
275 }
276
277 Ok((
278 SchemaTransition {
279 source,
280 target,
281 name,
282 version,
283 inputs,
284 },
285 incarnation,
286 ))
287}