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