Skip to main content

ic_db/store/maintenance/
mod.rs

1//! One frozen source and one exact executable-declared transformation identity.
2mod copy;
3use super::{Database, Map, live_manifest, manifest_key, query, read_revision};
4use crate::{
5    Entity, Error, QueryCursor, QueryPage, Schema,
6    codec::{Decoder, Encoder},
7};
8pub use copy::{CopyStep, RetiredSource, SchemaCopy};
9use ic_storage::{Memory, RuntimeMemory};
10use sha2::{Digest, Sha256};
11
12pub(super) const MAGIC: &[u8; 8] = b"ICDBMT02";
13const MAX_NAME: usize = 64;
14const MAX_INPUTS: usize = 256;
15const MAX_FRAME: usize = 421;
16
17pub(super) fn admits_gate(bytes: &[u8]) -> Result<bool, Error> {
18    if bytes.starts_with(MAGIC) {
19        decode(bytes)?;
20    } else if bytes.starts_with(copy::MAGIC) {
21        copy::decode(bytes)?;
22    } else {
23        return Ok(false);
24    }
25    Ok(true)
26}
27
28/// Identity of one explicitly supported source-to-target transformation.
29/// Changing code behavior requires a new version, even when both schemas match.
30/// This descriptor does not execute a transformation or authorize target publication.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct SchemaTransition {
33    source: [u8; 32],
34    target: [u8; 32],
35    name: String,
36    version: u32,
37    inputs: Vec<u8>,
38}
39
40impl SchemaTransition {
41    /// Bind compiled source/target contracts, a semantic name/version and fixed inputs.
42    /// Names contain 1..=64 UTF-8 bytes; fixed inputs contain at most 256 bytes.
43    /// # Errors
44    /// Refuses identical schemas, version zero or exceeded identity bounds.
45    pub fn new(
46        source: &Schema,
47        target: &Schema,
48        name: &str,
49        version: u32,
50        inputs: &[u8],
51    ) -> Result<Self, Error> {
52        if source.fingerprint() == target.fingerprint()
53            || name.is_empty()
54            || name.len() > MAX_NAME
55            || version == 0
56            || inputs.len() > MAX_INPUTS
57        {
58            return Err(Error::InvalidTransition);
59        }
60        Ok(Self {
61            source: source.fingerprint(),
62            target: target.fingerprint(),
63            name: name.into(),
64            version,
65            inputs: inputs.into(),
66        })
67    }
68
69    /// Required source contract fingerprint.
70    #[must_use]
71    pub const fn source(&self) -> [u8; 32] {
72        self.source
73    }
74
75    /// Intended target contract fingerprint.
76    #[must_use]
77    pub const fn target(&self) -> [u8; 32] {
78        self.target
79    }
80
81    /// Exact semantic transformation name, without normalization.
82    #[must_use]
83    pub fn name(&self) -> &str {
84        &self.name
85    }
86
87    /// Declared version of the transformation's behavior.
88    #[must_use]
89    pub const fn version(&self) -> u32 {
90        self.version
91    }
92
93    /// Fixed transformation inputs, bound byte-for-byte.
94    #[must_use]
95    pub fn inputs(&self) -> &[u8] {
96        &self.inputs
97    }
98
99    fn freeze(&self, incarnation: [u8; 16]) -> Result<Vec<u8>, Error> {
100        let mut payload = Encoder::new();
101        payload.nat8(0)?; // Only the source-frozen, no-target-allocation phase is admitted.
102        payload.nat32(self.version)?;
103        payload.bytes(self.name.as_bytes())?;
104        payload.bytes(&self.inputs)?;
105        let mut bytes = MAGIC.to_vec();
106        bytes.extend(self.source);
107        bytes.extend(self.target);
108        bytes.extend(incarnation);
109        bytes.extend(payload.finish());
110        Ok(bytes)
111    }
112}
113
114/// Exclusive handle to a durably frozen source, before any target allocation/copy.
115/// Dropping this handle leaves maintenance active. Ordinary reads/writes remain closed.
116/// Host adapters own authorization and endpoint exposure.
117pub struct Maintenance<M: Memory> {
118    map: Map<M>,
119    transition: SchemaTransition,
120    incarnation: [u8; 16],
121}
122
123impl<M: Memory> Database<M> {
124    /// Close ordinary access and bind one transition, consuming the live handle.
125    /// Performs one synchronous manifest replacement after complete preparation.
126    /// A later trap in the enclosing IC message rolls back the freeze as well.
127    /// # Errors
128    /// Refuses a transition for another source contract before persistent mutation.
129    /// # Panics
130    /// Supplier failures during mutation trap the enclosing IC message.
131    pub fn begin_maintenance(
132        mut self,
133        transition: &SchemaTransition,
134    ) -> Result<Maintenance<M>, Error> {
135        if transition.source != self.schema.fingerprint() {
136            return Err(Error::InvalidTransition);
137        }
138        let bytes = transition.freeze(self.incarnation)?;
139        let transition = transition.clone();
140        self.map.insert(manifest_key(), bytes);
141        Ok(Maintenance {
142            map: self.map,
143            transition,
144            incarnation: self.incarnation,
145        })
146    }
147}
148
149impl<M: Memory> Maintenance<M> {
150    /// Reopen a frozen source only for the exact supported transition.
151    /// # Errors
152    /// Refuses live data, different identities, unsupported phases and corrupt frames intact.
153    /// # Panics
154    /// Supplier corruption traps without repair, as for ordinary database admission.
155    pub fn resume(memory: RuntimeMemory<M>, expected: &SchemaTransition) -> Result<Self, Error> {
156        if memory.size() == 0 {
157            return Err(Error::Corrupt);
158        }
159        let map = Map::load(memory);
160        let bytes = map.get(&manifest_key()).ok_or(Error::Corrupt)?;
161        let (transition, incarnation) = decode(&bytes)?;
162        if transition != *expected {
163            return Err(Error::InvalidTransition);
164        }
165        Ok(Self {
166            map,
167            transition,
168            incarnation,
169        })
170    }
171
172    /// Inspect the admitted transformation identity.
173    #[must_use]
174    pub const fn transition(&self) -> &SchemaTransition {
175        &self.transition
176    }
177
178    /// Original database incarnation, preserved by cancellation.
179    #[must_use]
180    pub const fn incarnation(&self) -> [u8; 16] {
181        self.incarnation
182    }
183
184    /// Read frozen source entities in ascending primary-key order through their
185    /// explicitly supplied compiled source schema and decoder. Limits are 1..=32
186    /// candidates and 1..=128 KiB of encoded output per call. Only `next == None`
187    /// establishes completion; a byte-limited page retries its unreturned row.
188    /// Cursors bind the transition, database, entity and source revision. Cancelling,
189    /// editing that entity and refreezing invalidates earlier cursors. These are
190    /// caller-controlled read positions, not trusted migration checkpoints.
191    /// # Errors
192    /// Refuses incompatible source schemas/decoders, invalid limits/cursors and
193    /// corrupt rows or revisions. An individually oversized row returns `RowTooLarge`.
194    /// # Panics
195    /// Supplier corruption traps without repair.
196    pub fn source_page<E: Entity>(
197        &self,
198        source: &Schema,
199        after: Option<&QueryCursor>,
200        limit: usize,
201        bytes: usize,
202    ) -> Result<QueryPage<E>, Error> {
203        if source.fingerprint() != self.transition.source {
204            return Err(Error::IncompatibleSchema);
205        }
206        source.admits(E::SCHEMA)?;
207        let revision = read_revision(&self.map, E::ID)?;
208        let mut hash = Sha256::new();
209        hash.update(b"ic-db:maintenance-source:v1\0");
210        hash.update(self.transition.freeze(self.incarnation)?);
211        hash.update(revision.to_le_bytes());
212        query::source_page(
213            &self.map,
214            E::SCHEMA,
215            hash.finalize().into(),
216            self.incarnation,
217            after,
218            limit,
219            bytes,
220        )?
221        .decode_entities()
222    }
223
224    /// Cancel before target allocation/copy and restore the original live manifest.
225    /// Reopening then requires an executable compatible with the source contract.
226    /// A later trap in this IC message restores the frozen state.
227    /// # Panics
228    /// Supplier mutation failures trap the enclosing IC message.
229    pub fn cancel(mut self) {
230        let bytes = live_manifest(self.transition.source, self.incarnation);
231        self.map.insert(manifest_key(), bytes);
232    }
233}
234
235// Admission is shared by ordinary open and maintenance resume. Unknown future
236// phases refuse: an older executable must never cancel a copy it cannot interpret.
237pub(super) fn decode(bytes: &[u8]) -> Result<(SchemaTransition, [u8; 16]), Error> {
238    if !bytes.starts_with(MAGIC) {
239        return Err(Error::InvalidTransition);
240    }
241    if !(102..=MAX_FRAME).contains(&bytes.len()) {
242        return Err(Error::Corrupt);
243    }
244    let source = bytes[8..40].try_into().map_err(|_| Error::Corrupt)?;
245    let target = bytes[40..72].try_into().map_err(|_| Error::Corrupt)?;
246    let incarnation = bytes[72..88].try_into().map_err(|_| Error::Corrupt)?;
247    let mut reader = Decoder::new(&bytes[88..])?;
248    if reader.nat8()? != 0 {
249        return Err(Error::IncompatibleSchema);
250    }
251    let version = reader.nat32()?;
252    let name = reader.text(MAX_NAME)?;
253    let inputs = reader.blob(MAX_INPUTS)?;
254    reader.finish()?;
255    if source == target || incarnation == [0; 16] || version == 0 || name.is_empty() {
256        return Err(Error::Corrupt);
257    }
258    Ok((
259        SchemaTransition {
260            source,
261            target,
262            name,
263            version,
264            inputs,
265        },
266        incarnation,
267    ))
268}