nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Frame-0 `NV02` keyframe persistence (`Frame0File` / `frame0.nv02`).

use std::fmt;
#[cfg(not(target_arch = "wasm32"))]
use std::io;
use std::path::Path;

use nativeview_abi::xxh64;
use nativeview_codec::ByteReader;
use nativeview_store::wire::{WireDecoder, WireEncoder};
use nativeview_store::{NodeId, NodeStore};

use crate::store_backend::Frame0SubmitError;
use crate::{BackendApplyStats, StoreBackend, StoreWireReplica};

use super::{PersistenceError, remove_corrupt_frame0, write_file_atomic};
#[cfg(not(target_arch = "wasm32"))]
use super::{ReadBoundedError, read_file_bounded};

pub const DEFAULT_FRAME0_FILE_NAME: &str = "frame0.nv02";
pub const FRAME0_FOOTER_SIZE: usize = 40;
/// Maximum accepted `frame0.nv02` size (64 MiB) to bound memory against hostile/corrupt files.
pub const MAX_FRAME0_FILE_BYTES: usize = 64 * 1024 * 1024;

const FRAME0_XXH64_SEED: u64 = 0x4E56_4546_524D_3032;
#[cfg(not(target_arch = "wasm32"))]
const NV02_MAGIC_BYTES: [u8; 4] = *b"NV02";

/// Application build identifier stamped into `frame0.nv02` footers for cache invalidation.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct AppBuildId(pub u64);

impl PartialEq<u64> for AppBuildId {
    #[inline]
    fn eq(&self, other: &u64) -> bool {
        self.0 == *other
    }
}

impl fmt::Display for AppBuildId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Frame0Meta {
    pub table_schema_hash: u64,
    pub app_build_id: AppBuildId,
    pub env_hash: u64,
}

impl Frame0Meta {
    /// Canonical Frame-0 metadata for all 17 core tables (`app_build_id = 0`, `env_hash = 0`),
    /// shared across `nv prerender`, `nativeview-skia-shell`, and native hosts.
    pub fn default_core() -> Self {
        Self {
            table_schema_hash: nativeview_tables::tables::core_tables_schema_hash(),
            app_build_id: AppBuildId(0),
            env_hash: 0,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frame0Footer {
    pub node_count: u32,
    pub flags: u32,
    pub table_schema_hash: u64,
    pub app_build_id: AppBuildId,
    pub env_hash: u64,
    pub payload_xxh64: u64,
}

impl Frame0Footer {
    pub fn to_bytes(self) -> [u8; FRAME0_FOOTER_SIZE] {
        let mut out = [0u8; FRAME0_FOOTER_SIZE];
        out[0..4].copy_from_slice(&self.node_count.to_le_bytes());
        out[4..8].copy_from_slice(&self.flags.to_le_bytes());
        out[8..16].copy_from_slice(&self.table_schema_hash.to_le_bytes());
        out[16..24].copy_from_slice(&self.app_build_id.0.to_le_bytes());
        out[24..32].copy_from_slice(&self.env_hash.to_le_bytes());
        out[32..40].copy_from_slice(&self.payload_xxh64.to_le_bytes());
        out
    }

    pub fn from_bytes(b: &[u8; FRAME0_FOOTER_SIZE]) -> Self {
        let mut r = ByteReader::new(b);
        Self {
            node_count: r.read_u32().unwrap_or(0),
            flags: r.read_u32().unwrap_or(0),
            table_schema_hash: r.read_u64().unwrap_or(0),
            app_build_id: AppBuildId(r.read_u64().unwrap_or(0)),
            env_hash: r.read_u64().unwrap_or(0),
            payload_xxh64: r.read_u64().unwrap_or(0),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame0Miss {
    NotFound,
    Io(String),
    FlagsMismatch(u32),
    Corrupt(&'static str),
    Backend(String),
    SchemaMismatch { expected: u64, actual: u64 },
    BuildIdMismatch { expected: u64, actual: u64 },
    EnvHashMismatch { expected: u64, actual: u64 },
}

impl fmt::Display for Frame0Miss {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotFound => write!(f, "frame0.nv02 not found"),
            Self::Io(e) => write!(f, "frame0.nv02 I/O error: {e}"),
            Self::FlagsMismatch(fl) => write!(f, "frame0.nv02 unsupported flags: {fl:#x}"),
            Self::Corrupt(m) => write!(f, "frame0.nv02 corrupt: {m}"),
            Self::Backend(e) => write!(f, "frame0.nv02 backend commit error: {e}"),
            Self::SchemaMismatch { expected, actual } => {
                write!(
                    f,
                    "frame0.nv02 schema mismatch: {expected:#x} != {actual:#x}"
                )
            }
            Self::BuildIdMismatch { expected, actual } => {
                write!(
                    f,
                    "frame0.nv02 build_id mismatch: {expected:#x} != {actual:#x}"
                )
            }
            Self::EnvHashMismatch { expected, actual } => {
                write!(
                    f,
                    "frame0.nv02 env_hash mismatch: {expected:#x} != {actual:#x}"
                )
            }
        }
    }
}

impl std::error::Error for Frame0Miss {}

/// Frame-0 `NV02` keyframe file (`frame0.nv02`) + 40-byte little-endian footer.
pub struct Frame0File;

impl Frame0File {
    pub fn encode(store: &NodeStore, meta: Frame0Meta) -> Result<Vec<u8>, PersistenceError> {
        let live_nodes = store.stats().live_nodes;
        let node_count =
            u32::try_from(live_nodes).map_err(|_| PersistenceError::PayloadTooLarge(live_nodes))?;
        let mut out = Vec::with_capacity(live_nodes.saturating_mul(64) + FRAME0_FOOTER_SIZE + 64);
        WireEncoder::default().encode_full(store, &mut out);
        if out.len().saturating_add(FRAME0_FOOTER_SIZE) > MAX_FRAME0_FILE_BYTES {
            return Err(PersistenceError::PayloadTooLarge(out.len()));
        }
        append_footer(&mut out, node_count, meta);
        Ok(out)
    }

    pub fn encode_nv02(
        nv02_payload: &[u8],
        node_count: u32,
        meta: Frame0Meta,
    ) -> Result<Vec<u8>, PersistenceError> {
        let (frame, _ops) = WireDecoder::validate_header(nv02_payload)?;
        if frame != 1 {
            return Err(PersistenceError::Corrupt(
                "NV02 frame0 must be keyframe (frame == 1)",
            ));
        }
        let max_nodes = (nv02_payload.len() / 4).min(NodeId::MAX_INDEX as usize);
        if (node_count as usize) > max_nodes {
            return Err(PersistenceError::Corrupt(
                "node_count exceeds NV02 payload capacity",
            ));
        }
        if nv02_payload.len().saturating_add(FRAME0_FOOTER_SIZE) > MAX_FRAME0_FILE_BYTES {
            return Err(PersistenceError::PayloadTooLarge(nv02_payload.len()));
        }
        let mut out = Vec::with_capacity(nv02_payload.len() + FRAME0_FOOTER_SIZE);
        out.extend_from_slice(nv02_payload);
        append_footer(&mut out, node_count, meta);
        Ok(out)
    }

    pub fn save(
        path: impl AsRef<Path>,
        store: &NodeStore,
        meta: Frame0Meta,
    ) -> Result<Frame0Footer, PersistenceError> {
        let bytes = Self::encode(store, meta)?;
        write_file_atomic(path.as_ref(), &bytes, true)?;
        let arr: [u8; FRAME0_FOOTER_SIZE] = bytes[bytes.len() - FRAME0_FOOTER_SIZE..]
            .try_into()
            .map_err(|_| PersistenceError::Corrupt("footer slice"))?;
        Ok(Frame0Footer::from_bytes(&arr))
    }

    pub fn save_bytes(
        path: impl AsRef<Path>,
        envelope_bytes: &[u8],
    ) -> Result<(), PersistenceError> {
        write_file_atomic(path.as_ref(), envelope_bytes, true)
    }

    pub fn validate_bytes(
        bytes: &[u8],
        expected: Frame0Meta,
    ) -> Result<(Frame0Footer, &[u8]), Frame0Miss> {
        if bytes.len() > MAX_FRAME0_FILE_BYTES {
            return Err(Frame0Miss::Corrupt("frame0.nv02 exceeds max size"));
        }
        if bytes.len() < FRAME0_FOOTER_SIZE {
            return Err(Frame0Miss::Corrupt("truncated below 40-byte footer"));
        }
        let split = bytes.len() - FRAME0_FOOTER_SIZE;
        let payload = &bytes[..split];
        let arr: [u8; FRAME0_FOOTER_SIZE] = bytes[split..]
            .try_into()
            .map_err(|_| Frame0Miss::Corrupt("invalid footer slice"))?;
        let footer = Frame0Footer::from_bytes(&arr);
        if xxh64(&bytes[..bytes.len() - 8], FRAME0_XXH64_SEED) != footer.payload_xxh64 {
            return Err(Frame0Miss::Corrupt("XXH64 checksum mismatch"));
        }
        let Ok((frame, _ops)) = WireDecoder::validate_header(payload) else {
            return Err(Frame0Miss::Corrupt("invalid NV02 keyframe header"));
        };
        if frame != 1 {
            return Err(Frame0Miss::Corrupt(
                "NV02 frame0 must be keyframe (frame == 1)",
            ));
        }
        let max_nodes = (payload.len() / 4).min(NodeId::MAX_INDEX as usize);
        if (footer.node_count as usize) > max_nodes {
            return Err(Frame0Miss::Corrupt(
                "footer node_count exceeds NV02 payload capacity",
            ));
        }
        if footer.flags != 0 {
            return Err(Frame0Miss::FlagsMismatch(footer.flags));
        }
        if footer.table_schema_hash != expected.table_schema_hash {
            return Err(Frame0Miss::SchemaMismatch {
                expected: expected.table_schema_hash,
                actual: footer.table_schema_hash,
            });
        }
        if footer.app_build_id != expected.app_build_id {
            return Err(Frame0Miss::BuildIdMismatch {
                expected: expected.app_build_id.0,
                actual: footer.app_build_id.0,
            });
        }
        if footer.env_hash != expected.env_hash {
            return Err(Frame0Miss::EnvHashMismatch {
                expected: expected.env_hash,
                actual: footer.env_hash,
            });
        }
        Ok((footer, payload))
    }

    /// Validates an in-memory `frame0.nv02` envelope buffer against the expected schema hash,
    /// app build ID, and environment hash, returning the parsed footer and borrowed `NV02`
    /// keyframe payload slice without copying.
    pub fn read_and_validate_bytes(
        bytes: &[u8],
        expected_schema_hash: u64,
        expected_app_build_id: u64,
        expected_env_hash: u64,
    ) -> Result<(Frame0Footer, &[u8]), Frame0Miss> {
        Self::validate_bytes(
            bytes,
            Frame0Meta {
                table_schema_hash: expected_schema_hash,
                app_build_id: AppBuildId(expected_app_build_id),
                env_hash: expected_env_hash,
            },
        )
    }

    pub fn read_and_validate(
        path: impl AsRef<Path>,
        expected: Frame0Meta,
    ) -> Result<(Frame0Footer, Vec<u8>), Frame0Miss> {
        let mut buf = Vec::new();
        let footer = Self::read_into_buf(path.as_ref(), expected, &mut buf)?;
        buf.truncate(buf.len() - FRAME0_FOOTER_SIZE);
        Ok((footer, buf))
    }

    pub fn boot_bytes_into_replica<B: StoreBackend>(
        bytes: &[u8],
        expected: Frame0Meta,
        replica: &mut StoreWireReplica<B>,
    ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
        let (footer, payload) = Self::validate_bytes(bytes, expected)?;
        Self::boot_validated_into_replica(footer, payload, replica, None)
    }

    pub fn boot_into_replica<B: StoreBackend>(
        path: impl AsRef<Path>,
        expected: Frame0Meta,
        replica: &mut StoreWireReplica<B>,
    ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
        Self::boot_into_replica_with_buf(path, expected, &mut Vec::new(), replica)
    }

    pub fn boot_into_replica_with_buf<B: StoreBackend>(
        path: impl AsRef<Path>,
        expected: Frame0Meta,
        scratch: &mut Vec<u8>,
        replica: &mut StoreWireReplica<B>,
    ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
        let path = path.as_ref();
        let footer = Self::read_into_buf(path, expected, scratch)?;
        let payload = &scratch[..scratch.len() - FRAME0_FOOTER_SIZE];
        Self::boot_validated_into_replica(footer, payload, replica, Some(path))
    }

    fn boot_validated_into_replica<B: StoreBackend>(
        footer: Frame0Footer,
        payload: &[u8],
        replica: &mut StoreWireReplica<B>,
        disk_path: Option<&Path>,
    ) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
        let res = replica.submit_frame0_nv02(payload, footer.node_count as usize);
        map_frame0_submit_result(res, footer, disk_path)
    }

    /// Returns `true` iff `path` exists, is readable, and begins with the 4-byte `NV02` magic
    /// header (prevents corrupt-file cleanup from deleting unrelated files).
    #[cfg(not(target_arch = "wasm32"))]
    pub fn file_has_nv02_magic(path: &Path) -> bool {
        use std::io::Read as _;
        let Ok(mut f) = std::fs::File::open(path) else {
            return false;
        };
        let mut magic = [0u8; 4];
        f.read_exact(&mut magic).is_ok() && magic == NV02_MAGIC_BYTES
    }

    fn read_into_buf(
        path: &Path,
        expected: Frame0Meta,
        buf: &mut Vec<u8>,
    ) -> Result<Frame0Footer, Frame0Miss> {
        #[cfg(target_arch = "wasm32")]
        {
            let _ = (path, expected, buf);
            Err(Frame0Miss::NotFound)
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let mut file = match std::fs::File::open(path) {
                Ok(f) => f,
                Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(Frame0Miss::NotFound),
                Err(e) => return Err(Frame0Miss::Io(e.to_string())),
            };
            match read_file_bounded(&mut file, MAX_FRAME0_FILE_BYTES, buf) {
                Ok(()) => {}
                Err(ReadBoundedError::Io(e)) => return Err(Frame0Miss::Io(e.to_string())),
                Err(ReadBoundedError::TooLarge) => {
                    drop(file);
                    if Self::file_has_nv02_magic(path) {
                        let _ = std::fs::remove_file(path);
                    }
                    return Err(Frame0Miss::Corrupt("frame0.nv02 exceeds max size"));
                }
            }
            drop(file);
            Self::validate_bytes(buf, expected)
                .map(|(f, _)| f)
                .map_err(|miss| {
                    if matches!(miss, Frame0Miss::Corrupt(_)) && buf.starts_with(&NV02_MAGIC_BYTES) {
                        let _ = std::fs::remove_file(path);
                    }
                    miss
                })
        }
    }
}

fn map_frame0_submit_result(
    res: Result<BackendApplyStats, Frame0SubmitError>,
    footer: Frame0Footer,
    disk_path: Option<&Path>,
) -> Result<(Frame0Footer, BackendApplyStats), Frame0Miss> {
    match res {
        Ok(stats) => Ok((footer, stats)),
        Err(Frame0SubmitError::NodeCountMismatch) => {
            remove_corrupt_frame0(disk_path);
            Err(Frame0Miss::Corrupt("footer node_count mismatch"))
        }
        Err(Frame0SubmitError::Wire) => {
            remove_corrupt_frame0(disk_path);
            Err(Frame0Miss::Corrupt("NV02 decode failed"))
        }
        Err(Frame0SubmitError::Alloc) => {
            Err(Frame0Miss::Backend("NV02 allocation failed".to_string()))
        }
        Err(Frame0SubmitError::Backend(err)) => Err(Frame0Miss::Backend(err.to_string())),
    }
}

fn append_footer(out: &mut Vec<u8>, node_count: u32, meta: Frame0Meta) {
    let f = Frame0Footer {
        node_count,
        flags: 0,
        table_schema_hash: meta.table_schema_hash,
        app_build_id: meta.app_build_id,
        env_hash: meta.env_hash,
        payload_xxh64: 0,
    };
    let start = out.len();
    out.extend_from_slice(&f.to_bytes());
    let hash = xxh64(&out[..start + 32], FRAME0_XXH64_SEED);
    out[start + 32..start + 40].copy_from_slice(&hash.to_le_bytes());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn frame0_submit_alloc_error_maps_to_backend_miss_and_preserves_disk_file() {
        let path = std::env::temp_dir().join(format!(
            "nv_frame0_alloc_preserve_{}.nv02",
            std::process::id()
        ));
        std::fs::write(&path, b"valid-cache-sentinel").expect("write sentinel");
        let footer = Frame0Footer {
            node_count: 1,
            flags: 0,
            table_schema_hash: 0,
            app_build_id: AppBuildId(0),
            env_hash: 0,
            payload_xxh64: 0,
        };
        assert!(matches!(
            map_frame0_submit_result(Err(Frame0SubmitError::Alloc), footer, Some(&path)),
            Err(Frame0Miss::Backend(ref msg)) if msg.contains("allocation")
        ));
        assert!(
            path.exists(),
            "transient Frame0SubmitError::Alloc must preserve disk cache"
        );
        assert!(matches!(
            map_frame0_submit_result(Err(Frame0SubmitError::Wire), footer, Some(&path)),
            Err(Frame0Miss::Corrupt(_))
        ));
        assert!(
            !path.exists(),
            "deterministic Frame0SubmitError::Wire / Budget must remove corrupt disk cache"
        );
    }

    #[test]
    fn frame0_rejects_table_schema_hash_when_only_resource_kind_changes() {
        use nativeview_store::{FlatResource, NvTable, Res, ValidatedWords};

        struct KindAlpha;
        impl FlatResource for KindAlpha {
            const KIND: nativeview_abi::Key64 = nativeview_abi::Key64::of("test.frame0.kind_alpha");
            type View<'a> = &'a [u32];
            fn write_words(&self, out: &mut Vec<u32>) -> bool {
                out.push(1);
                true
            }
            fn validate(w: &[u32]) -> bool {
                w.len() == 1
            }
            fn view(w: ValidatedWords<'_, Self>) -> &[u32] {
                w.as_slice()
            }
        }

        struct KindBeta;
        impl FlatResource for KindBeta {
            const KIND: nativeview_abi::Key64 = nativeview_abi::Key64::of("test.frame0.kind_beta");
            type View<'a> = &'a [u32];
            fn write_words(&self, out: &mut Vec<u32>) -> bool {
                out.push(2);
                true
            }
            fn validate(w: &[u32]) -> bool {
                w.len() == 1
            }
            fn view(w: ValidatedWords<'_, Self>) -> &[u32] {
                w.as_slice()
            }
        }

        #[allow(dead_code)]
        #[derive(nativeview_store::NvTable)]
        #[nv_table(name = "test.frame0.res_kind_schema", storage = "sparse")]
        struct SchemaAlpha {
            #[effect(paint)]
            payload: Res<KindAlpha>,
        }

        #[allow(dead_code)]
        #[derive(nativeview_store::NvTable)]
        #[nv_table(name = "test.frame0.res_kind_schema", storage = "sparse")]
        struct SchemaBeta {
            #[effect(paint)]
            payload: Res<KindBeta>,
        }

        let store = NodeStore::new();
        let meta_alpha = Frame0Meta {
            table_schema_hash: nativeview_store::tables_schema_hash(&[&SchemaAlpha::DESC]),
            app_build_id: AppBuildId(1),
            env_hash: 0,
        };
        let meta_beta = Frame0Meta {
            table_schema_hash: nativeview_store::tables_schema_hash(&[&SchemaBeta::DESC]),
            app_build_id: AppBuildId(1),
            env_hash: 0,
        };
        assert_ne!(meta_alpha.table_schema_hash, meta_beta.table_schema_hash);
        let bytes = Frame0File::encode(&store, meta_alpha).expect("encode frame0");
        assert_eq!(
            Frame0File::validate_bytes(&bytes, meta_beta).unwrap_err(),
            Frame0Miss::SchemaMismatch {
                expected: meta_beta.table_schema_hash,
                actual: meta_alpha.table_schema_hash,
            }
        );
    }
}