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
use std::fmt;

use nativeview_codec::{ByteReader, ByteWriter, CodecError, DEFAULT_MAX_BYTES};

/// 16-byte wire magic identifying a binary `HotPatchMsg` frame (`NV_HOT_PATCH\0\0\0`).
pub const HOT_PATCH_WIRE_MAGIC: [u8; 16] = *b"NV_HOT_PATCH\0\0\0\0";

/// Wire protocol version immediately following [`HOT_PATCH_WIRE_MAGIC`].
/// Version 2 replaces legacy CSS string `attr_updates` with binary `RowPatch` `u32` word payloads
/// and 64-bit `xxh64` template identity keys.
pub const HOT_PATCH_VERSION: u8 = 2;

/// Maximum item count accepted per vector inside a binary `NV_HOT_PATCH` frame to prevent OOM on corrupt input.
const MAX_WIRE_ITEMS: usize = 65_536;

/// Error returned when decoding a binary `NV_HOT_PATCH` `HotPatchMsg` frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HotPatchDecodeError {
    Truncated,
    InvalidMagic,
    UnsupportedVersion(u8),
    UnknownVariant(u8),
    InvalidBool(u8),
    InvalidUtf8,
    LimitExceeded,
    TrailingBytes(usize),
}

impl From<CodecError> for HotPatchDecodeError {
    #[inline]
    fn from(err: CodecError) -> Self {
        match err {
            CodecError::Truncated { .. } => Self::Truncated,
            CodecError::BadMagic => Self::InvalidMagic,
            CodecError::BadVersion(v) => Self::UnsupportedVersion(v as u8),
            CodecError::BadEnum { raw, .. } => Self::UnknownVariant(raw as u8),
            CodecError::BadBool(b) => Self::InvalidBool(b),
            CodecError::InvalidUtf8 => Self::InvalidUtf8,
            CodecError::LenOverflow { .. } => Self::LimitExceeded,
            CodecError::TrailingBytes(n) => Self::TrailingBytes(n),
            CodecError::NonZeroReserved(_) => Self::InvalidMagic,
            CodecError::DepthExceeded { .. } => Self::LimitExceeded,
        }
    }
}

impl fmt::Display for HotPatchDecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Truncated => f.write_str("truncated NV_HOT_PATCH buffer"),
            Self::InvalidMagic => f.write_str("invalid NV_HOT_PATCH magic"),
            Self::UnsupportedVersion(v) => write!(
                f,
                "unsupported hot-patch wire version {v} (expected {HOT_PATCH_VERSION})"
            ),
            Self::UnknownVariant(v) => write!(f, "unknown NV_HOT_PATCH variant tag {v}"),
            Self::InvalidBool(v) => write!(f, "invalid NV_HOT_PATCH boolean tag {v}"),
            Self::InvalidUtf8 => f.write_str("invalid UTF-8 in NV_HOT_PATCH string"),
            Self::LimitExceeded => f.write_str("NV_HOT_PATCH collection limit exceeded"),
            Self::TrailingBytes(n) => write!(f, "trailing {n} byte(s) in NV_HOT_PATCH buffer"),
        }
    }
}

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

/// Unified 2-tier hot-reload protocol broadcast by `nv dev` over WebSocket (binary v2
/// frames, see [`HotPatchMsg::to_bytes`]) to Desktop Skia, iOS Simulator/Device, Android
/// Emulator/Device, and Web clients, and handed to apps through `NvDevApi::apply_hot_patch`.
/// There is no JSON form and no CSS attribute string payload.
#[derive(Debug, Clone, PartialEq)]
pub enum HotPatchMsg {
    /// Tier 1 (<10ms, zero recompile, works on physical iOS devices & browsers):
    /// Applies a binary `nativeview_store::RowPatch` and/or targeted text update directly onto matching
    /// `NodeStore` nodes identified by `(template_key, node_path)` or `target_test_id`.
    TemplatePatch {
        generation: u64,
        /// Collision-free `xxh64` template identity (`view!` `AnchorKey`); `0` if unkeyed.
        template_key: u64,
        /// Structural child-index path inside the template tree (from template root).
        node_path: Vec<u16>,
        /// Optional `test_id` / `data-testid` / `testID` fallback targeting a specific element.
        target_test_id: Option<String>,
        /// Flat `u32` words encoded by `nativeview_store::RowPatch::write_words` (validated via
        /// `RowPatchView::from_words` and applied directly via `Transaction::apply_row_patch`).
        row_patch_words: Vec<u32>,
        /// Positional `(text_index, new_text)` updates.
        text_updates: Vec<(usize, String)>,
        /// Exact `(old_text, new_text)` static text replacements scoped to the target.
        text_replacements: Vec<(String, String)>,
    },
    /// Tier 2 (150-400ms, desktop + iOS Simulator + Android):
    /// Instructs the host shell to hot-swap the compiled Rust app cdylib while preserving state.
    DylibReload {
        generation: u64,
        dylib_path: String,
        build_ms: u64,
    },
    /// Heartbeat / diagnostic banner sent to the live on-screen HUD.
    DevStatus {
        message: String,
        latency_ms: u64,
    },
    /// Client -> daemon acknowledgement emitted after a `TemplatePatch` or `DylibReload`
    /// has been applied (and presented, when a visible surface exists) or failed.
    ReloadAck {
        generation: u64,
        ok: bool,
        applied: bool,
        applied_ms: u64,
        detail: String,
    },
    /// Client -> daemon greeting sent immediately on WebSocket open (including after a Web
    /// Tier-2 `location.reload()`) so `nv dev` knows the host type and booted bundle hash.
    ClientHello {
        client_kind: String,
        bundle_hash: String,
        reloaded_generation: u64,
    },
}

impl HotPatchMsg {
    /// Encodes this hot-patch message into compact binary v2 framing.
    pub fn to_bytes(&self) -> Result<Vec<u8>, CodecError> {
        let mut w = ByteWriter::with_capacity(64);
        w.write_raw(&HOT_PATCH_WIRE_MAGIC);
        w.write_u8(HOT_PATCH_VERSION);
        match self {
            Self::TemplatePatch {
                generation,
                template_key,
                node_path,
                target_test_id,
                row_patch_words,
                text_updates,
                text_replacements,
            } => {
                w.write_u8(1);
                w.write_u64(*generation);
                w.write_u64(*template_key);

                w.write_len_max(node_path.len(), MAX_WIRE_ITEMS)?;
                for &step in node_path {
                    w.write_u16(step);
                }

                w.write_opt(target_test_id.as_deref(), |w, s| {
                    w.write_str_max(s, DEFAULT_MAX_BYTES)
                })?;

                w.write_len_max(row_patch_words.len(), MAX_WIRE_ITEMS)?;
                for &word in row_patch_words {
                    w.write_u32(word);
                }

                w.write_len_max(text_updates.len(), MAX_WIRE_ITEMS)?;
                for (idx, text) in text_updates {
                    w.write_len(*idx)?;
                    w.write_str_max(text, DEFAULT_MAX_BYTES)?;
                }

                w.write_len_max(text_replacements.len(), MAX_WIRE_ITEMS)?;
                for (old_text, new_text) in text_replacements {
                    w.write_str_max(old_text, DEFAULT_MAX_BYTES)?;
                    w.write_str_max(new_text, DEFAULT_MAX_BYTES)?;
                }
            }
            Self::DylibReload {
                generation,
                dylib_path,
                build_ms,
            } => {
                w.write_u8(2);
                w.write_u64(*generation);
                w.write_str_max(dylib_path, DEFAULT_MAX_BYTES)?;
                w.write_u64(*build_ms);
            }
            Self::DevStatus {
                message,
                latency_ms,
            } => {
                w.write_u8(3);
                w.write_str_max(message, DEFAULT_MAX_BYTES)?;
                w.write_u64(*latency_ms);
            }
            Self::ReloadAck {
                generation,
                ok,
                applied,
                applied_ms,
                detail,
            } => {
                w.write_u8(4);
                w.write_u64(*generation);
                w.write_bool(*ok);
                w.write_bool(*applied);
                w.write_u64(*applied_ms);
                w.write_str_max(detail, DEFAULT_MAX_BYTES)?;
            }
            Self::ClientHello {
                client_kind,
                bundle_hash,
                reloaded_generation,
            } => {
                w.write_u8(5);
                w.write_str_max(client_kind, DEFAULT_MAX_BYTES)?;
                w.write_str_max(bundle_hash, DEFAULT_MAX_BYTES)?;
                w.write_u64(*reloaded_generation);
            }
        }
        Ok(w.into_bytes())
    }

    /// Decodes a compact binary v2 hot-patch frame.
    pub fn from_bytes(raw: &[u8]) -> Result<Self, HotPatchDecodeError> {
        let mut r = ByteReader::new(raw);
        r.expect_magic(&HOT_PATCH_WIRE_MAGIC)?;
        let version = r.read_u8()?;
        if version != HOT_PATCH_VERSION {
            return Err(HotPatchDecodeError::UnsupportedVersion(version));
        }
        let variant = r.read_u8()?;
        let msg = match variant {
            1 => {
                let generation = r.read_u64()?;
                let template_key = r.read_u64()?;

                let node_path = r.read_vec(MAX_WIRE_ITEMS, 2, |r| r.read_u16())?;

                let target_test_id = r.read_opt(|r| r.read_string(DEFAULT_MAX_BYTES))?;

                let row_patch_words = r.read_vec(MAX_WIRE_ITEMS, 4, |r| r.read_u32())?;

                let text_updates = r.read_vec(MAX_WIRE_ITEMS, 8, |r| {
                    let idx = r.read_u32()? as usize;
                    let text = r.read_string(DEFAULT_MAX_BYTES)?;
                    Ok((idx, text))
                })?;

                let text_replacements = r.read_vec(MAX_WIRE_ITEMS, 8, |r| {
                    let old_t = r.read_string(DEFAULT_MAX_BYTES)?;
                    let new_t = r.read_string(DEFAULT_MAX_BYTES)?;
                    Ok((old_t, new_t))
                })?;

                Self::TemplatePatch {
                    generation,
                    template_key,
                    node_path,
                    target_test_id,
                    row_patch_words,
                    text_updates,
                    text_replacements,
                }
            }
            2 => Self::DylibReload {
                generation: r.read_u64()?,
                dylib_path: r.read_string(DEFAULT_MAX_BYTES)?,
                build_ms: r.read_u64()?,
            },
            3 => Self::DevStatus {
                message: r.read_string(DEFAULT_MAX_BYTES)?,
                latency_ms: r.read_u64()?,
            },
            4 => Self::ReloadAck {
                generation: r.read_u64()?,
                ok: r.read_bool()?,
                applied: r.read_bool()?,
                applied_ms: r.read_u64()?,
                detail: r.read_string(DEFAULT_MAX_BYTES)?,
            },
            5 => Self::ClientHello {
                client_kind: r.read_string(DEFAULT_MAX_BYTES)?,
                bundle_hash: r.read_string(DEFAULT_MAX_BYTES)?,
                reloaded_generation: r.read_u64()?,
            },
            other => return Err(HotPatchDecodeError::UnknownVariant(other)),
        };
        r.finish()?;
        Ok(msg)
    }
}

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

    #[test]
    fn hot_patch_v2_roundtrips_all_variants_and_rejects_corrupt_inputs() {
        let key = 0x5EED_0000_0000_0002_u64;
        let cases = vec![
            HotPatchMsg::TemplatePatch {
                generation: 42,
                template_key: key,
                node_path: vec![0, 2, 1],
                target_test_id: Some("studio-panel".into()),
                row_patch_words: vec![1, 0x1122_3344, 0x5566_7788, 1, 0, u32::MAX, 0x3F80_0000],
                text_updates: vec![(0, "AETHER".into()), (3, "東京テスト".into())],
                text_replacements: vec![("Old".into(), "New".into())],
            },
            HotPatchMsg::TemplatePatch {
                generation: 1,
                template_key: 0,
                node_path: vec![],
                target_test_id: None,
                row_patch_words: vec![],
                text_updates: vec![],
                text_replacements: vec![],
            },
            HotPatchMsg::DylibReload {
                generation: 99,
                dylib_path: "target/debug/libnativeview_studio_workspace.dylib".into(),
                build_ms: 287,
            },
            HotPatchMsg::DevStatus {
                message: "watching 4 crates".into(),
                latency_ms: 8,
            },
            HotPatchMsg::ReloadAck {
                generation: 99,
                ok: true,
                applied: true,
                applied_ms: 14,
                detail: String::new(),
            },
            HotPatchMsg::ReloadAck {
                generation: 100,
                ok: false,
                applied: false,
                applied_ms: 3,
                detail: "dlopen failed".into(),
            },
            HotPatchMsg::ClientHello {
                client_kind: "web".into(),
                bundle_hash: "a1b2c3d4e5f60718".into(),
                reloaded_generation: 99,
            },
        ];

        for msg in &cases {
            let bin = msg.to_bytes().unwrap();
            assert!(bin.starts_with(&HOT_PATCH_WIRE_MAGIC));
            assert_eq!(bin[HOT_PATCH_WIRE_MAGIC.len()], HOT_PATCH_VERSION);
            assert_eq!(HotPatchMsg::from_bytes(&bin).unwrap(), *msg);
            for cut in 0..bin.len() {
                assert_eq!(
                    HotPatchMsg::from_bytes(&bin[..cut]),
                    Err(HotPatchDecodeError::Truncated)
                );
            }
            let mut extended = bin.clone();
            extended.push(0xAA);
            assert_eq!(
                HotPatchMsg::from_bytes(&extended),
                Err(HotPatchDecodeError::TrailingBytes(1))
            );
        }

        assert_eq!(
            HotPatchMsg::from_bytes(b"WRONG_MAGIC_1234\x02\x01"),
            Err(HotPatchDecodeError::InvalidMagic)
        );
        // Older v1 frames (version byte = 1) are rejected cleanly as UnsupportedVersion.
        let mut bad_ver = Vec::from(HOT_PATCH_WIRE_MAGIC);
        bad_ver.extend_from_slice(&[1, 1]);
        assert_eq!(
            HotPatchMsg::from_bytes(&bad_ver),
            Err(HotPatchDecodeError::UnsupportedVersion(1))
        );
        let mut bad_var = Vec::from(HOT_PATCH_WIRE_MAGIC);
        bad_var.extend_from_slice(&[HOT_PATCH_VERSION, 0xFF]);
        assert_eq!(
            HotPatchMsg::from_bytes(&bad_var),
            Err(HotPatchDecodeError::UnknownVariant(0xFF))
        );
        let mut bad_oom = Vec::from(HOT_PATCH_WIRE_MAGIC);
        bad_oom.push(HOT_PATCH_VERSION);
        bad_oom.push(1);
        bad_oom.extend_from_slice(&1u64.to_le_bytes()); // generation
        bad_oom.extend_from_slice(&0u64.to_le_bytes()); // template_key
        bad_oom.extend_from_slice(&(u32::MAX).to_le_bytes()); // node_path len
        assert_eq!(
            HotPatchMsg::from_bytes(&bad_oom),
            Err(HotPatchDecodeError::LimitExceeded)
        );
        assert_eq!(
            HotPatchMsg::from_bytes(br#"{"type":"dev_status","message":"x","latency_ms":0}"#),
            Err(HotPatchDecodeError::InvalidMagic)
        );
        let mut bad_utf8 = Vec::from(HOT_PATCH_WIRE_MAGIC);
        bad_utf8.push(HOT_PATCH_VERSION);
        bad_utf8.push(3);
        bad_utf8.extend_from_slice(&2u32.to_le_bytes());
        bad_utf8.extend_from_slice(&[0xFF, 0xFE]);
        bad_utf8.extend_from_slice(&0u64.to_le_bytes());
        assert_eq!(
            HotPatchMsg::from_bytes(&bad_utf8),
            Err(HotPatchDecodeError::InvalidUtf8)
        );
        let mut bad_bool = Vec::from(HOT_PATCH_WIRE_MAGIC);
        bad_bool.push(HOT_PATCH_VERSION);
        bad_bool.push(1);
        bad_bool.extend_from_slice(&1u64.to_le_bytes()); // generation
        bad_bool.extend_from_slice(&0u64.to_le_bytes()); // template_key
        bad_bool.extend_from_slice(&0u32.to_le_bytes()); // node_path len = 0
        bad_bool.push(7); // invalid Option tag for target_test_id
        assert_eq!(
            HotPatchMsg::from_bytes(&bad_bool),
            Err(HotPatchDecodeError::InvalidBool(7))
        );

        // Encode-side cap matches decoder MAX_WIRE_ITEMS so oversized frames fail at encode time.
        let oversized = HotPatchMsg::TemplatePatch {
            generation: 1,
            template_key: 0,
            node_path: vec![0; MAX_WIRE_ITEMS + 1],
            target_test_id: None,
            row_patch_words: vec![],
            text_updates: vec![],
            text_replacements: vec![],
        };
        assert_eq!(
            oversized.to_bytes(),
            Err(CodecError::LenOverflow {
                len: MAX_WIRE_ITEMS + 1,
                max: MAX_WIRE_ITEMS,
            })
        );
    }
}