Skip to main content

ic_db/store/maintenance/
mod.rs

1//! One frozen source and one exact executable-declared transformation identity.
2
3mod 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/// Identity of one explicitly supported source-to-target transformation.
32/// Changing code behavior requires a new version, even when both schemas match.
33/// This descriptor does not execute a transformation or authorize target publication.
34#[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    /// Bind compiled source/target contracts, a semantic name/version and fixed inputs.
45    /// Names contain 1..=64 UTF-8 bytes; fixed inputs contain at most 256 bytes.
46    /// # Errors
47    /// Refuses identical schemas, version zero or exceeded identity bounds.
48    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    /// Required source contract fingerprint.
74    #[must_use]
75    pub const fn source(&self) -> [u8; 32] {
76        self.source
77    }
78
79    /// Intended target contract fingerprint.
80    #[must_use]
81    pub const fn target(&self) -> [u8; 32] {
82        self.target
83    }
84
85    /// Exact semantic transformation name, without normalization.
86    #[must_use]
87    pub fn name(&self) -> &str {
88        &self.name
89    }
90
91    /// Declared version of the transformation's behavior.
92    #[must_use]
93    pub const fn version(&self) -> u32 {
94        self.version
95    }
96
97    /// Fixed transformation inputs, bound byte-for-byte.
98    #[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)?; // Only the source-frozen, no-target-allocation phase is admitted.
106        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
119/// Exclusive handle to a durably frozen source, before any target allocation/copy.
120/// Dropping this handle leaves maintenance active. Ordinary reads/writes remain closed.
121/// Host adapters own authorization and endpoint exposure.
122pub struct Maintenance<M: Memory> {
123    map: Map<M>,
124    transition: SchemaTransition,
125    incarnation: [u8; 16],
126}
127
128impl<M: Memory> Database<M> {
129    /// Close ordinary access and bind one transition, consuming the live handle.
130    /// Performs one synchronous manifest replacement after complete preparation.
131    /// A later trap in the enclosing IC message rolls back the freeze as well.
132    /// # Errors
133    /// Refuses a transition for another source contract before persistent mutation.
134    /// # Panics
135    /// Supplier failures during mutation trap the enclosing IC message.
136    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    /// Reopen a frozen source only for the exact supported transition.
157    /// # Errors
158    /// Refuses live data, different identities, unsupported phases and corrupt frames intact.
159    /// # Panics
160    /// Supplier corruption traps without repair, as for ordinary database admission.
161    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    /// Inspect the admitted transformation identity.
176    #[must_use]
177    pub const fn transition(&self) -> &SchemaTransition {
178        &self.transition
179    }
180
181    /// Original database incarnation, preserved by cancellation.
182    #[must_use]
183    pub const fn incarnation(&self) -> [u8; 16] {
184        self.incarnation
185    }
186
187    /// Read frozen source entities in ascending primary-key order through their
188    /// explicitly supplied compiled source schema and decoder. Limits are 1..=32
189    /// candidates and 1..=128 KiB of encoded output per call. Only `next == None`
190    /// establishes completion; a byte-limited page retries its unreturned row.
191    /// Cursors bind the transition, database, entity and source revision. Cancelling,
192    /// editing that entity and refreezing invalidates earlier cursors. These are
193    /// caller-controlled read positions, not trusted migration checkpoints.
194    /// # Errors
195    /// Refuses incompatible source schemas/decoders, invalid limits/cursors and
196    /// corrupt rows or revisions. An individually oversized row returns `RowTooLarge`.
197    /// # Panics
198    /// Supplier corruption traps without repair.
199    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    /// Cancel before target allocation/copy and restore the original live manifest.
215    /// Reopening then requires an executable compatible with the source contract.
216    /// A later trap in this IC message restores the frozen state.
217    /// # Panics
218    /// Supplier mutation failures trap the enclosing IC message.
219    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_rows(E::decode)
250    }
251}
252
253// Admission is shared by ordinary open and maintenance resume. Unknown future
254// phases refuse: an older executable must never cancel a copy it cannot interpret.
255pub(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}