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        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    /// Inspect the admitted transformation identity.
180    #[must_use]
181    pub const fn transition(&self) -> &SchemaTransition {
182        &self.transition
183    }
184
185    /// Original database incarnation, preserved by cancellation.
186    #[must_use]
187    pub const fn incarnation(&self) -> [u8; 16] {
188        self.incarnation
189    }
190
191    /// Read frozen source entities in ascending primary-key order through their
192    /// explicitly supplied compiled source schema and decoder. Limits are 1..=32
193    /// candidates and 1..=128 KiB of encoded output per call. Only `next == None`
194    /// establishes completion; a byte-limited page retries its unreturned row.
195    /// Cursors bind the transition, database, entity and source revision. Cancelling,
196    /// editing that entity and refreezing invalidates earlier cursors. These are
197    /// caller-controlled read positions, not trusted migration checkpoints.
198    /// # Errors
199    /// Refuses incompatible source schemas/decoders, invalid limits/cursors and
200    /// corrupt rows or revisions. An individually oversized row returns `RowTooLarge`.
201    /// # Panics
202    /// Supplier corruption traps without repair.
203    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    /// Cancel before target allocation/copy and restore the original live manifest.
233    /// Reopening then requires an executable compatible with the source contract.
234    /// A later trap in this IC message restores the frozen state.
235    /// # Panics
236    /// Supplier mutation failures trap the enclosing IC message.
237    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
243// Admission is shared by ordinary open and maintenance resume. Unknown future
244// phases refuse: an older executable must never cancel a copy it cannot interpret.
245pub(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}